SemaHLSL.cpp 445 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875
  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. AR_BASIC_DEPENDENT,
  72. //
  73. // The following pseudo-entries represent higher-level
  74. // object types that are treated as units.
  75. //
  76. AR_BASIC_POINTER,
  77. AR_BASIC_ENUM_CLASS,
  78. AR_OBJECT_NULL,
  79. AR_OBJECT_STRING_LITERAL,
  80. AR_OBJECT_STRING,
  81. // AR_OBJECT_TEXTURE,
  82. AR_OBJECT_TEXTURE1D,
  83. AR_OBJECT_TEXTURE1D_ARRAY,
  84. AR_OBJECT_TEXTURE2D,
  85. AR_OBJECT_TEXTURE2D_ARRAY,
  86. AR_OBJECT_TEXTURE3D,
  87. AR_OBJECT_TEXTURECUBE,
  88. AR_OBJECT_TEXTURECUBE_ARRAY,
  89. AR_OBJECT_TEXTURE2DMS,
  90. AR_OBJECT_TEXTURE2DMS_ARRAY,
  91. AR_OBJECT_SAMPLER,
  92. AR_OBJECT_SAMPLER1D,
  93. AR_OBJECT_SAMPLER2D,
  94. AR_OBJECT_SAMPLER3D,
  95. AR_OBJECT_SAMPLERCUBE,
  96. AR_OBJECT_SAMPLERCOMPARISON,
  97. AR_OBJECT_BUFFER,
  98. //
  99. // View objects are only used as variable/types within the Effects
  100. // framework, for example in calls to OMSetRenderTargets.
  101. //
  102. AR_OBJECT_RENDERTARGETVIEW,
  103. AR_OBJECT_DEPTHSTENCILVIEW,
  104. //
  105. // Shader objects are only used as variable/types within the Effects
  106. // framework, for example as a result of CompileShader().
  107. //
  108. AR_OBJECT_COMPUTESHADER,
  109. AR_OBJECT_DOMAINSHADER,
  110. AR_OBJECT_GEOMETRYSHADER,
  111. AR_OBJECT_HULLSHADER,
  112. AR_OBJECT_PIXELSHADER,
  113. AR_OBJECT_VERTEXSHADER,
  114. AR_OBJECT_PIXELFRAGMENT,
  115. AR_OBJECT_VERTEXFRAGMENT,
  116. AR_OBJECT_STATEBLOCK,
  117. AR_OBJECT_RASTERIZER,
  118. AR_OBJECT_DEPTHSTENCIL,
  119. AR_OBJECT_BLEND,
  120. AR_OBJECT_POINTSTREAM,
  121. AR_OBJECT_LINESTREAM,
  122. AR_OBJECT_TRIANGLESTREAM,
  123. AR_OBJECT_INPUTPATCH,
  124. AR_OBJECT_OUTPUTPATCH,
  125. AR_OBJECT_RWTEXTURE1D,
  126. AR_OBJECT_RWTEXTURE1D_ARRAY,
  127. AR_OBJECT_RWTEXTURE2D,
  128. AR_OBJECT_RWTEXTURE2D_ARRAY,
  129. AR_OBJECT_RWTEXTURE3D,
  130. AR_OBJECT_RWBUFFER,
  131. AR_OBJECT_BYTEADDRESS_BUFFER,
  132. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  133. AR_OBJECT_STRUCTURED_BUFFER,
  134. AR_OBJECT_RWSTRUCTURED_BUFFER,
  135. AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  136. AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  137. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  138. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  139. AR_OBJECT_CONSTANT_BUFFER,
  140. AR_OBJECT_TEXTURE_BUFFER,
  141. AR_OBJECT_ROVBUFFER,
  142. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  143. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  144. AR_OBJECT_ROVTEXTURE1D,
  145. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  146. AR_OBJECT_ROVTEXTURE2D,
  147. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  148. AR_OBJECT_ROVTEXTURE3D,
  149. AR_OBJECT_FEEDBACKTEXTURE2D,
  150. AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY,
  151. // SPIRV change starts
  152. #ifdef ENABLE_SPIRV_CODEGEN
  153. AR_OBJECT_VK_SUBPASS_INPUT,
  154. AR_OBJECT_VK_SUBPASS_INPUT_MS,
  155. #endif // ENABLE_SPIRV_CODEGEN
  156. // SPIRV change ends
  157. AR_OBJECT_INNER, // Used for internal type object
  158. AR_OBJECT_LEGACY_EFFECT,
  159. AR_OBJECT_WAVE,
  160. AR_OBJECT_RAY_DESC,
  161. AR_OBJECT_ACCELERATION_STRUCT,
  162. AR_OBJECT_USER_DEFINED_TYPE,
  163. AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES,
  164. // subobjects
  165. AR_OBJECT_STATE_OBJECT_CONFIG,
  166. AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  167. AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  168. AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  169. AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  170. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  171. AR_OBJECT_TRIANGLE_HIT_GROUP,
  172. AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  173. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  174. // RayQuery
  175. AR_OBJECT_RAY_QUERY,
  176. // Resource
  177. AR_OBJECT_RESOURCE,
  178. AR_BASIC_MAXIMUM_COUNT
  179. };
  180. #define AR_BASIC_TEXTURE_MS_CASES \
  181. case AR_OBJECT_TEXTURE2DMS: \
  182. case AR_OBJECT_TEXTURE2DMS_ARRAY
  183. #define AR_BASIC_NON_TEXTURE_MS_CASES \
  184. case AR_OBJECT_TEXTURE1D: \
  185. case AR_OBJECT_TEXTURE1D_ARRAY: \
  186. case AR_OBJECT_TEXTURE2D: \
  187. case AR_OBJECT_TEXTURE2D_ARRAY: \
  188. case AR_OBJECT_TEXTURE3D: \
  189. case AR_OBJECT_TEXTURECUBE: \
  190. case AR_OBJECT_TEXTURECUBE_ARRAY
  191. #define AR_BASIC_TEXTURE_CASES \
  192. AR_BASIC_TEXTURE_MS_CASES: \
  193. AR_BASIC_NON_TEXTURE_MS_CASES
  194. #define AR_BASIC_NON_CMP_SAMPLER_CASES \
  195. case AR_OBJECT_SAMPLER: \
  196. case AR_OBJECT_SAMPLER1D: \
  197. case AR_OBJECT_SAMPLER2D: \
  198. case AR_OBJECT_SAMPLER3D: \
  199. case AR_OBJECT_SAMPLERCUBE
  200. #define AR_BASIC_ROBJECT_CASES \
  201. case AR_OBJECT_BLEND: \
  202. case AR_OBJECT_RASTERIZER: \
  203. case AR_OBJECT_DEPTHSTENCIL: \
  204. case AR_OBJECT_STATEBLOCK
  205. //
  206. // Properties of entries in the ArBasicKind enumeration.
  207. // These properties are intended to allow easy identification
  208. // of classes of basic kinds. More specific checks on the
  209. // actual kind values could then be done.
  210. //
  211. // The first four bits are used as a subtype indicator,
  212. // such as bit count for primitive kinds or specific
  213. // types for non-primitive-data kinds.
  214. #define BPROP_SUBTYPE_MASK 0x0000000f
  215. // Bit counts must be ordered from smaller to larger.
  216. #define BPROP_BITS0 0x00000000
  217. #define BPROP_BITS8 0x00000001
  218. #define BPROP_BITS10 0x00000002
  219. #define BPROP_BITS12 0x00000003
  220. #define BPROP_BITS16 0x00000004
  221. #define BPROP_BITS32 0x00000005
  222. #define BPROP_BITS64 0x00000006
  223. #define BPROP_BITS_NON_PRIM 0x00000007
  224. #define GET_BPROP_SUBTYPE(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  225. #define GET_BPROP_BITS(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  226. #define BPROP_BOOLEAN 0x00000010 // Whether the type is bool
  227. #define BPROP_INTEGER 0x00000020 // Whether the type is an integer
  228. #define BPROP_UNSIGNED 0x00000040 // Whether the type is an unsigned numeric (its absence implies signed)
  229. #define BPROP_NUMERIC 0x00000080 // Whether the type is numeric or boolean
  230. #define BPROP_LITERAL 0x00000100 // Whether the type is a literal float or integer
  231. #define BPROP_FLOATING 0x00000200 // Whether the type is a float
  232. #define BPROP_OBJECT 0x00000400 // Whether the type is an object (including null or stream)
  233. #define BPROP_OTHER 0x00000800 // Whether the type is a pseudo-entry in another table.
  234. #define BPROP_PARTIAL_PRECISION 0x00001000 // Whether the type has partial precision for calculations (i.e., is this 'half')
  235. #define BPROP_POINTER 0x00002000 // Whether the type is a basic pointer.
  236. #define BPROP_TEXTURE 0x00004000 // Whether the type is any kind of texture.
  237. #define BPROP_SAMPLER 0x00008000 // Whether the type is any kind of sampler object.
  238. #define BPROP_STREAM 0x00010000 // Whether the type is a point, line or triangle stream.
  239. #define BPROP_PATCH 0x00020000 // Whether the type is an input or output patch.
  240. #define BPROP_RBUFFER 0x00040000 // Whether the type acts as a read-only buffer.
  241. #define BPROP_RWBUFFER 0x00080000 // Whether the type acts as a read-write buffer.
  242. #define BPROP_PRIMITIVE 0x00100000 // Whether the type is a primitive scalar type.
  243. #define BPROP_MIN_PRECISION 0x00200000 // Whether the type is qualified with a minimum precision.
  244. #define BPROP_ROVBUFFER 0x00400000 // Whether the type is a ROV object.
  245. #define BPROP_FEEDBACKTEXTURE 0x00800000 // Whether the type is a feedback texture.
  246. #define BPROP_ENUM 0x01000000 // Whether the type is a enum
  247. #define GET_BPROP_PRIM_KIND(_Props) \
  248. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING))
  249. #define GET_BPROP_PRIM_KIND_SU(_Props) \
  250. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING | BPROP_UNSIGNED))
  251. #define IS_BPROP_PRIMITIVE(_Props) \
  252. (((_Props) & BPROP_PRIMITIVE) != 0)
  253. #define IS_BPROP_BOOL(_Props) \
  254. (((_Props) & BPROP_BOOLEAN) != 0)
  255. #define IS_BPROP_FLOAT(_Props) \
  256. (((_Props) & BPROP_FLOATING) != 0)
  257. #define IS_BPROP_SINT(_Props) \
  258. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  259. BPROP_INTEGER)
  260. #define IS_BPROP_UINT(_Props) \
  261. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  262. (BPROP_INTEGER | BPROP_UNSIGNED))
  263. #define IS_BPROP_AINT(_Props) \
  264. (((_Props) & (BPROP_INTEGER | BPROP_BOOLEAN)) == BPROP_INTEGER)
  265. #define IS_BPROP_STREAM(_Props) \
  266. (((_Props) & BPROP_STREAM) != 0)
  267. #define IS_BPROP_SAMPLER(_Props) \
  268. (((_Props) & BPROP_SAMPLER) != 0)
  269. #define IS_BPROP_TEXTURE(_Props) \
  270. (((_Props) & BPROP_TEXTURE) != 0)
  271. #define IS_BPROP_OBJECT(_Props) \
  272. (((_Props) & BPROP_OBJECT) != 0)
  273. #define IS_BPROP_MIN_PRECISION(_Props) \
  274. (((_Props) & BPROP_MIN_PRECISION) != 0)
  275. #define IS_BPROP_UNSIGNABLE(_Props) \
  276. (IS_BPROP_AINT(_Props) && GET_BPROP_BITS(_Props) != BPROP_BITS12)
  277. #define IS_BPROP_ENUM(_Props) \
  278. (((_Props) & BPROP_ENUM) != 0)
  279. const UINT g_uBasicKindProps[] =
  280. {
  281. BPROP_PRIMITIVE | BPROP_BOOLEAN | BPROP_INTEGER | BPROP_NUMERIC | BPROP_BITS0, // AR_BASIC_BOOL
  282. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_FLOAT
  283. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16, // AR_BASIC_FLOAT16
  284. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32 | BPROP_PARTIAL_PRECISION, // AR_BASIC_FLOAT32_PARTIAL_PRECISION
  285. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32, // AR_BASIC_FLOAT32
  286. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS64, // AR_BASIC_FLOAT64
  287. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_INT
  288. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS8, // AR_BASIC_INT8
  289. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS8, // AR_BASIC_UINT8
  290. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16, // AR_BASIC_INT16
  291. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16,// AR_BASIC_UINT16
  292. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS32, // AR_BASIC_INT32
  293. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS32,// AR_BASIC_UINT32
  294. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS64, // AR_BASIC_INT64
  295. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS64,// AR_BASIC_UINT64
  296. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS10 | BPROP_MIN_PRECISION, // AR_BASIC_MIN10FLOAT
  297. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16FLOAT
  298. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS12 | BPROP_MIN_PRECISION, // AR_BASIC_MIN12INT
  299. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16INT
  300. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16UINT
  301. BPROP_ENUM | BPROP_NUMERIC | BPROP_INTEGER, // AR_BASIC_ENUM
  302. BPROP_OTHER, // AR_BASIC_COUNT
  303. //
  304. // Pseudo-entries for intrinsic tables and such.
  305. //
  306. 0, // AR_BASIC_NONE
  307. BPROP_OTHER, // AR_BASIC_UNKNOWN
  308. BPROP_OTHER, // AR_BASIC_NOCAST
  309. 0, // AR_BASIC_DEPENDENT
  310. //
  311. // The following pseudo-entries represent higher-level
  312. // object types that are treated as units.
  313. //
  314. BPROP_POINTER, // AR_BASIC_POINTER
  315. BPROP_ENUM, // AR_BASIC_ENUM_CLASS
  316. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_NULL
  317. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRING_LITERAL
  318. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRING
  319. // BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE
  320. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D
  321. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D_ARRAY
  322. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D
  323. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D_ARRAY
  324. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE3D
  325. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE
  326. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE_ARRAY
  327. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS
  328. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS_ARRAY
  329. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER
  330. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER1D
  331. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER2D
  332. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER3D
  333. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCUBE
  334. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCOMPARISON
  335. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BUFFER
  336. BPROP_OBJECT, // AR_OBJECT_RENDERTARGETVIEW
  337. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCILVIEW
  338. BPROP_OBJECT, // AR_OBJECT_COMPUTESHADER
  339. BPROP_OBJECT, // AR_OBJECT_DOMAINSHADER
  340. BPROP_OBJECT, // AR_OBJECT_GEOMETRYSHADER
  341. BPROP_OBJECT, // AR_OBJECT_HULLSHADER
  342. BPROP_OBJECT, // AR_OBJECT_PIXELSHADER
  343. BPROP_OBJECT, // AR_OBJECT_VERTEXSHADER
  344. BPROP_OBJECT, // AR_OBJECT_PIXELFRAGMENT
  345. BPROP_OBJECT, // AR_OBJECT_VERTEXFRAGMENT
  346. BPROP_OBJECT, // AR_OBJECT_STATEBLOCK
  347. BPROP_OBJECT, // AR_OBJECT_RASTERIZER
  348. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCIL
  349. BPROP_OBJECT, // AR_OBJECT_BLEND
  350. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_POINTSTREAM
  351. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_LINESTREAM
  352. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_TRIANGLESTREAM
  353. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_INPUTPATCH
  354. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_OUTPUTPATCH
  355. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D
  356. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D_ARRAY
  357. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D
  358. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D_ARRAY
  359. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE3D
  360. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBUFFER
  361. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BYTEADDRESS_BUFFER
  362. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  363. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRUCTURED_BUFFER
  364. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER
  365. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  366. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  367. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  368. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  369. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_CONSTANT_BUFFER
  370. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_TEXTURE_BUFFER
  371. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBUFFER
  372. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  373. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  374. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D
  375. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  376. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D
  377. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  378. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE3D
  379. BPROP_OBJECT | BPROP_TEXTURE | BPROP_FEEDBACKTEXTURE, // AR_OBJECT_FEEDBACKTEXTURE2D
  380. BPROP_OBJECT | BPROP_TEXTURE | BPROP_FEEDBACKTEXTURE, // AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY
  381. // SPIRV change starts
  382. #ifdef ENABLE_SPIRV_CODEGEN
  383. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_VK_SUBPASS_INPUT
  384. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_VK_SUBPASS_INPUT_MS
  385. #endif // ENABLE_SPIRV_CODEGEN
  386. // SPIRV change ends
  387. BPROP_OBJECT, // AR_OBJECT_INNER
  388. BPROP_OBJECT, // AR_OBJECT_LEGACY_EFFECT
  389. BPROP_OBJECT, // AR_OBJECT_WAVE
  390. LICOMPTYPE_RAYDESC, // AR_OBJECT_RAY_DESC
  391. LICOMPTYPE_ACCELERATION_STRUCT, // AR_OBJECT_ACCELERATION_STRUCT
  392. LICOMPTYPE_USER_DEFINED_TYPE, // AR_OBJECT_USER_DEFINED_TYPE
  393. 0, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  394. // subobjects
  395. 0, //AR_OBJECT_STATE_OBJECT_CONFIG,
  396. 0, //AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  397. 0, //AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  398. 0, //AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  399. 0, //AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  400. 0, //AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  401. 0, //AR_OBJECT_TRIANGLE_HIT_GROUP,
  402. 0, //AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  403. 0, //AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  404. 0, //AR_OBJECT_RAY_QUERY,
  405. 0, //AR_OBJECT_RESOURCE,
  406. // AR_BASIC_MAXIMUM_COUNT
  407. };
  408. C_ASSERT(ARRAYSIZE(g_uBasicKindProps) == AR_BASIC_MAXIMUM_COUNT);
  409. #define GetBasicKindProps(_Kind) g_uBasicKindProps[(_Kind)]
  410. #define GET_BASIC_BITS(_Kind) \
  411. GET_BPROP_BITS(GetBasicKindProps(_Kind))
  412. #define GET_BASIC_PRIM_KIND(_Kind) \
  413. GET_BPROP_PRIM_KIND(GetBasicKindProps(_Kind))
  414. #define GET_BASIC_PRIM_KIND_SU(_Kind) \
  415. GET_BPROP_PRIM_KIND_SU(GetBasicKindProps(_Kind))
  416. #define IS_BASIC_PRIMITIVE(_Kind) \
  417. IS_BPROP_PRIMITIVE(GetBasicKindProps(_Kind))
  418. #define IS_BASIC_BOOL(_Kind) \
  419. IS_BPROP_BOOL(GetBasicKindProps(_Kind))
  420. #define IS_BASIC_FLOAT(_Kind) \
  421. IS_BPROP_FLOAT(GetBasicKindProps(_Kind))
  422. #define IS_BASIC_SINT(_Kind) \
  423. IS_BPROP_SINT(GetBasicKindProps(_Kind))
  424. #define IS_BASIC_UINT(_Kind) \
  425. IS_BPROP_UINT(GetBasicKindProps(_Kind))
  426. #define IS_BASIC_AINT(_Kind) \
  427. IS_BPROP_AINT(GetBasicKindProps(_Kind))
  428. #define IS_BASIC_STREAM(_Kind) \
  429. IS_BPROP_STREAM(GetBasicKindProps(_Kind))
  430. #define IS_BASIC_SAMPLER(_Kind) \
  431. IS_BPROP_SAMPLER(GetBasicKindProps(_Kind))
  432. #define IS_BASIC_TEXTURE(_Kind) \
  433. IS_BPROP_TEXTURE(GetBasicKindProps(_Kind))
  434. #define IS_BASIC_OBJECT(_Kind) \
  435. IS_BPROP_OBJECT(GetBasicKindProps(_Kind))
  436. #define IS_BASIC_MIN_PRECISION(_Kind) \
  437. IS_BPROP_MIN_PRECISION(GetBasicKindProps(_Kind))
  438. #define IS_BASIC_UNSIGNABLE(_Kind) \
  439. IS_BPROP_UNSIGNABLE(GetBasicKindProps(_Kind))
  440. #define IS_BASIC_ENUM(_Kind) \
  441. IS_BPROP_ENUM(GetBasicKindProps(_Kind))
  442. #define BITWISE_ENUM_OPS(_Type) \
  443. inline _Type operator|(_Type F1, _Type F2) \
  444. { \
  445. return (_Type)((UINT)F1 | (UINT)F2); \
  446. } \
  447. inline _Type operator&(_Type F1, _Type F2) \
  448. { \
  449. return (_Type)((UINT)F1 & (UINT)F2); \
  450. } \
  451. inline _Type& operator|=(_Type& F1, _Type F2) \
  452. { \
  453. F1 = F1 | F2; \
  454. return F1; \
  455. } \
  456. inline _Type& operator&=(_Type& F1, _Type F2) \
  457. { \
  458. F1 = F1 & F2; \
  459. return F1; \
  460. } \
  461. inline _Type& operator&=(_Type& F1, UINT F2) \
  462. { \
  463. F1 = (_Type)((UINT)F1 & F2); \
  464. return F1; \
  465. }
  466. enum ArTypeObjectKind {
  467. AR_TOBJ_INVALID, // Flag for an unassigned / unavailable object type.
  468. AR_TOBJ_VOID, // Represents the type for functions with not returned valued.
  469. AR_TOBJ_BASIC, // Represents a primitive type.
  470. AR_TOBJ_COMPOUND, // Represents a struct or class.
  471. AR_TOBJ_INTERFACE, // Represents an interface.
  472. AR_TOBJ_POINTER, // Represents a pointer to another type.
  473. AR_TOBJ_OBJECT, // Represents a built-in object.
  474. AR_TOBJ_ARRAY, // Represents an array of other types.
  475. AR_TOBJ_MATRIX, // Represents a matrix of basic types.
  476. AR_TOBJ_VECTOR, // Represents a vector of basic types.
  477. AR_TOBJ_QUALIFIER, // Represents another type plus an ArTypeQualifier.
  478. AR_TOBJ_INNER_OBJ, // Represents a built-in inner object, such as an
  479. // indexer object used to implement .mips[1].
  480. AR_TOBJ_STRING, // Represents a string
  481. AR_TOBJ_DEPENDENT, // Dependent type for template.
  482. };
  483. enum TYPE_CONVERSION_FLAGS
  484. {
  485. TYPE_CONVERSION_DEFAULT = 0x00000000, // Indicates an implicit conversion is done.
  486. TYPE_CONVERSION_EXPLICIT = 0x00000001, // Indicates a conversion is done through an explicit cast.
  487. TYPE_CONVERSION_BY_REFERENCE = 0x00000002, // Indicates a conversion is done to an output parameter.
  488. };
  489. enum TYPE_CONVERSION_REMARKS
  490. {
  491. TYPE_CONVERSION_NONE = 0x00000000,
  492. TYPE_CONVERSION_PRECISION_LOSS = 0x00000001,
  493. TYPE_CONVERSION_IDENTICAL = 0x00000002,
  494. TYPE_CONVERSION_TO_VOID = 0x00000004,
  495. TYPE_CONVERSION_ELT_TRUNCATION = 0x00000008,
  496. };
  497. BITWISE_ENUM_OPS(TYPE_CONVERSION_REMARKS)
  498. #define AR_TOBJ_SCALAR AR_TOBJ_BASIC
  499. #define AR_TOBJ_UNKNOWN AR_TOBJ_INVALID
  500. #define AR_TPROP_VOID 0x0000000000000001
  501. #define AR_TPROP_CONST 0x0000000000000002
  502. #define AR_TPROP_IMP_CONST 0x0000000000000004
  503. #define AR_TPROP_OBJECT 0x0000000000000008
  504. #define AR_TPROP_SCALAR 0x0000000000000010
  505. #define AR_TPROP_UNSIGNED 0x0000000000000020
  506. #define AR_TPROP_NUMERIC 0x0000000000000040
  507. #define AR_TPROP_INTEGRAL 0x0000000000000080
  508. #define AR_TPROP_FLOATING 0x0000000000000100
  509. #define AR_TPROP_LITERAL 0x0000000000000200
  510. #define AR_TPROP_POINTER 0x0000000000000400
  511. #define AR_TPROP_INPUT_PATCH 0x0000000000000800
  512. #define AR_TPROP_OUTPUT_PATCH 0x0000000000001000
  513. #define AR_TPROP_INH_IFACE 0x0000000000002000
  514. #define AR_TPROP_HAS_COMPOUND 0x0000000000004000
  515. #define AR_TPROP_HAS_TEXTURES 0x0000000000008000
  516. #define AR_TPROP_HAS_SAMPLERS 0x0000000000010000
  517. #define AR_TPROP_HAS_SAMPLER_CMPS 0x0000000000020000
  518. #define AR_TPROP_HAS_STREAMS 0x0000000000040000
  519. #define AR_TPROP_HAS_OTHER_OBJECTS 0x0000000000080000
  520. #define AR_TPROP_HAS_BASIC 0x0000000000100000
  521. #define AR_TPROP_HAS_BUFFERS 0x0000000000200000
  522. #define AR_TPROP_HAS_ROBJECTS 0x0000000000400000
  523. #define AR_TPROP_HAS_POINTERS 0x0000000000800000
  524. #define AR_TPROP_INDEXABLE 0x0000000001000000
  525. #define AR_TPROP_HAS_MIPS 0x0000000002000000
  526. #define AR_TPROP_WRITABLE_GLOBAL 0x0000000004000000
  527. #define AR_TPROP_HAS_UAVS 0x0000000008000000
  528. #define AR_TPROP_HAS_BYTEADDRESS 0x0000000010000000
  529. #define AR_TPROP_HAS_STRUCTURED 0x0000000020000000
  530. #define AR_TPROP_HAS_SAMPLE 0x0000000040000000
  531. #define AR_TPROP_MIN_PRECISION 0x0000000080000000
  532. #define AR_TPROP_HAS_CBUFFERS 0x0000000100008000
  533. #define AR_TPROP_HAS_TBUFFERS 0x0000000200008000
  534. #define AR_TPROP_ALL 0xffffffffffffffff
  535. #define AR_TPROP_HAS_OBJECTS \
  536. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  537. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_STREAMS | \
  538. AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BUFFERS | \
  539. AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_UAVS | \
  540. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED)
  541. #define AR_TPROP_HAS_BASIC_RESOURCES \
  542. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  543. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_BUFFERS | \
  544. AR_TPROP_HAS_UAVS)
  545. #define AR_TPROP_UNION_BITS \
  546. (AR_TPROP_INH_IFACE | AR_TPROP_HAS_COMPOUND | AR_TPROP_HAS_TEXTURES | \
  547. AR_TPROP_HAS_SAMPLERS | AR_TPROP_HAS_SAMPLER_CMPS | \
  548. AR_TPROP_HAS_STREAMS | AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BASIC | \
  549. AR_TPROP_HAS_BUFFERS | AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_POINTERS | \
  550. AR_TPROP_WRITABLE_GLOBAL | AR_TPROP_HAS_UAVS | \
  551. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED | AR_TPROP_MIN_PRECISION)
  552. #define AR_TINFO_ALLOW_COMPLEX 0x00000001
  553. #define AR_TINFO_ALLOW_OBJECTS 0x00000002
  554. #define AR_TINFO_IGNORE_QUALIFIERS 0x00000004
  555. #define AR_TINFO_OBJECTS_AS_ELEMENTS 0x00000008
  556. #define AR_TINFO_PACK_SCALAR 0x00000010
  557. #define AR_TINFO_PACK_ROW_MAJOR 0x00000020
  558. #define AR_TINFO_PACK_TEMP_ARRAY 0x00000040
  559. #define AR_TINFO_ALL_VAR_INFO 0x00000080
  560. #define AR_TINFO_ALLOW_ALL (AR_TINFO_ALLOW_COMPLEX | AR_TINFO_ALLOW_OBJECTS)
  561. #define AR_TINFO_PACK_CBUFFER 0
  562. #define AR_TINFO_LAYOUT_PACK_ALL (AR_TINFO_PACK_SCALAR | AR_TINFO_PACK_TEMP_ARRAY)
  563. #define AR_TINFO_SIMPLE_OBJECTS \
  564. (AR_TINFO_ALLOW_OBJECTS | AR_TINFO_OBJECTS_AS_ELEMENTS)
  565. struct ArTypeInfo {
  566. ArTypeObjectKind ShapeKind; // The shape of the type (basic, matrix, etc.)
  567. ArBasicKind EltKind; // The primitive type of elements in this type.
  568. ArBasicKind ObjKind; // The object type for this type (textures, buffers, etc.)
  569. UINT uRows;
  570. UINT uCols;
  571. UINT uTotalElts;
  572. };
  573. using namespace clang;
  574. using namespace clang::sema;
  575. using namespace hlsl;
  576. extern const char *HLSLScalarTypeNames[];
  577. static const bool ExplicitConversionFalse = false;// a conversion operation is not the result of an explicit cast
  578. static const bool ParameterPackFalse = false; // template parameter is not an ellipsis.
  579. static const bool TypenameTrue = false; // 'typename' specified rather than 'class' for a template argument.
  580. static const bool DelayTypeCreationTrue = true; // delay type creation for a declaration
  581. static const SourceLocation NoLoc; // no source location attribution available
  582. static const SourceRange NoRange; // no source range attribution available
  583. static const bool HasWrittenPrototypeTrue = true; // function had the prototype written
  584. static const bool InlineSpecifiedFalse = false; // function was not specified as inline
  585. static const bool IsConstexprFalse = false; // function is not constexpr
  586. static const bool ListInitializationFalse = false;// not performing a list initialization
  587. static const bool SuppressWarningsFalse = false; // do not suppress warning diagnostics
  588. static const bool SuppressErrorsTrue = true; // suppress error diagnostics
  589. static const bool SuppressErrorsFalse = false; // do not suppress error diagnostics
  590. static const int OneRow = 1; // a single row for a type
  591. static const bool MipsFalse = false; // a type does not support the .mips member
  592. static const bool MipsTrue = true; // a type supports the .mips member
  593. static const bool SampleFalse = false; // a type does not support the .sample member
  594. static const bool SampleTrue = true; // a type supports the .sample member
  595. static const size_t MaxVectorSize = 4; // maximum size for a vector
  596. static
  597. QualType GetOrCreateTemplateSpecialization(
  598. ASTContext& context,
  599. Sema& sema,
  600. _In_ ClassTemplateDecl* templateDecl,
  601. ArrayRef<TemplateArgument> templateArgs
  602. )
  603. {
  604. DXASSERT_NOMSG(templateDecl);
  605. DeclContext* currentDeclContext = context.getTranslationUnitDecl();
  606. SmallVector<TemplateArgument, 3> templateArgsForDecl;
  607. for (const TemplateArgument& Arg : templateArgs) {
  608. if (Arg.getKind() == TemplateArgument::Type) {
  609. // the class template need to use CanonicalType
  610. templateArgsForDecl.emplace_back(TemplateArgument(Arg.getAsType().getCanonicalType()));
  611. }else
  612. templateArgsForDecl.emplace_back(Arg);
  613. }
  614. // First, try looking up existing specialization
  615. void* InsertPos = nullptr;
  616. ClassTemplateSpecializationDecl* specializationDecl =
  617. templateDecl->findSpecialization(templateArgsForDecl, InsertPos);
  618. if (specializationDecl) {
  619. // Instantiate the class template if not yet.
  620. if (specializationDecl->getInstantiatedFrom().isNull()) {
  621. // InstantiateClassTemplateSpecialization returns true if it finds an
  622. // error.
  623. DXVERIFY_NOMSG(false ==
  624. sema.InstantiateClassTemplateSpecialization(
  625. NoLoc, specializationDecl,
  626. TemplateSpecializationKind::TSK_ImplicitInstantiation,
  627. true));
  628. }
  629. return context.getTemplateSpecializationType(
  630. TemplateName(templateDecl), templateArgs.data(), templateArgs.size(),
  631. context.getTypeDeclType(specializationDecl));
  632. }
  633. specializationDecl = ClassTemplateSpecializationDecl::Create(
  634. context, TagDecl::TagKind::TTK_Class, currentDeclContext, NoLoc, NoLoc,
  635. templateDecl, templateArgsForDecl.data(), templateArgsForDecl.size(), nullptr);
  636. // InstantiateClassTemplateSpecialization returns true if it finds an error.
  637. DXVERIFY_NOMSG(false == sema.InstantiateClassTemplateSpecialization(
  638. NoLoc, specializationDecl, TemplateSpecializationKind::TSK_ImplicitInstantiation, true));
  639. templateDecl->AddSpecialization(specializationDecl, InsertPos);
  640. specializationDecl->setImplicit(true);
  641. QualType canonType = context.getTypeDeclType(specializationDecl);
  642. DXASSERT(isa<RecordType>(canonType), "type of non-dependent specialization is not a RecordType");
  643. TemplateArgumentListInfo templateArgumentList(NoLoc, NoLoc);
  644. TemplateArgumentLocInfo NoTemplateArgumentLocInfo;
  645. for (unsigned i = 0; i < templateArgs.size(); i++) {
  646. templateArgumentList.addArgument(TemplateArgumentLoc(templateArgs[i], NoTemplateArgumentLocInfo));
  647. }
  648. return context.getTemplateSpecializationType(
  649. TemplateName(templateDecl), templateArgumentList, canonType);
  650. }
  651. /// <summary>Instantiates a new matrix type specialization or gets an existing one from the AST.</summary>
  652. static
  653. QualType GetOrCreateMatrixSpecialization(ASTContext& context, Sema* sema,
  654. _In_ ClassTemplateDecl* matrixTemplateDecl,
  655. QualType elementType, uint64_t rowCount, uint64_t colCount)
  656. {
  657. DXASSERT_NOMSG(sema);
  658. TemplateArgument templateArgs[3] = {
  659. TemplateArgument(elementType),
  660. TemplateArgument(
  661. context,
  662. llvm::APSInt(
  663. llvm::APInt(context.getIntWidth(context.IntTy), rowCount), false),
  664. context.IntTy),
  665. TemplateArgument(
  666. context,
  667. llvm::APSInt(
  668. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  669. context.IntTy)};
  670. QualType matrixSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, matrixTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  671. #ifdef DBG
  672. // Verify that we can read the field member from the template record.
  673. DXASSERT(matrixSpecializationType->getAsCXXRecordDecl(),
  674. "type of non-dependent specialization is not a RecordType");
  675. DeclContext::lookup_result lookupResult = matrixSpecializationType->getAsCXXRecordDecl()->
  676. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  677. DXASSERT(!lookupResult.empty(), "otherwise matrix handle cannot be looked up");
  678. #endif
  679. return matrixSpecializationType;
  680. }
  681. /// <summary>Instantiates a new vector type specialization or gets an existing one from the AST.</summary>
  682. static
  683. QualType GetOrCreateVectorSpecialization(ASTContext& context, Sema* sema,
  684. _In_ ClassTemplateDecl* vectorTemplateDecl,
  685. QualType elementType, uint64_t colCount)
  686. {
  687. DXASSERT_NOMSG(sema);
  688. DXASSERT_NOMSG(vectorTemplateDecl);
  689. TemplateArgument templateArgs[2] = {
  690. TemplateArgument(elementType),
  691. TemplateArgument(
  692. context,
  693. llvm::APSInt(
  694. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  695. context.IntTy)};
  696. QualType vectorSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, vectorTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  697. #ifdef DBG
  698. // Verify that we can read the field member from the template record.
  699. DXASSERT(vectorSpecializationType->getAsCXXRecordDecl(),
  700. "type of non-dependent specialization is not a RecordType");
  701. DeclContext::lookup_result lookupResult = vectorSpecializationType->getAsCXXRecordDecl()->
  702. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  703. DXASSERT(!lookupResult.empty(), "otherwise vector handle cannot be looked up");
  704. #endif
  705. return vectorSpecializationType;
  706. }
  707. // Decls.cpp constants start here - these should be refactored or, better, replaced with clang::Type-based constructs.
  708. static const LPCSTR kBuiltinIntrinsicTableName = "op";
  709. static const unsigned kAtomicDstOperandIdx = 1;
  710. static const ArTypeObjectKind g_ScalarTT[] =
  711. {
  712. AR_TOBJ_SCALAR,
  713. AR_TOBJ_UNKNOWN
  714. };
  715. static const ArTypeObjectKind g_VectorTT[] =
  716. {
  717. AR_TOBJ_VECTOR,
  718. AR_TOBJ_UNKNOWN
  719. };
  720. static const ArTypeObjectKind g_MatrixTT[] =
  721. {
  722. AR_TOBJ_MATRIX,
  723. AR_TOBJ_UNKNOWN
  724. };
  725. static const ArTypeObjectKind g_AnyTT[] =
  726. {
  727. AR_TOBJ_SCALAR,
  728. AR_TOBJ_VECTOR,
  729. AR_TOBJ_MATRIX,
  730. AR_TOBJ_UNKNOWN
  731. };
  732. static const ArTypeObjectKind g_ObjectTT[] =
  733. {
  734. AR_TOBJ_OBJECT,
  735. AR_TOBJ_UNKNOWN
  736. };
  737. static const ArTypeObjectKind g_NullTT[] =
  738. {
  739. AR_TOBJ_VOID,
  740. AR_TOBJ_UNKNOWN
  741. };
  742. const ArTypeObjectKind* g_LegalIntrinsicTemplates[] =
  743. {
  744. g_NullTT,
  745. g_ScalarTT,
  746. g_VectorTT,
  747. g_MatrixTT,
  748. g_AnyTT,
  749. g_ObjectTT,
  750. };
  751. C_ASSERT(ARRAYSIZE(g_LegalIntrinsicTemplates) == LITEMPLATE_COUNT);
  752. //
  753. // The first one is used to name the representative group, so make
  754. // sure its name will make sense in error messages.
  755. //
  756. static const ArBasicKind g_BoolCT[] =
  757. {
  758. AR_BASIC_BOOL,
  759. AR_BASIC_UNKNOWN
  760. };
  761. static const ArBasicKind g_IntCT[] =
  762. {
  763. AR_BASIC_INT32,
  764. AR_BASIC_LITERAL_INT,
  765. AR_BASIC_UNKNOWN
  766. };
  767. static const ArBasicKind g_UIntCT[] =
  768. {
  769. AR_BASIC_UINT32,
  770. AR_BASIC_LITERAL_INT,
  771. AR_BASIC_UNKNOWN
  772. };
  773. // We use the first element for default if matching kind is missing in the list.
  774. // AR_BASIC_INT32 should be the default for any int since min precision integers should map to int32, not int16 or int64
  775. static const ArBasicKind g_AnyIntCT[] =
  776. {
  777. AR_BASIC_INT32,
  778. AR_BASIC_INT16,
  779. AR_BASIC_UINT32,
  780. AR_BASIC_UINT16,
  781. AR_BASIC_INT64,
  782. AR_BASIC_UINT64,
  783. AR_BASIC_LITERAL_INT,
  784. AR_BASIC_UNKNOWN
  785. };
  786. static const ArBasicKind g_AnyInt32CT[] =
  787. {
  788. AR_BASIC_INT32,
  789. AR_BASIC_UINT32,
  790. AR_BASIC_LITERAL_INT,
  791. AR_BASIC_UNKNOWN
  792. };
  793. static const ArBasicKind g_UIntOnlyCT[] =
  794. {
  795. AR_BASIC_UINT32,
  796. AR_BASIC_UINT64,
  797. AR_BASIC_LITERAL_INT,
  798. AR_BASIC_NOCAST,
  799. AR_BASIC_UNKNOWN
  800. };
  801. static const ArBasicKind g_FloatCT[] =
  802. {
  803. AR_BASIC_FLOAT32,
  804. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  805. AR_BASIC_LITERAL_FLOAT,
  806. AR_BASIC_UNKNOWN
  807. };
  808. static const ArBasicKind g_AnyFloatCT[] =
  809. {
  810. AR_BASIC_FLOAT32,
  811. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  812. AR_BASIC_FLOAT16,
  813. AR_BASIC_FLOAT64,
  814. AR_BASIC_LITERAL_FLOAT,
  815. AR_BASIC_MIN10FLOAT,
  816. AR_BASIC_MIN16FLOAT,
  817. AR_BASIC_UNKNOWN
  818. };
  819. static const ArBasicKind g_FloatLikeCT[] =
  820. {
  821. AR_BASIC_FLOAT32,
  822. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  823. AR_BASIC_FLOAT16,
  824. AR_BASIC_LITERAL_FLOAT,
  825. AR_BASIC_MIN10FLOAT,
  826. AR_BASIC_MIN16FLOAT,
  827. AR_BASIC_UNKNOWN
  828. };
  829. static const ArBasicKind g_FloatDoubleCT[] =
  830. {
  831. AR_BASIC_FLOAT32,
  832. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  833. AR_BASIC_FLOAT64,
  834. AR_BASIC_LITERAL_FLOAT,
  835. AR_BASIC_UNKNOWN
  836. };
  837. static const ArBasicKind g_DoubleCT[] =
  838. {
  839. AR_BASIC_FLOAT64,
  840. AR_BASIC_LITERAL_FLOAT,
  841. AR_BASIC_UNKNOWN
  842. };
  843. static const ArBasicKind g_DoubleOnlyCT[] =
  844. {
  845. AR_BASIC_FLOAT64,
  846. AR_BASIC_NOCAST,
  847. AR_BASIC_UNKNOWN
  848. };
  849. static const ArBasicKind g_NumericCT[] =
  850. {
  851. AR_BASIC_LITERAL_FLOAT,
  852. AR_BASIC_FLOAT32,
  853. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  854. AR_BASIC_FLOAT16,
  855. AR_BASIC_FLOAT64,
  856. AR_BASIC_MIN10FLOAT,
  857. AR_BASIC_MIN16FLOAT,
  858. AR_BASIC_LITERAL_INT,
  859. AR_BASIC_INT16,
  860. AR_BASIC_INT32,
  861. AR_BASIC_UINT16,
  862. AR_BASIC_UINT32,
  863. AR_BASIC_MIN12INT,
  864. AR_BASIC_MIN16INT,
  865. AR_BASIC_MIN16UINT,
  866. AR_BASIC_INT64,
  867. AR_BASIC_UINT64,
  868. AR_BASIC_UNKNOWN
  869. };
  870. static const ArBasicKind g_Numeric32CT[] =
  871. {
  872. AR_BASIC_LITERAL_FLOAT,
  873. AR_BASIC_FLOAT32,
  874. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  875. AR_BASIC_LITERAL_INT,
  876. AR_BASIC_INT32,
  877. AR_BASIC_UINT32,
  878. AR_BASIC_UNKNOWN
  879. };
  880. static const ArBasicKind g_Numeric32OnlyCT[] =
  881. {
  882. AR_BASIC_LITERAL_FLOAT,
  883. AR_BASIC_FLOAT32,
  884. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  885. AR_BASIC_LITERAL_INT,
  886. AR_BASIC_INT32,
  887. AR_BASIC_UINT32,
  888. AR_BASIC_NOCAST,
  889. AR_BASIC_UNKNOWN
  890. };
  891. static const ArBasicKind g_AnyCT[] =
  892. {
  893. AR_BASIC_LITERAL_FLOAT,
  894. AR_BASIC_FLOAT32,
  895. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  896. AR_BASIC_FLOAT16,
  897. AR_BASIC_FLOAT64,
  898. AR_BASIC_MIN10FLOAT,
  899. AR_BASIC_MIN16FLOAT,
  900. AR_BASIC_LITERAL_INT,
  901. AR_BASIC_INT16,
  902. AR_BASIC_UINT16,
  903. AR_BASIC_INT32,
  904. AR_BASIC_UINT32,
  905. AR_BASIC_MIN12INT,
  906. AR_BASIC_MIN16INT,
  907. AR_BASIC_MIN16UINT,
  908. AR_BASIC_BOOL,
  909. AR_BASIC_INT64,
  910. AR_BASIC_UINT64,
  911. AR_BASIC_UNKNOWN
  912. };
  913. static const ArBasicKind g_Sampler1DCT[] =
  914. {
  915. AR_OBJECT_SAMPLER1D,
  916. AR_BASIC_UNKNOWN
  917. };
  918. static const ArBasicKind g_Sampler2DCT[] =
  919. {
  920. AR_OBJECT_SAMPLER2D,
  921. AR_BASIC_UNKNOWN
  922. };
  923. static const ArBasicKind g_Sampler3DCT[] =
  924. {
  925. AR_OBJECT_SAMPLER3D,
  926. AR_BASIC_UNKNOWN
  927. };
  928. static const ArBasicKind g_SamplerCUBECT[] =
  929. {
  930. AR_OBJECT_SAMPLERCUBE,
  931. AR_BASIC_UNKNOWN
  932. };
  933. static const ArBasicKind g_SamplerCmpCT[] =
  934. {
  935. AR_OBJECT_SAMPLERCOMPARISON,
  936. AR_BASIC_UNKNOWN
  937. };
  938. static const ArBasicKind g_SamplerCT[] =
  939. {
  940. AR_OBJECT_SAMPLER,
  941. AR_BASIC_UNKNOWN
  942. };
  943. static const ArBasicKind g_Texture2DCT[] =
  944. {
  945. AR_OBJECT_TEXTURE2D,
  946. AR_BASIC_UNKNOWN
  947. };
  948. static const ArBasicKind g_Texture2DArrayCT[] =
  949. {
  950. AR_OBJECT_TEXTURE2D_ARRAY,
  951. AR_BASIC_UNKNOWN
  952. };
  953. static const ArBasicKind g_ResourceCT[] = {AR_OBJECT_RESOURCE,
  954. AR_BASIC_UNKNOWN};
  955. static const ArBasicKind g_RayDescCT[] =
  956. {
  957. AR_OBJECT_RAY_DESC,
  958. AR_BASIC_UNKNOWN
  959. };
  960. static const ArBasicKind g_AccelerationStructCT[] =
  961. {
  962. AR_OBJECT_ACCELERATION_STRUCT,
  963. AR_BASIC_UNKNOWN
  964. };
  965. static const ArBasicKind g_UDTCT[] =
  966. {
  967. AR_OBJECT_USER_DEFINED_TYPE,
  968. AR_BASIC_UNKNOWN
  969. };
  970. static const ArBasicKind g_StringCT[] =
  971. {
  972. AR_OBJECT_STRING_LITERAL,
  973. AR_OBJECT_STRING,
  974. AR_BASIC_UNKNOWN
  975. };
  976. static const ArBasicKind g_NullCT[] =
  977. {
  978. AR_OBJECT_NULL,
  979. AR_BASIC_UNKNOWN
  980. };
  981. static const ArBasicKind g_WaveCT[] =
  982. {
  983. AR_OBJECT_WAVE,
  984. AR_BASIC_UNKNOWN
  985. };
  986. static const ArBasicKind g_UInt64CT[] =
  987. {
  988. AR_BASIC_UINT64,
  989. AR_BASIC_UNKNOWN
  990. };
  991. static const ArBasicKind g_Float16CT[] =
  992. {
  993. AR_BASIC_FLOAT16,
  994. AR_BASIC_LITERAL_FLOAT,
  995. AR_BASIC_UNKNOWN
  996. };
  997. static const ArBasicKind g_Int16CT[] =
  998. {
  999. AR_BASIC_INT16,
  1000. AR_BASIC_LITERAL_INT,
  1001. AR_BASIC_UNKNOWN
  1002. };
  1003. static const ArBasicKind g_UInt16CT[] =
  1004. {
  1005. AR_BASIC_UINT16,
  1006. AR_BASIC_LITERAL_INT,
  1007. AR_BASIC_UNKNOWN
  1008. };
  1009. static const ArBasicKind g_Numeric16OnlyCT[] =
  1010. {
  1011. AR_BASIC_FLOAT16,
  1012. AR_BASIC_INT16,
  1013. AR_BASIC_UINT16,
  1014. AR_BASIC_LITERAL_FLOAT,
  1015. AR_BASIC_LITERAL_INT,
  1016. AR_BASIC_NOCAST,
  1017. AR_BASIC_UNKNOWN
  1018. };
  1019. // Basic kinds, indexed by a LEGAL_INTRINSIC_COMPTYPES value.
  1020. const ArBasicKind* g_LegalIntrinsicCompTypes[] =
  1021. {
  1022. g_NullCT, // LICOMPTYPE_VOID
  1023. g_BoolCT, // LICOMPTYPE_BOOL
  1024. g_IntCT, // LICOMPTYPE_INT
  1025. g_UIntCT, // LICOMPTYPE_UINT
  1026. g_AnyIntCT, // LICOMPTYPE_ANY_INT
  1027. g_AnyInt32CT, // LICOMPTYPE_ANY_INT32
  1028. g_UIntOnlyCT, // LICOMPTYPE_UINT_ONLY
  1029. g_FloatCT, // LICOMPTYPE_FLOAT
  1030. g_AnyFloatCT, // LICOMPTYPE_ANY_FLOAT
  1031. g_FloatLikeCT, // LICOMPTYPE_FLOAT_LIKE
  1032. g_FloatDoubleCT, // LICOMPTYPE_FLOAT_DOUBLE
  1033. g_DoubleCT, // LICOMPTYPE_DOUBLE
  1034. g_DoubleOnlyCT, // LICOMPTYPE_DOUBLE_ONLY
  1035. g_NumericCT, // LICOMPTYPE_NUMERIC
  1036. g_Numeric32CT, // LICOMPTYPE_NUMERIC32
  1037. g_Numeric32OnlyCT, // LICOMPTYPE_NUMERIC32_ONLY
  1038. g_AnyCT, // LICOMPTYPE_ANY
  1039. g_Sampler1DCT, // LICOMPTYPE_SAMPLER1D
  1040. g_Sampler2DCT, // LICOMPTYPE_SAMPLER2D
  1041. g_Sampler3DCT, // LICOMPTYPE_SAMPLER3D
  1042. g_SamplerCUBECT, // LICOMPTYPE_SAMPLERCUBE
  1043. g_SamplerCmpCT, // LICOMPTYPE_SAMPLERCMP
  1044. g_SamplerCT, // LICOMPTYPE_SAMPLER
  1045. g_StringCT, // LICOMPTYPE_STRING
  1046. g_WaveCT, // LICOMPTYPE_WAVE
  1047. g_UInt64CT, // LICOMPTYPE_UINT64
  1048. g_Float16CT, // LICOMPTYPE_FLOAT16
  1049. g_Int16CT, // LICOMPTYPE_INT16
  1050. g_UInt16CT, // LICOMPTYPE_UINT16
  1051. g_Numeric16OnlyCT, // LICOMPTYPE_NUMERIC16_ONLY
  1052. g_RayDescCT, // LICOMPTYPE_RAYDESC
  1053. g_AccelerationStructCT, // LICOMPTYPE_ACCELERATION_STRUCT,
  1054. g_UDTCT, // LICOMPTYPE_USER_DEFINED_TYPE
  1055. g_Texture2DCT, // LICOMPTYPE_TEXTURE2D
  1056. g_Texture2DArrayCT, // LICOMPTYPE_TEXTURE2DARRAY
  1057. g_ResourceCT, // LICOMPTYPE_RESOURCE
  1058. };
  1059. static_assert(ARRAYSIZE(g_LegalIntrinsicCompTypes) == LICOMPTYPE_COUNT,
  1060. "Intrinsic comp type table must be updated when new enumerants are added.");
  1061. // Decls.cpp constants ends here - these should be refactored or, better, replaced with clang::Type-based constructs.
  1062. // Basic kind objects that are represented as HLSL structures or templates.
  1063. static
  1064. const ArBasicKind g_ArBasicKindsAsTypes[] =
  1065. {
  1066. AR_OBJECT_BUFFER, // Buffer
  1067. // AR_OBJECT_TEXTURE,
  1068. AR_OBJECT_TEXTURE1D, // Texture1D
  1069. AR_OBJECT_TEXTURE1D_ARRAY, // Texture1DArray
  1070. AR_OBJECT_TEXTURE2D, // Texture2D
  1071. AR_OBJECT_TEXTURE2D_ARRAY, // Texture2DArray
  1072. AR_OBJECT_TEXTURE3D, // Texture3D
  1073. AR_OBJECT_TEXTURECUBE, // TextureCube
  1074. AR_OBJECT_TEXTURECUBE_ARRAY, // TextureCubeArray
  1075. AR_OBJECT_TEXTURE2DMS, // Texture2DMS
  1076. AR_OBJECT_TEXTURE2DMS_ARRAY, // Texture2DMSArray
  1077. AR_OBJECT_SAMPLER,
  1078. //AR_OBJECT_SAMPLER1D,
  1079. //AR_OBJECT_SAMPLER2D,
  1080. //AR_OBJECT_SAMPLER3D,
  1081. //AR_OBJECT_SAMPLERCUBE,
  1082. AR_OBJECT_SAMPLERCOMPARISON,
  1083. AR_OBJECT_POINTSTREAM,
  1084. AR_OBJECT_LINESTREAM,
  1085. AR_OBJECT_TRIANGLESTREAM,
  1086. AR_OBJECT_INPUTPATCH,
  1087. AR_OBJECT_OUTPUTPATCH,
  1088. AR_OBJECT_RWTEXTURE1D,
  1089. AR_OBJECT_RWTEXTURE1D_ARRAY,
  1090. AR_OBJECT_RWTEXTURE2D,
  1091. AR_OBJECT_RWTEXTURE2D_ARRAY,
  1092. AR_OBJECT_RWTEXTURE3D,
  1093. AR_OBJECT_RWBUFFER,
  1094. AR_OBJECT_BYTEADDRESS_BUFFER,
  1095. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  1096. AR_OBJECT_STRUCTURED_BUFFER,
  1097. AR_OBJECT_RWSTRUCTURED_BUFFER,
  1098. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  1099. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  1100. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  1101. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  1102. AR_OBJECT_ROVBUFFER,
  1103. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  1104. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  1105. AR_OBJECT_ROVTEXTURE1D,
  1106. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  1107. AR_OBJECT_ROVTEXTURE2D,
  1108. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  1109. AR_OBJECT_ROVTEXTURE3D,
  1110. AR_OBJECT_FEEDBACKTEXTURE2D,
  1111. AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY,
  1112. // SPIRV change starts
  1113. #ifdef ENABLE_SPIRV_CODEGEN
  1114. AR_OBJECT_VK_SUBPASS_INPUT,
  1115. AR_OBJECT_VK_SUBPASS_INPUT_MS,
  1116. #endif // ENABLE_SPIRV_CODEGEN
  1117. // SPIRV change ends
  1118. AR_OBJECT_LEGACY_EFFECT, // Used for all unsupported but ignored legacy effect types
  1119. AR_OBJECT_WAVE,
  1120. AR_OBJECT_RAY_DESC,
  1121. AR_OBJECT_ACCELERATION_STRUCT,
  1122. AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES,
  1123. // subobjects
  1124. AR_OBJECT_STATE_OBJECT_CONFIG,
  1125. AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  1126. AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  1127. AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  1128. AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  1129. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  1130. AR_OBJECT_TRIANGLE_HIT_GROUP,
  1131. AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  1132. AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  1133. AR_OBJECT_RAY_QUERY,
  1134. AR_OBJECT_RESOURCE,
  1135. };
  1136. // Count of template arguments for basic kind of objects that look like templates (one or more type arguments).
  1137. static
  1138. const uint8_t g_ArBasicKindsTemplateCount[] =
  1139. {
  1140. 1, // AR_OBJECT_BUFFER
  1141. // AR_OBJECT_TEXTURE,
  1142. 1, // AR_OBJECT_TEXTURE1D
  1143. 1, // AR_OBJECT_TEXTURE1D_ARRAY
  1144. 1, // AR_OBJECT_TEXTURE2D
  1145. 1, // AR_OBJECT_TEXTURE2D_ARRAY
  1146. 1, // AR_OBJECT_TEXTURE3D
  1147. 1, // AR_OBJECT_TEXTURECUBE
  1148. 1, // AR_OBJECT_TEXTURECUBE_ARRAY
  1149. 2, // AR_OBJECT_TEXTURE2DMS
  1150. 2, // AR_OBJECT_TEXTURE2DMS_ARRAY
  1151. 0, // AR_OBJECT_SAMPLER
  1152. //AR_OBJECT_SAMPLER1D,
  1153. //AR_OBJECT_SAMPLER2D,
  1154. //AR_OBJECT_SAMPLER3D,
  1155. //AR_OBJECT_SAMPLERCUBE,
  1156. 0, // AR_OBJECT_SAMPLERCOMPARISON
  1157. 1, // AR_OBJECT_POINTSTREAM
  1158. 1, // AR_OBJECT_LINESTREAM
  1159. 1, // AR_OBJECT_TRIANGLESTREAM
  1160. 2, // AR_OBJECT_INPUTPATCH
  1161. 2, // AR_OBJECT_OUTPUTPATCH
  1162. 1, // AR_OBJECT_RWTEXTURE1D
  1163. 1, // AR_OBJECT_RWTEXTURE1D_ARRAY
  1164. 1, // AR_OBJECT_RWTEXTURE2D
  1165. 1, // AR_OBJECT_RWTEXTURE2D_ARRAY
  1166. 1, // AR_OBJECT_RWTEXTURE3D
  1167. 1, // AR_OBJECT_RWBUFFER
  1168. 0, // AR_OBJECT_BYTEADDRESS_BUFFER
  1169. 0, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  1170. 1, // AR_OBJECT_STRUCTURED_BUFFER
  1171. 1, // AR_OBJECT_RWSTRUCTURED_BUFFER
  1172. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  1173. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  1174. 1, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  1175. 1, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  1176. 1, // AR_OBJECT_ROVBUFFER
  1177. 0, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  1178. 1, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  1179. 1, // AR_OBJECT_ROVTEXTURE1D
  1180. 1, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  1181. 1, // AR_OBJECT_ROVTEXTURE2D
  1182. 1, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  1183. 1, // AR_OBJECT_ROVTEXTURE3D
  1184. 1, // AR_OBJECT_FEEDBACKTEXTURE2D
  1185. 1, // AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY
  1186. // SPIRV change starts
  1187. #ifdef ENABLE_SPIRV_CODEGEN
  1188. 1, // AR_OBJECT_VK_SUBPASS_INPUT
  1189. 1, // AR_OBJECT_VK_SUBPASS_INPUT_MS
  1190. #endif // ENABLE_SPIRV_CODEGEN
  1191. // SPIRV change ends
  1192. 0, // AR_OBJECT_LEGACY_EFFECT // Used for all unsupported but ignored legacy effect types
  1193. 0, // AR_OBJECT_WAVE
  1194. 0, // AR_OBJECT_RAY_DESC
  1195. 0, // AR_OBJECT_ACCELERATION_STRUCT
  1196. 0, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  1197. 0, // AR_OBJECT_STATE_OBJECT_CONFIG,
  1198. 0, // AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  1199. 0, // AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  1200. 0, // AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  1201. 0, // AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  1202. 0, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  1203. 0, // AR_OBJECT_TRIANGLE_HIT_GROUP,
  1204. 0, // AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  1205. 0, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  1206. 1, // AR_OBJECT_RAY_QUERY,
  1207. 0, // AR_OBJECT_RESOURCE,
  1208. };
  1209. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsTemplateCount));
  1210. /// <summary>Describes the how the subscript or indexing operators work on a given type.</summary>
  1211. struct SubscriptOperatorRecord
  1212. {
  1213. unsigned int SubscriptCardinality : 4; // Number of elements expected in subscript - zero if operator not supported.
  1214. bool HasMips : 1; // true if the kind has a mips member; false otherwise
  1215. bool HasSample : 1; // true if the kind has a sample member; false otherwise
  1216. };
  1217. // Subscript operators for objects that are represented as HLSL structures or templates.
  1218. static
  1219. const SubscriptOperatorRecord g_ArBasicKindsSubscripts[] =
  1220. {
  1221. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_BUFFER (Buffer)
  1222. // AR_OBJECT_TEXTURE,
  1223. { 1, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D (Texture1D)
  1224. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D_ARRAY (Texture1DArray)
  1225. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D (Texture2D)
  1226. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D_ARRAY (Texture2DArray)
  1227. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE3D (Texture3D)
  1228. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE (TextureCube)
  1229. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE_ARRAY (TextureCubeArray)
  1230. { 2, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS (Texture2DMS)
  1231. { 3, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS_ARRAY (Texture2DMSArray)
  1232. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLER (SamplerState)
  1233. //AR_OBJECT_SAMPLER1D,
  1234. //AR_OBJECT_SAMPLER2D,
  1235. //AR_OBJECT_SAMPLER3D,
  1236. //AR_OBJECT_SAMPLERCUBE,
  1237. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLERCOMPARISON (SamplerComparison)
  1238. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_POINTSTREAM (PointStream)
  1239. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LINESTREAM (LineStream)
  1240. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLESTREAM (TriangleStream)
  1241. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_INPUTPATCH (InputPatch)
  1242. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_OUTPUTPATCH (OutputPatch)
  1243. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D (RWTexture1D)
  1244. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D_ARRAY (RWTexture1DArray)
  1245. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D (RWTexture2D)
  1246. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D_ARRAY (RWTexture2DArray)
  1247. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE3D (RWTexture3D)
  1248. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWBUFFER (RWBuffer)
  1249. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_BYTEADDRESS_BUFFER (ByteAddressBuffer)
  1250. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RWBYTEADDRESS_BUFFER (RWByteAddressBuffer)
  1251. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_STRUCTURED_BUFFER (StructuredBuffer)
  1252. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWSTRUCTURED_BUFFER (RWStructuredBuffer)
  1253. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  1254. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  1255. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_APPEND_STRUCTURED_BUFFER (AppendStructuredBuffer)
  1256. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER (ConsumeStructuredBuffer)
  1257. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBUFFER (ROVBuffer)
  1258. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBYTEADDRESS_BUFFER (ROVByteAddressBuffer)
  1259. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVSTRUCTURED_BUFFER (ROVStructuredBuffer)
  1260. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D (ROVTexture1D)
  1261. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D_ARRAY (ROVTexture1DArray)
  1262. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D (ROVTexture2D)
  1263. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D_ARRAY (ROVTexture2DArray)
  1264. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE3D (ROVTexture3D)
  1265. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_FEEDBACKTEXTURE2D
  1266. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY
  1267. // SPIRV change starts
  1268. #ifdef ENABLE_SPIRV_CODEGEN
  1269. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_VK_SUBPASS_INPUT (SubpassInput)
  1270. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_VK_SUBPASS_INPUT_MS (SubpassInputMS)
  1271. #endif // ENABLE_SPIRV_CODEGEN
  1272. // SPIRV change ends
  1273. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LEGACY_EFFECT (legacy effect objects)
  1274. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_WAVE
  1275. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAY_DESC
  1276. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_ACCELERATION_STRUCT
  1277. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES
  1278. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_STATE_OBJECT_CONFIG,
  1279. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_GLOBAL_ROOT_SIGNATURE,
  1280. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LOCAL_ROOT_SIGNATURE,
  1281. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC,
  1282. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAYTRACING_SHADER_CONFIG,
  1283. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG,
  1284. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLE_HIT_GROUP,
  1285. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP,
  1286. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1,
  1287. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RAY_QUERY,
  1288. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RESOURCE,
  1289. };
  1290. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsSubscripts));
  1291. // Type names for ArBasicKind values.
  1292. static
  1293. const char* g_ArBasicTypeNames[] =
  1294. {
  1295. "bool", "float", "half", "half", "float", "double",
  1296. "int", "sbyte", "byte", "short", "ushort",
  1297. "int", "uint", "long", "ulong",
  1298. "min10float", "min16float",
  1299. "min12int", "min16int", "min16uint",
  1300. "enum",
  1301. "<count>",
  1302. "<none>",
  1303. "<unknown>",
  1304. "<nocast>",
  1305. "<dependent>",
  1306. "<pointer>",
  1307. "enum class",
  1308. "null",
  1309. "literal string",
  1310. "string",
  1311. // "texture",
  1312. "Texture1D",
  1313. "Texture1DArray",
  1314. "Texture2D",
  1315. "Texture2DArray",
  1316. "Texture3D",
  1317. "TextureCube",
  1318. "TextureCubeArray",
  1319. "Texture2DMS",
  1320. "Texture2DMSArray",
  1321. "SamplerState",
  1322. "sampler1D",
  1323. "sampler2D",
  1324. "sampler3D",
  1325. "samplerCUBE",
  1326. "SamplerComparisonState",
  1327. "Buffer",
  1328. "RenderTargetView",
  1329. "DepthStencilView",
  1330. "ComputeShader",
  1331. "DomainShader",
  1332. "GeometryShader",
  1333. "HullShader",
  1334. "PixelShader",
  1335. "VertexShader",
  1336. "pixelfragment",
  1337. "vertexfragment",
  1338. "StateBlock",
  1339. "Rasterizer",
  1340. "DepthStencil",
  1341. "Blend",
  1342. "PointStream",
  1343. "LineStream",
  1344. "TriangleStream",
  1345. "InputPatch",
  1346. "OutputPatch",
  1347. "RWTexture1D",
  1348. "RWTexture1DArray",
  1349. "RWTexture2D",
  1350. "RWTexture2DArray",
  1351. "RWTexture3D",
  1352. "RWBuffer",
  1353. "ByteAddressBuffer",
  1354. "RWByteAddressBuffer",
  1355. "StructuredBuffer",
  1356. "RWStructuredBuffer",
  1357. "RWStructuredBuffer(Incrementable)",
  1358. "RWStructuredBuffer(Decrementable)",
  1359. "AppendStructuredBuffer",
  1360. "ConsumeStructuredBuffer",
  1361. "ConstantBuffer",
  1362. "TextureBuffer",
  1363. "RasterizerOrderedBuffer",
  1364. "RasterizerOrderedByteAddressBuffer",
  1365. "RasterizerOrderedStructuredBuffer",
  1366. "RasterizerOrderedTexture1D",
  1367. "RasterizerOrderedTexture1DArray",
  1368. "RasterizerOrderedTexture2D",
  1369. "RasterizerOrderedTexture2DArray",
  1370. "RasterizerOrderedTexture3D",
  1371. "FeedbackTexture2D",
  1372. "FeedbackTexture2DArray",
  1373. // SPIRV change starts
  1374. #ifdef ENABLE_SPIRV_CODEGEN
  1375. "SubpassInput",
  1376. "SubpassInputMS",
  1377. #endif // ENABLE_SPIRV_CODEGEN
  1378. // SPIRV change ends
  1379. "<internal inner type object>",
  1380. "deprecated effect object",
  1381. "wave_t",
  1382. "RayDesc",
  1383. "RaytracingAccelerationStructure",
  1384. "user defined type",
  1385. "BuiltInTriangleIntersectionAttributes",
  1386. // subobjects
  1387. "StateObjectConfig",
  1388. "GlobalRootSignature",
  1389. "LocalRootSignature",
  1390. "SubobjectToExportsAssociation",
  1391. "RaytracingShaderConfig",
  1392. "RaytracingPipelineConfig",
  1393. "TriangleHitGroup",
  1394. "ProceduralPrimitiveHitGroup",
  1395. "RaytracingPipelineConfig1",
  1396. "RayQuery",
  1397. "Resource",
  1398. };
  1399. C_ASSERT(_countof(g_ArBasicTypeNames) == AR_BASIC_MAXIMUM_COUNT);
  1400. static bool IsValidBasicKind(ArBasicKind kind) {
  1401. return kind != AR_BASIC_COUNT &&
  1402. kind != AR_BASIC_NONE &&
  1403. kind != AR_BASIC_UNKNOWN &&
  1404. kind != AR_BASIC_NOCAST &&
  1405. kind != AR_BASIC_POINTER &&
  1406. kind != AR_OBJECT_RENDERTARGETVIEW &&
  1407. kind != AR_OBJECT_DEPTHSTENCILVIEW &&
  1408. kind != AR_OBJECT_COMPUTESHADER &&
  1409. kind != AR_OBJECT_DOMAINSHADER &&
  1410. kind != AR_OBJECT_GEOMETRYSHADER &&
  1411. kind != AR_OBJECT_HULLSHADER &&
  1412. kind != AR_OBJECT_PIXELSHADER &&
  1413. kind != AR_OBJECT_VERTEXSHADER &&
  1414. kind != AR_OBJECT_PIXELFRAGMENT &&
  1415. kind != AR_OBJECT_VERTEXFRAGMENT;
  1416. }
  1417. // kind should never be a flag value or effects framework type - we simply do not expect to deal with these
  1418. #define DXASSERT_VALIDBASICKIND(kind) \
  1419. DXASSERT(IsValidBasicKind(kind), "otherwise caller is using a special flag or an unsupported kind value");
  1420. static
  1421. const char* g_DeprecatedEffectObjectNames[] =
  1422. {
  1423. // These are case insensitive in fxc, but we'll just create two case aliases
  1424. // to capture the majority of cases
  1425. "texture", "Texture",
  1426. "pixelshader", "PixelShader",
  1427. "vertexshader", "VertexShader",
  1428. // These are case sensitive in fxc
  1429. "pixelfragment", // 13
  1430. "vertexfragment", // 14
  1431. "ComputeShader", // 13
  1432. "DomainShader", // 12
  1433. "GeometryShader", // 14
  1434. "HullShader", // 10
  1435. "BlendState", // 10
  1436. "DepthStencilState",// 17
  1437. "DepthStencilView", // 16
  1438. "RasterizerState", // 15
  1439. "RenderTargetView", // 16
  1440. };
  1441. static bool IsVariadicIntrinsicFunction(const HLSL_INTRINSIC *fn) {
  1442. return fn->pArgs[fn->uNumArgs - 1].uTemplateId == INTRIN_TEMPLATE_VARARGS;
  1443. }
  1444. static bool IsVariadicArgument(const HLSL_INTRINSIC_ARGUMENT &arg) {
  1445. return arg.uTemplateId == INTRIN_TEMPLATE_VARARGS;
  1446. }
  1447. static hlsl::ParameterModifier
  1448. ParamModsFromIntrinsicArg(const HLSL_INTRINSIC_ARGUMENT *pArg) {
  1449. if (pArg->qwUsage == AR_QUAL_IN_OUT) {
  1450. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::InOut);
  1451. }
  1452. if (pArg->qwUsage == AR_QUAL_OUT) {
  1453. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::Out);
  1454. }
  1455. DXASSERT(pArg->qwUsage & AR_QUAL_IN, "else usage is incorrect");
  1456. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::In);
  1457. }
  1458. static void InitParamMods(const HLSL_INTRINSIC *pIntrinsic,
  1459. SmallVectorImpl<hlsl::ParameterModifier> &paramMods) {
  1460. // The first argument is the return value, which isn't included.
  1461. UINT i = 1, size = paramMods.size();
  1462. for (; i < pIntrinsic->uNumArgs; ++i) {
  1463. // Once we reach varargs we can break out of this loop.
  1464. if (IsVariadicArgument(pIntrinsic->pArgs[i]))
  1465. break;
  1466. paramMods.push_back(ParamModsFromIntrinsicArg(&pIntrinsic->pArgs[i]));
  1467. }
  1468. // For variadic functions, any argument not explicitly specified will be
  1469. // considered an input argument.
  1470. if (IsVariadicIntrinsicFunction(pIntrinsic)) {
  1471. for (; i < size; ++i) {
  1472. paramMods.push_back(
  1473. hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::In));
  1474. }
  1475. }
  1476. }
  1477. static bool IsAtomicOperation(IntrinsicOp op) {
  1478. switch (op) {
  1479. case IntrinsicOp::IOP_InterlockedAdd:
  1480. case IntrinsicOp::IOP_InterlockedAnd:
  1481. case IntrinsicOp::IOP_InterlockedCompareExchange:
  1482. case IntrinsicOp::IOP_InterlockedCompareStore:
  1483. case IntrinsicOp::IOP_InterlockedExchange:
  1484. case IntrinsicOp::IOP_InterlockedMax:
  1485. case IntrinsicOp::IOP_InterlockedMin:
  1486. case IntrinsicOp::IOP_InterlockedOr:
  1487. case IntrinsicOp::IOP_InterlockedXor:
  1488. case IntrinsicOp::MOP_InterlockedAdd:
  1489. case IntrinsicOp::MOP_InterlockedAnd:
  1490. case IntrinsicOp::MOP_InterlockedCompareExchange:
  1491. case IntrinsicOp::MOP_InterlockedCompareStore:
  1492. case IntrinsicOp::MOP_InterlockedExchange:
  1493. case IntrinsicOp::MOP_InterlockedMax:
  1494. case IntrinsicOp::MOP_InterlockedMin:
  1495. case IntrinsicOp::MOP_InterlockedOr:
  1496. case IntrinsicOp::MOP_InterlockedXor:
  1497. return true;
  1498. default:
  1499. return false;
  1500. }
  1501. }
  1502. static bool IsBuiltinTable(LPCSTR tableName) {
  1503. return tableName == kBuiltinIntrinsicTableName;
  1504. }
  1505. static void AddHLSLIntrinsicAttr(FunctionDecl *FD, ASTContext &context,
  1506. LPCSTR tableName, LPCSTR lowering,
  1507. const HLSL_INTRINSIC *pIntrinsic) {
  1508. unsigned opcode = (unsigned)pIntrinsic->Op;
  1509. if (HasUnsignedOpcode(opcode) && IsBuiltinTable(tableName)) {
  1510. QualType Ty = FD->getReturnType();
  1511. if (pIntrinsic->iOverloadParamIndex != -1) {
  1512. const FunctionProtoType *FT =
  1513. FD->getFunctionType()->getAs<FunctionProtoType>();
  1514. Ty = FT->getParamType(pIntrinsic->iOverloadParamIndex);
  1515. // To go thru reference type.
  1516. if (Ty->isReferenceType())
  1517. Ty = Ty.getNonReferenceType();
  1518. }
  1519. // TODO: refine the code for getting element type
  1520. if (const ExtVectorType *VecTy = hlsl::ConvertHLSLVecMatTypeToExtVectorType(context, Ty)) {
  1521. Ty = VecTy->getElementType();
  1522. }
  1523. // Make sure to use unsigned op when return type is 'unsigned' matrix
  1524. bool isUnsignedMatOp =
  1525. IsHLSLMatType(Ty) && GetHLSLMatElementType(Ty)->isUnsignedIntegerType();
  1526. if (Ty->isUnsignedIntegerType() || isUnsignedMatOp) {
  1527. opcode = hlsl::GetUnsignedOpcode(opcode);
  1528. }
  1529. }
  1530. FD->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, tableName, lowering, opcode));
  1531. if (pIntrinsic->bReadNone)
  1532. FD->addAttr(ConstAttr::CreateImplicit(context));
  1533. if (pIntrinsic->bReadOnly)
  1534. FD->addAttr(PureAttr::CreateImplicit(context));
  1535. if (pIntrinsic->bIsWave)
  1536. FD->addAttr(HLSLWaveSensitiveAttr::CreateImplicit(context));
  1537. }
  1538. static
  1539. FunctionDecl *AddHLSLIntrinsicFunction(
  1540. ASTContext &context, _In_ NamespaceDecl *NS,
  1541. LPCSTR tableName, LPCSTR lowering,
  1542. _In_ const HLSL_INTRINSIC *pIntrinsic,
  1543. std::vector<QualType> *functionArgQualTypesVector)
  1544. {
  1545. DeclContext *currentDeclContext = context.getTranslationUnitDecl();
  1546. std::vector<QualType> &functionArgQualTypes = *functionArgQualTypesVector;
  1547. const size_t functionArgTypeCount = functionArgQualTypes.size();
  1548. const bool isVariadic = IsVariadicIntrinsicFunction(pIntrinsic);
  1549. DXASSERT(isVariadic || functionArgTypeCount - 1 <= g_MaxIntrinsicParamCount,
  1550. "otherwise g_MaxIntrinsicParamCount should be larger");
  1551. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  1552. if (isVariadic) {
  1553. // For variadic functions, the number of arguments is larger than the
  1554. // function declaration signature.
  1555. paramMods.resize(functionArgTypeCount);
  1556. }
  1557. InitParamMods(pIntrinsic, paramMods);
  1558. // Change dest address into reference type for atomic.
  1559. if (IsBuiltinTable(tableName)) {
  1560. if (IsAtomicOperation(static_cast<IntrinsicOp>(pIntrinsic->Op))) {
  1561. DXASSERT(functionArgTypeCount > kAtomicDstOperandIdx,
  1562. "else operation was misrecognized");
  1563. functionArgQualTypes[kAtomicDstOperandIdx] =
  1564. context.getLValueReferenceType(functionArgQualTypes[kAtomicDstOperandIdx]);
  1565. }
  1566. }
  1567. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1568. // Change out/inout param to reference type.
  1569. if (paramMods[i-1].isAnyOut()) {
  1570. QualType Ty = functionArgQualTypes[i];
  1571. // Aggregate type will be indirect param convert to pointer type.
  1572. // Don't need add reference for it.
  1573. if ((!Ty->isArrayType() && !Ty->isRecordType()) ||
  1574. hlsl::IsHLSLVecMatType(Ty)) {
  1575. functionArgQualTypes[i] = context.getLValueReferenceType(Ty);
  1576. }
  1577. }
  1578. }
  1579. IdentifierInfo &functionId = context.Idents.get(
  1580. StringRef(pIntrinsic->pArgs[0].pName), tok::TokenKind::identifier);
  1581. DeclarationName functionName(&functionId);
  1582. auto protoInfo = clang::FunctionProtoType::ExtProtoInfo();
  1583. protoInfo.Variadic = isVariadic;
  1584. // functionArgQualTypes first element is the function return type, and
  1585. // function argument types start at index 1.
  1586. const QualType fnReturnType = functionArgQualTypes[0];
  1587. std::vector<QualType> fnArgTypes(functionArgQualTypes.begin() + 1,
  1588. functionArgQualTypes.end());
  1589. QualType functionType =
  1590. context.getFunctionType(fnReturnType, fnArgTypes, protoInfo, paramMods);
  1591. FunctionDecl *functionDecl = FunctionDecl::Create(
  1592. context, currentDeclContext, NoLoc,
  1593. DeclarationNameInfo(functionName, NoLoc), functionType, nullptr,
  1594. StorageClass::SC_Extern, InlineSpecifiedFalse, HasWrittenPrototypeTrue);
  1595. currentDeclContext->addDecl(functionDecl);
  1596. functionDecl->setLexicalDeclContext(currentDeclContext);
  1597. // put under hlsl namespace
  1598. functionDecl->setDeclContext(NS);
  1599. // Add intrinsic attribute
  1600. AddHLSLIntrinsicAttr(functionDecl, context, tableName, lowering, pIntrinsic);
  1601. llvm::SmallVector<ParmVarDecl *, 4> paramDecls;
  1602. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1603. // For variadic functions all non-explicit arguments will have the same
  1604. // name: "..."
  1605. std::string name = i < pIntrinsic->uNumArgs - 1
  1606. ? pIntrinsic->pArgs[i].pName
  1607. : pIntrinsic->pArgs[pIntrinsic->uNumArgs - 1].pName;
  1608. IdentifierInfo &parameterId =
  1609. context.Idents.get(name, tok::TokenKind::identifier);
  1610. ParmVarDecl *paramDecl =
  1611. ParmVarDecl::Create(context, functionDecl, NoLoc, NoLoc, &parameterId,
  1612. functionArgQualTypes[i], nullptr,
  1613. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  1614. functionDecl->addDecl(paramDecl);
  1615. paramDecls.push_back(paramDecl);
  1616. }
  1617. functionDecl->setParams(paramDecls);
  1618. functionDecl->setImplicit(true);
  1619. return functionDecl;
  1620. }
  1621. /// <summary>
  1622. /// Checks whether the specified expression is a (possibly parenthesized) comma operator.
  1623. /// </summary>
  1624. static
  1625. bool IsExpressionBinaryComma(_In_ const Expr* expr)
  1626. {
  1627. DXASSERT_NOMSG(expr != nullptr);
  1628. expr = expr->IgnoreParens();
  1629. return
  1630. expr->getStmtClass() == Expr::StmtClass::BinaryOperatorClass &&
  1631. cast<BinaryOperator>(expr)->getOpcode() == BinaryOperatorKind::BO_Comma;
  1632. }
  1633. /// <summary>
  1634. /// Silences diagnostics for the initialization sequence, typically because they have already
  1635. /// been emitted.
  1636. /// </summary>
  1637. static
  1638. void SilenceSequenceDiagnostics(_Inout_ InitializationSequence* initSequence)
  1639. {
  1640. DXASSERT_NOMSG(initSequence != nullptr);
  1641. initSequence->SetFailed(InitializationSequence::FK_ListInitializationFailed);
  1642. }
  1643. class UsedIntrinsic
  1644. {
  1645. public:
  1646. static int compareArgs(const QualType& LHS, const QualType& RHS)
  1647. {
  1648. // The canonical representations are unique'd in an ASTContext, and so these
  1649. // should be stable.
  1650. return RHS.getTypePtr() - LHS.getTypePtr();
  1651. }
  1652. static int compareIntrinsic(const HLSL_INTRINSIC* LHS, const HLSL_INTRINSIC* RHS)
  1653. {
  1654. // The intrinsics are defined in a single static table, and so should be stable.
  1655. return RHS - LHS;
  1656. }
  1657. int compare(const UsedIntrinsic& other) const
  1658. {
  1659. // Check whether it's the same instance.
  1660. if (this == &other) return 0;
  1661. int result = compareIntrinsic(m_intrinsicSource, other.m_intrinsicSource);
  1662. if (result != 0) return result;
  1663. // At this point, it's the exact same intrinsic name.
  1664. // Compare the arguments for ordering then.
  1665. DXASSERT(IsVariadicIntrinsicFunction(m_intrinsicSource) ||
  1666. m_args.size() == other.m_args.size(),
  1667. "only variadic intrinsics can be overloaded on argument count");
  1668. // For variadic functions with different number of args, order by number of
  1669. // arguments.
  1670. if (m_args.size() != other.m_args.size())
  1671. return m_args.size() - other.m_args.size();
  1672. for (size_t i = 0; i < m_args.size(); i++) {
  1673. int argComparison = compareArgs(m_args[i], other.m_args[i]);
  1674. if (argComparison != 0) return argComparison;
  1675. }
  1676. // Exactly the same.
  1677. return 0;
  1678. }
  1679. public:
  1680. UsedIntrinsic(const HLSL_INTRINSIC* intrinsicSource, llvm::ArrayRef<QualType> args)
  1681. : m_args(args.begin(), args.end()), m_intrinsicSource(intrinsicSource), m_functionDecl(nullptr)
  1682. {
  1683. }
  1684. void setFunctionDecl(FunctionDecl* value) const
  1685. {
  1686. DXASSERT(value != nullptr, "no reason to clear this out");
  1687. DXASSERT(m_functionDecl == nullptr, "otherwise cached value is being invaldiated");
  1688. m_functionDecl = value;
  1689. }
  1690. FunctionDecl* getFunctionDecl() const { return m_functionDecl; }
  1691. bool operator==(const UsedIntrinsic& other) const
  1692. {
  1693. return compare(other) == 0;
  1694. }
  1695. bool operator<(const UsedIntrinsic& other) const
  1696. {
  1697. return compare(other) < 0;
  1698. }
  1699. private:
  1700. std::vector<QualType> m_args;
  1701. const HLSL_INTRINSIC* m_intrinsicSource;
  1702. mutable FunctionDecl* m_functionDecl;
  1703. };
  1704. template <typename T>
  1705. inline void AssignOpt(T value, _Out_opt_ T* ptr)
  1706. {
  1707. if (ptr != nullptr)
  1708. {
  1709. *ptr = value;
  1710. }
  1711. }
  1712. static bool CombineBasicTypes(ArBasicKind LeftKind,
  1713. ArBasicKind RightKind,
  1714. _Out_ ArBasicKind* pOutKind)
  1715. {
  1716. if ((LeftKind < 0 || LeftKind >= AR_BASIC_COUNT) ||
  1717. (RightKind < 0 || RightKind >= AR_BASIC_COUNT)) {
  1718. return false;
  1719. }
  1720. if (LeftKind == RightKind) {
  1721. *pOutKind = LeftKind;
  1722. return true;
  1723. }
  1724. UINT uLeftProps = GetBasicKindProps(LeftKind);
  1725. UINT uRightProps = GetBasicKindProps(RightKind);
  1726. UINT uBits = GET_BPROP_BITS(uLeftProps) > GET_BPROP_BITS(uRightProps) ?
  1727. GET_BPROP_BITS(uLeftProps) : GET_BPROP_BITS(uRightProps);
  1728. UINT uBothFlags = uLeftProps & uRightProps;
  1729. UINT uEitherFlags = uLeftProps | uRightProps;
  1730. // Notes: all numeric types have either BPROP_FLOATING or BPROP_INTEGER (even bool)
  1731. // unsigned only applies to non-literal ints, not bool or enum
  1732. // literals, bool, and enum are all BPROP_BITS0
  1733. if (uBothFlags & BPROP_BOOLEAN) {
  1734. *pOutKind = AR_BASIC_BOOL;
  1735. return true;
  1736. }
  1737. bool bFloatResult = 0 != (uEitherFlags & BPROP_FLOATING);
  1738. if (uBothFlags & BPROP_LITERAL) {
  1739. *pOutKind = bFloatResult ? AR_BASIC_LITERAL_FLOAT : AR_BASIC_LITERAL_INT;
  1740. return true;
  1741. }
  1742. // Starting approximation of result properties:
  1743. // - float if either are float, otherwise int (see Notes above)
  1744. // - min/partial precision if both have same flag
  1745. // - if not float, add unsigned if either is unsigned
  1746. UINT uResultFlags =
  1747. (uBothFlags & (BPROP_INTEGER | BPROP_MIN_PRECISION | BPROP_PARTIAL_PRECISION)) |
  1748. (uEitherFlags & BPROP_FLOATING) |
  1749. (!bFloatResult ? (uEitherFlags & BPROP_UNSIGNED) : 0);
  1750. // If one is literal/bool/enum, use min/partial precision from the other
  1751. if (uEitherFlags & (BPROP_LITERAL | BPROP_BOOLEAN | BPROP_ENUM)) {
  1752. uResultFlags |= uEitherFlags & (BPROP_MIN_PRECISION | BPROP_PARTIAL_PRECISION);
  1753. }
  1754. // Now if we have partial precision, we know the result must be half
  1755. if (uResultFlags & BPROP_PARTIAL_PRECISION) {
  1756. *pOutKind = AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  1757. return true;
  1758. }
  1759. // uBits are already initialized to max of either side, so now:
  1760. // if only one is float, get result props from float side
  1761. // min16float + int -> min16float
  1762. // also take min precision from that side
  1763. if (bFloatResult && 0 == (uBothFlags & BPROP_FLOATING)) {
  1764. uResultFlags = (uLeftProps & BPROP_FLOATING) ? uLeftProps : uRightProps;
  1765. uBits = GET_BPROP_BITS(uResultFlags);
  1766. uResultFlags &= ~BPROP_LITERAL;
  1767. }
  1768. bool bMinPrecisionResult = uResultFlags & BPROP_MIN_PRECISION;
  1769. // if uBits is 0 here, upgrade to 32-bits
  1770. // this happens if bool, literal or enum on both sides,
  1771. // or if float came from literal side
  1772. if (uBits == BPROP_BITS0)
  1773. uBits = BPROP_BITS32;
  1774. DXASSERT(uBits != BPROP_BITS0, "CombineBasicTypes: uBits should not be zero at this point");
  1775. DXASSERT(uBits != BPROP_BITS8, "CombineBasicTypes: 8-bit types not supported at this time");
  1776. if (bMinPrecisionResult) {
  1777. DXASSERT(uBits < BPROP_BITS32, "CombineBasicTypes: min-precision result must be less than 32-bits");
  1778. } else {
  1779. DXASSERT(uBits > BPROP_BITS12, "CombineBasicTypes: 10 or 12 bit result must be min precision");
  1780. }
  1781. if (bFloatResult) {
  1782. DXASSERT(uBits != BPROP_BITS12, "CombineBasicTypes: 12-bit result must be int");
  1783. } else {
  1784. DXASSERT(uBits != BPROP_BITS10, "CombineBasicTypes: 10-bit result must be float");
  1785. }
  1786. if (uBits == BPROP_BITS12) {
  1787. DXASSERT(!(uResultFlags & BPROP_UNSIGNED), "CombineBasicTypes: 12-bit result must not be unsigned");
  1788. }
  1789. if (bFloatResult) {
  1790. switch (uBits) {
  1791. case BPROP_BITS10:
  1792. *pOutKind = AR_BASIC_MIN10FLOAT;
  1793. break;
  1794. case BPROP_BITS16:
  1795. *pOutKind = bMinPrecisionResult ? AR_BASIC_MIN16FLOAT : AR_BASIC_FLOAT16;
  1796. break;
  1797. case BPROP_BITS32:
  1798. *pOutKind = AR_BASIC_FLOAT32;
  1799. break;
  1800. case BPROP_BITS64:
  1801. *pOutKind = AR_BASIC_FLOAT64;
  1802. break;
  1803. default:
  1804. DXASSERT(false, "Unexpected bit count for float result");
  1805. break;
  1806. }
  1807. } else {
  1808. // int or unsigned int
  1809. switch (uBits) {
  1810. case BPROP_BITS12:
  1811. *pOutKind = AR_BASIC_MIN12INT;
  1812. break;
  1813. case BPROP_BITS16:
  1814. if (uResultFlags & BPROP_UNSIGNED)
  1815. *pOutKind = bMinPrecisionResult ? AR_BASIC_MIN16UINT : AR_BASIC_UINT16;
  1816. else
  1817. *pOutKind = bMinPrecisionResult ? AR_BASIC_MIN16INT : AR_BASIC_INT16;
  1818. break;
  1819. case BPROP_BITS32:
  1820. *pOutKind = (uResultFlags & BPROP_UNSIGNED) ? AR_BASIC_UINT32 : AR_BASIC_INT32;
  1821. break;
  1822. case BPROP_BITS64:
  1823. *pOutKind = (uResultFlags & BPROP_UNSIGNED) ? AR_BASIC_UINT64 : AR_BASIC_INT64;
  1824. break;
  1825. default:
  1826. DXASSERT(false, "Unexpected bit count for int result");
  1827. break;
  1828. }
  1829. }
  1830. return true;
  1831. }
  1832. class UsedIntrinsicStore : public std::set<UsedIntrinsic>
  1833. {
  1834. };
  1835. static
  1836. void GetIntrinsicMethods(ArBasicKind kind, _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics, _Out_ size_t* intrinsicCount)
  1837. {
  1838. DXASSERT_NOMSG(intrinsics != nullptr);
  1839. DXASSERT_NOMSG(intrinsicCount != nullptr);
  1840. switch (kind)
  1841. {
  1842. case AR_OBJECT_TRIANGLESTREAM:
  1843. case AR_OBJECT_POINTSTREAM:
  1844. case AR_OBJECT_LINESTREAM:
  1845. *intrinsics = g_StreamMethods;
  1846. *intrinsicCount = _countof(g_StreamMethods);
  1847. break;
  1848. case AR_OBJECT_TEXTURE1D:
  1849. *intrinsics = g_Texture1DMethods;
  1850. *intrinsicCount = _countof(g_Texture1DMethods);
  1851. break;
  1852. case AR_OBJECT_TEXTURE1D_ARRAY:
  1853. *intrinsics = g_Texture1DArrayMethods;
  1854. *intrinsicCount = _countof(g_Texture1DArrayMethods);
  1855. break;
  1856. case AR_OBJECT_TEXTURE2D:
  1857. *intrinsics = g_Texture2DMethods;
  1858. *intrinsicCount = _countof(g_Texture2DMethods);
  1859. break;
  1860. case AR_OBJECT_TEXTURE2DMS:
  1861. *intrinsics = g_Texture2DMSMethods;
  1862. *intrinsicCount = _countof(g_Texture2DMSMethods);
  1863. break;
  1864. case AR_OBJECT_TEXTURE2D_ARRAY:
  1865. *intrinsics = g_Texture2DArrayMethods;
  1866. *intrinsicCount = _countof(g_Texture2DArrayMethods);
  1867. break;
  1868. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  1869. *intrinsics = g_Texture2DArrayMSMethods;
  1870. *intrinsicCount = _countof(g_Texture2DArrayMSMethods);
  1871. break;
  1872. case AR_OBJECT_TEXTURE3D:
  1873. *intrinsics = g_Texture3DMethods;
  1874. *intrinsicCount = _countof(g_Texture3DMethods);
  1875. break;
  1876. case AR_OBJECT_TEXTURECUBE:
  1877. *intrinsics = g_TextureCUBEMethods;
  1878. *intrinsicCount = _countof(g_TextureCUBEMethods);
  1879. break;
  1880. case AR_OBJECT_TEXTURECUBE_ARRAY:
  1881. *intrinsics = g_TextureCUBEArrayMethods;
  1882. *intrinsicCount = _countof(g_TextureCUBEArrayMethods);
  1883. break;
  1884. case AR_OBJECT_BUFFER:
  1885. *intrinsics = g_BufferMethods;
  1886. *intrinsicCount = _countof(g_BufferMethods);
  1887. break;
  1888. case AR_OBJECT_RWTEXTURE1D:
  1889. case AR_OBJECT_ROVTEXTURE1D:
  1890. *intrinsics = g_RWTexture1DMethods;
  1891. *intrinsicCount = _countof(g_RWTexture1DMethods);
  1892. break;
  1893. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  1894. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  1895. *intrinsics = g_RWTexture1DArrayMethods;
  1896. *intrinsicCount = _countof(g_RWTexture1DArrayMethods);
  1897. break;
  1898. case AR_OBJECT_RWTEXTURE2D:
  1899. case AR_OBJECT_ROVTEXTURE2D:
  1900. *intrinsics = g_RWTexture2DMethods;
  1901. *intrinsicCount = _countof(g_RWTexture2DMethods);
  1902. break;
  1903. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  1904. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  1905. *intrinsics = g_RWTexture2DArrayMethods;
  1906. *intrinsicCount = _countof(g_RWTexture2DArrayMethods);
  1907. break;
  1908. case AR_OBJECT_RWTEXTURE3D:
  1909. case AR_OBJECT_ROVTEXTURE3D:
  1910. *intrinsics = g_RWTexture3DMethods;
  1911. *intrinsicCount = _countof(g_RWTexture3DMethods);
  1912. break;
  1913. case AR_OBJECT_FEEDBACKTEXTURE2D:
  1914. *intrinsics = g_FeedbackTexture2DMethods;
  1915. *intrinsicCount = _countof(g_FeedbackTexture2DMethods);
  1916. break;
  1917. case AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY:
  1918. *intrinsics = g_FeedbackTexture2DArrayMethods;
  1919. *intrinsicCount = _countof(g_FeedbackTexture2DArrayMethods);
  1920. break;
  1921. case AR_OBJECT_RWBUFFER:
  1922. case AR_OBJECT_ROVBUFFER:
  1923. *intrinsics = g_RWBufferMethods;
  1924. *intrinsicCount = _countof(g_RWBufferMethods);
  1925. break;
  1926. case AR_OBJECT_BYTEADDRESS_BUFFER:
  1927. *intrinsics = g_ByteAddressBufferMethods;
  1928. *intrinsicCount = _countof(g_ByteAddressBufferMethods);
  1929. break;
  1930. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  1931. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  1932. *intrinsics = g_RWByteAddressBufferMethods;
  1933. *intrinsicCount = _countof(g_RWByteAddressBufferMethods);
  1934. break;
  1935. case AR_OBJECT_STRUCTURED_BUFFER:
  1936. *intrinsics = g_StructuredBufferMethods;
  1937. *intrinsicCount = _countof(g_StructuredBufferMethods);
  1938. break;
  1939. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  1940. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  1941. *intrinsics = g_RWStructuredBufferMethods;
  1942. *intrinsicCount = _countof(g_RWStructuredBufferMethods);
  1943. break;
  1944. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  1945. *intrinsics = g_AppendStructuredBufferMethods;
  1946. *intrinsicCount = _countof(g_AppendStructuredBufferMethods);
  1947. break;
  1948. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  1949. *intrinsics = g_ConsumeStructuredBufferMethods;
  1950. *intrinsicCount = _countof(g_ConsumeStructuredBufferMethods);
  1951. break;
  1952. case AR_OBJECT_RAY_QUERY:
  1953. *intrinsics = g_RayQueryMethods;
  1954. *intrinsicCount = _countof(g_RayQueryMethods);
  1955. break;
  1956. // SPIRV change starts
  1957. #ifdef ENABLE_SPIRV_CODEGEN
  1958. case AR_OBJECT_VK_SUBPASS_INPUT:
  1959. *intrinsics = g_VkSubpassInputMethods;
  1960. *intrinsicCount = _countof(g_VkSubpassInputMethods);
  1961. break;
  1962. case AR_OBJECT_VK_SUBPASS_INPUT_MS:
  1963. *intrinsics = g_VkSubpassInputMSMethods;
  1964. *intrinsicCount = _countof(g_VkSubpassInputMSMethods);
  1965. break;
  1966. #endif // ENABLE_SPIRV_CODEGEN
  1967. // SPIRV change ends
  1968. default:
  1969. *intrinsics = nullptr;
  1970. *intrinsicCount = 0;
  1971. break;
  1972. }
  1973. }
  1974. static
  1975. bool IsRowOrColumnVariable(size_t value)
  1976. {
  1977. return IA_SPECIAL_BASE <= value && value <= (IA_SPECIAL_BASE + IA_SPECIAL_SLOTS - 1);
  1978. }
  1979. static
  1980. bool DoesComponentTypeAcceptMultipleTypes(LEGAL_INTRINSIC_COMPTYPES value)
  1981. {
  1982. return
  1983. value == LICOMPTYPE_ANY_INT || // signed or unsigned ints
  1984. value == LICOMPTYPE_ANY_INT32 || // signed or unsigned ints
  1985. value == LICOMPTYPE_ANY_FLOAT || // float or double
  1986. value == LICOMPTYPE_FLOAT_LIKE || // float or min16
  1987. value == LICOMPTYPE_FLOAT_DOUBLE || // float or double
  1988. value == LICOMPTYPE_NUMERIC || // all sorts of numbers
  1989. value == LICOMPTYPE_NUMERIC32 || // all sorts of numbers
  1990. value == LICOMPTYPE_NUMERIC32_ONLY || // all sorts of numbers
  1991. value == LICOMPTYPE_ANY; // any time
  1992. }
  1993. static
  1994. bool DoesComponentTypeAcceptMultipleTypes(BYTE value)
  1995. {
  1996. return DoesComponentTypeAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_COMPTYPES>(value));
  1997. }
  1998. static
  1999. bool DoesLegalTemplateAcceptMultipleTypes(LEGAL_INTRINSIC_TEMPLATES value)
  2000. {
  2001. // Note that LITEMPLATE_OBJECT can accept different types, but it
  2002. // specifies a single 'layout'. In practice, this information is used
  2003. // together with a component type that specifies a single object.
  2004. return value == LITEMPLATE_ANY; // Any layout
  2005. }
  2006. static
  2007. bool DoesLegalTemplateAcceptMultipleTypes(BYTE value)
  2008. {
  2009. return DoesLegalTemplateAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_TEMPLATES>(value));
  2010. }
  2011. static
  2012. bool TemplateHasDefaultType(ArBasicKind kind)
  2013. {
  2014. switch (kind) {
  2015. case AR_OBJECT_BUFFER:
  2016. case AR_OBJECT_TEXTURE1D:
  2017. case AR_OBJECT_TEXTURE2D:
  2018. case AR_OBJECT_TEXTURE3D:
  2019. case AR_OBJECT_TEXTURE1D_ARRAY:
  2020. case AR_OBJECT_TEXTURE2D_ARRAY:
  2021. case AR_OBJECT_TEXTURECUBE:
  2022. case AR_OBJECT_TEXTURECUBE_ARRAY:
  2023. // SPIRV change starts
  2024. #ifdef ENABLE_SPIRV_CODEGEN
  2025. case AR_OBJECT_VK_SUBPASS_INPUT:
  2026. case AR_OBJECT_VK_SUBPASS_INPUT_MS:
  2027. #endif // ENABLE_SPIRV_CODEGEN
  2028. // SPIRV change ends
  2029. return true;
  2030. default:
  2031. // Objects with default types return true. Everything else is false.
  2032. return false;
  2033. }
  2034. }
  2035. /// <summary>
  2036. /// Use this class to iterate over intrinsic definitions that come from an external source.
  2037. /// </summary>
  2038. class IntrinsicTableDefIter
  2039. {
  2040. private:
  2041. StringRef _typeName;
  2042. StringRef _functionName;
  2043. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& _tables;
  2044. const HLSL_INTRINSIC* _tableIntrinsic;
  2045. UINT64 _tableLookupCookie;
  2046. unsigned _tableIndex;
  2047. unsigned _argCount;
  2048. bool _firstChecked;
  2049. IntrinsicTableDefIter(
  2050. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  2051. StringRef typeName,
  2052. StringRef functionName,
  2053. unsigned argCount) :
  2054. _typeName(typeName), _functionName(functionName), _tables(tables),
  2055. _tableIntrinsic(nullptr), _tableLookupCookie(0), _tableIndex(0),
  2056. _argCount(argCount), _firstChecked(false)
  2057. {
  2058. }
  2059. void CheckForIntrinsic() {
  2060. if (_tableIndex >= _tables.size()) {
  2061. return;
  2062. }
  2063. _firstChecked = true;
  2064. // TODO: review this - this will allocate at least once per string
  2065. CA2WEX<> typeName(_typeName.str().c_str(), CP_UTF8);
  2066. CA2WEX<> functionName(_functionName.str().c_str(), CP_UTF8);
  2067. if (FAILED(_tables[_tableIndex]->LookupIntrinsic(
  2068. typeName, functionName, &_tableIntrinsic, &_tableLookupCookie))) {
  2069. _tableLookupCookie = 0;
  2070. _tableIntrinsic = nullptr;
  2071. }
  2072. }
  2073. void MoveToNext() {
  2074. for (;;) {
  2075. // If we don't have an intrinsic, try the following table.
  2076. if (_firstChecked && _tableIntrinsic == nullptr) {
  2077. _tableIndex++;
  2078. }
  2079. CheckForIntrinsic();
  2080. if (_tableIndex == _tables.size() ||
  2081. (_tableIntrinsic != nullptr &&
  2082. _tableIntrinsic->uNumArgs ==
  2083. (_argCount + 1))) // uNumArgs includes return
  2084. break;
  2085. }
  2086. }
  2087. public:
  2088. static IntrinsicTableDefIter CreateStart(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  2089. StringRef typeName,
  2090. StringRef functionName,
  2091. unsigned argCount)
  2092. {
  2093. IntrinsicTableDefIter result(tables, typeName, functionName, argCount);
  2094. return result;
  2095. }
  2096. static IntrinsicTableDefIter CreateEnd(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables)
  2097. {
  2098. IntrinsicTableDefIter result(tables, StringRef(), StringRef(), 0);
  2099. result._tableIndex = tables.size();
  2100. return result;
  2101. }
  2102. bool operator!=(const IntrinsicTableDefIter& other)
  2103. {
  2104. if (!_firstChecked) {
  2105. MoveToNext();
  2106. }
  2107. return _tableIndex != other._tableIndex; // More things could be compared but we only match end.
  2108. }
  2109. const HLSL_INTRINSIC* operator*()
  2110. {
  2111. DXASSERT(_firstChecked, "otherwise deref without comparing to end");
  2112. return _tableIntrinsic;
  2113. }
  2114. LPCSTR GetTableName()
  2115. {
  2116. LPCSTR tableName = nullptr;
  2117. if (FAILED(_tables[_tableIndex]->GetTableName(&tableName))) {
  2118. return nullptr;
  2119. }
  2120. return tableName;
  2121. }
  2122. LPCSTR GetLoweringStrategy()
  2123. {
  2124. LPCSTR lowering = nullptr;
  2125. if (FAILED(_tables[_tableIndex]->GetLoweringStrategy(_tableIntrinsic->Op, &lowering))) {
  2126. return nullptr;
  2127. }
  2128. return lowering;
  2129. }
  2130. IntrinsicTableDefIter& operator++()
  2131. {
  2132. MoveToNext();
  2133. return *this;
  2134. }
  2135. };
  2136. /// <summary>
  2137. /// Use this class to iterate over intrinsic definitions that have the same name and parameter count.
  2138. /// </summary>
  2139. class IntrinsicDefIter
  2140. {
  2141. const HLSL_INTRINSIC* _current;
  2142. const HLSL_INTRINSIC* _end;
  2143. IntrinsicTableDefIter _tableIter;
  2144. IntrinsicDefIter(const HLSL_INTRINSIC* value, const HLSL_INTRINSIC* end, IntrinsicTableDefIter tableIter) :
  2145. _current(value), _end(end), _tableIter(tableIter)
  2146. { }
  2147. public:
  2148. static IntrinsicDefIter CreateStart(const HLSL_INTRINSIC* table, size_t count, const HLSL_INTRINSIC* start, IntrinsicTableDefIter tableIter)
  2149. {
  2150. return IntrinsicDefIter(start, table + count, tableIter);
  2151. }
  2152. static IntrinsicDefIter CreateEnd(const HLSL_INTRINSIC* table, size_t count, IntrinsicTableDefIter tableIter)
  2153. {
  2154. return IntrinsicDefIter(table + count, table + count, tableIter);
  2155. }
  2156. bool operator!=(const IntrinsicDefIter& other)
  2157. {
  2158. return _current != other._current || _tableIter.operator!=(other._tableIter);
  2159. }
  2160. const HLSL_INTRINSIC* operator*()
  2161. {
  2162. return (_current != _end) ? _current : *_tableIter;
  2163. }
  2164. LPCSTR GetTableName()
  2165. {
  2166. return (_current != _end) ? kBuiltinIntrinsicTableName : _tableIter.GetTableName();
  2167. }
  2168. LPCSTR GetLoweringStrategy()
  2169. {
  2170. return (_current != _end) ? "" : _tableIter.GetLoweringStrategy();
  2171. }
  2172. IntrinsicDefIter& operator++()
  2173. {
  2174. if (_current != _end) {
  2175. const HLSL_INTRINSIC* next = _current + 1;
  2176. if (next != _end && _current->uNumArgs == next->uNumArgs && 0 == strcmp(_current->pArgs[0].pName, next->pArgs[0].pName)) {
  2177. _current = next;
  2178. }
  2179. else {
  2180. _current = _end;
  2181. }
  2182. } else {
  2183. ++_tableIter;
  2184. }
  2185. return *this;
  2186. }
  2187. };
  2188. static void AddHLSLSubscriptAttr(Decl *D, ASTContext &context, HLSubscriptOpcode opcode) {
  2189. StringRef group = GetHLOpcodeGroupName(HLOpcodeGroup::HLSubscript);
  2190. D->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, group, "", static_cast<unsigned>(opcode)));
  2191. }
  2192. static void CreateSimpleField(clang::ASTContext &context, CXXRecordDecl *recordDecl, StringRef Name,
  2193. QualType Ty, AccessSpecifier access = AccessSpecifier::AS_public) {
  2194. IdentifierInfo &fieldId =
  2195. context.Idents.get(Name, tok::TokenKind::identifier);
  2196. TypeSourceInfo *filedTypeSource = context.getTrivialTypeSourceInfo(Ty, NoLoc);
  2197. const bool MutableFalse = false;
  2198. const InClassInitStyle initStyle = InClassInitStyle::ICIS_NoInit;
  2199. FieldDecl *fieldDecl =
  2200. FieldDecl::Create(context, recordDecl, NoLoc, NoLoc, &fieldId, Ty,
  2201. filedTypeSource, nullptr, MutableFalse, initStyle);
  2202. fieldDecl->setAccess(access);
  2203. fieldDecl->setImplicit(true);
  2204. recordDecl->addDecl(fieldDecl);
  2205. }
  2206. // struct RayDesc
  2207. //{
  2208. // float3 Origin;
  2209. // float TMin;
  2210. // float3 Direction;
  2211. // float TMax;
  2212. //};
  2213. static CXXRecordDecl *CreateRayDescStruct(clang::ASTContext &context,
  2214. QualType float3Ty) {
  2215. DeclContext *currentDeclContext = context.getTranslationUnitDecl();
  2216. IdentifierInfo &rayDesc =
  2217. context.Idents.get(StringRef("RayDesc"), tok::TokenKind::identifier);
  2218. CXXRecordDecl *rayDescDecl = CXXRecordDecl::Create(
  2219. context, TagTypeKind::TTK_Struct, currentDeclContext, NoLoc, NoLoc,
  2220. &rayDesc, nullptr, DelayTypeCreationTrue);
  2221. rayDescDecl->addAttr(FinalAttr::CreateImplicit(context, FinalAttr::Keyword_final));
  2222. rayDescDecl->startDefinition();
  2223. QualType floatTy = context.FloatTy;
  2224. // float3 Origin;
  2225. CreateSimpleField(context, rayDescDecl, "Origin", float3Ty);
  2226. // float TMin;
  2227. CreateSimpleField(context, rayDescDecl, "TMin", floatTy);
  2228. // float3 Direction;
  2229. CreateSimpleField(context, rayDescDecl, "Direction", float3Ty);
  2230. // float TMax;
  2231. CreateSimpleField(context, rayDescDecl, "TMax", floatTy);
  2232. rayDescDecl->completeDefinition();
  2233. // Both declarations need to be present for correct handling.
  2234. currentDeclContext->addDecl(rayDescDecl);
  2235. rayDescDecl->setImplicit(true);
  2236. return rayDescDecl;
  2237. }
  2238. // struct BuiltInTriangleIntersectionAttributes
  2239. // {
  2240. // float2 barycentrics;
  2241. // };
  2242. static CXXRecordDecl *AddBuiltInTriangleIntersectionAttributes(ASTContext& context, QualType baryType) {
  2243. DeclContext *curDC = context.getTranslationUnitDecl();
  2244. IdentifierInfo &attributesId =
  2245. context.Idents.get(StringRef("BuiltInTriangleIntersectionAttributes"),
  2246. tok::TokenKind::identifier);
  2247. CXXRecordDecl *attributesDecl = CXXRecordDecl::Create(
  2248. context, TagTypeKind::TTK_Struct, curDC, NoLoc, NoLoc,
  2249. &attributesId, nullptr, DelayTypeCreationTrue);
  2250. attributesDecl->addAttr(FinalAttr::CreateImplicit(context, FinalAttr::Keyword_final));
  2251. attributesDecl->startDefinition();
  2252. // float2 barycentrics;
  2253. CreateSimpleField(context, attributesDecl, "barycentrics", baryType);
  2254. attributesDecl->completeDefinition();
  2255. attributesDecl->setImplicit(true);
  2256. curDC->addDecl(attributesDecl);
  2257. return attributesDecl;
  2258. }
  2259. //
  2260. // Subobjects
  2261. static CXXRecordDecl *StartSubobjectDecl(ASTContext& context, const char *name) {
  2262. IdentifierInfo &id = context.Idents.get(StringRef(name), tok::TokenKind::identifier);
  2263. CXXRecordDecl *decl = CXXRecordDecl::Create( context, TagTypeKind::TTK_Struct,
  2264. context.getTranslationUnitDecl(), NoLoc, NoLoc, &id, nullptr, DelayTypeCreationTrue);
  2265. decl->addAttr(FinalAttr::CreateImplicit(context, FinalAttr::Keyword_final));
  2266. decl->startDefinition();
  2267. return decl;
  2268. }
  2269. void FinishSubobjectDecl(ASTContext& context, CXXRecordDecl *decl) {
  2270. decl->completeDefinition();
  2271. context.getTranslationUnitDecl()->addDecl(decl);
  2272. decl->setImplicit(true);
  2273. }
  2274. // struct StateObjectConfig
  2275. // {
  2276. // uint32_t Flags;
  2277. // };
  2278. static CXXRecordDecl *CreateSubobjectStateObjectConfig(ASTContext& context) {
  2279. CXXRecordDecl *decl = StartSubobjectDecl(context, "StateObjectConfig");
  2280. CreateSimpleField(context, decl, "Flags", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2281. FinishSubobjectDecl(context, decl);
  2282. return decl;
  2283. }
  2284. // struct GlobalRootSignature
  2285. // {
  2286. // string signature;
  2287. // };
  2288. static CXXRecordDecl *CreateSubobjectRootSignature(ASTContext& context, bool global) {
  2289. CXXRecordDecl *decl = StartSubobjectDecl(context, global ? "GlobalRootSignature" : "LocalRootSignature");
  2290. CreateSimpleField(context, decl, "Data", context.HLSLStringTy, AccessSpecifier::AS_private);
  2291. FinishSubobjectDecl(context, decl);
  2292. return decl;
  2293. }
  2294. // struct SubobjectToExportsAssociation
  2295. // {
  2296. // string Subobject;
  2297. // string Exports;
  2298. // };
  2299. static CXXRecordDecl *CreateSubobjectSubobjectToExportsAssoc(ASTContext& context) {
  2300. CXXRecordDecl *decl = StartSubobjectDecl(context, "SubobjectToExportsAssociation");
  2301. CreateSimpleField(context, decl, "Subobject", context.HLSLStringTy, AccessSpecifier::AS_private);
  2302. CreateSimpleField(context, decl, "Exports", context.HLSLStringTy, AccessSpecifier::AS_private);
  2303. FinishSubobjectDecl(context, decl);
  2304. return decl;
  2305. }
  2306. // struct RaytracingShaderConfig
  2307. // {
  2308. // uint32_t MaxPayloadSizeInBytes;
  2309. // uint32_t MaxAttributeSizeInBytes;
  2310. // };
  2311. static CXXRecordDecl *CreateSubobjectRaytracingShaderConfig(ASTContext& context) {
  2312. CXXRecordDecl *decl = StartSubobjectDecl(context, "RaytracingShaderConfig");
  2313. CreateSimpleField(context, decl, "MaxPayloadSizeInBytes", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2314. CreateSimpleField(context, decl, "MaxAttributeSizeInBytes", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2315. FinishSubobjectDecl(context, decl);
  2316. return decl;
  2317. }
  2318. // struct RaytracingPipelineConfig
  2319. // {
  2320. // uint32_t MaxTraceRecursionDepth;
  2321. // };
  2322. static CXXRecordDecl *CreateSubobjectRaytracingPipelineConfig(ASTContext& context) {
  2323. CXXRecordDecl *decl = StartSubobjectDecl(context, "RaytracingPipelineConfig");
  2324. CreateSimpleField(context, decl, "MaxTraceRecursionDepth", context.UnsignedIntTy, AccessSpecifier::AS_private);
  2325. FinishSubobjectDecl(context, decl);
  2326. return decl;
  2327. }
  2328. // struct RaytracingPipelineConfig1
  2329. // {
  2330. // uint32_t MaxTraceRecursionDepth;
  2331. // uint32_t Flags;
  2332. // };
  2333. static CXXRecordDecl *
  2334. CreateSubobjectRaytracingPipelineConfig1(ASTContext &context) {
  2335. CXXRecordDecl *decl =
  2336. StartSubobjectDecl(context, "RaytracingPipelineConfig1");
  2337. CreateSimpleField(context, decl, "MaxTraceRecursionDepth",
  2338. context.UnsignedIntTy, AccessSpecifier::AS_private);
  2339. CreateSimpleField(context, decl, "Flags", context.UnsignedIntTy,
  2340. AccessSpecifier::AS_private);
  2341. FinishSubobjectDecl(context, decl);
  2342. return decl;
  2343. }
  2344. // struct TriangleHitGroup
  2345. // {
  2346. // string AnyHit;
  2347. // string ClosestHit;
  2348. // };
  2349. static CXXRecordDecl *CreateSubobjectTriangleHitGroup(ASTContext& context) {
  2350. CXXRecordDecl *decl = StartSubobjectDecl(context, "TriangleHitGroup");
  2351. CreateSimpleField(context, decl, "AnyHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2352. CreateSimpleField(context, decl, "ClosestHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2353. FinishSubobjectDecl(context, decl);
  2354. return decl;
  2355. }
  2356. // struct ProceduralPrimitiveHitGroup
  2357. // {
  2358. // string AnyHit;
  2359. // string ClosestHit;
  2360. // string Intersection;
  2361. // };
  2362. static CXXRecordDecl *CreateSubobjectProceduralPrimitiveHitGroup(ASTContext& context) {
  2363. CXXRecordDecl *decl = StartSubobjectDecl(context, "ProceduralPrimitiveHitGroup");
  2364. CreateSimpleField(context, decl, "AnyHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2365. CreateSimpleField(context, decl, "ClosestHit", context.HLSLStringTy, AccessSpecifier::AS_private);
  2366. CreateSimpleField(context, decl, "Intersection", context.HLSLStringTy, AccessSpecifier::AS_private);
  2367. FinishSubobjectDecl(context, decl);
  2368. return decl;
  2369. }
  2370. //
  2371. // This is similar to clang/Analysis/CallGraph, but the following differences
  2372. // motivate this:
  2373. //
  2374. // - track traversed vs. observed nodes explicitly
  2375. // - fully visit all reachable functions
  2376. // - merge graph visiting with checking for recursion
  2377. // - track global variables and types used (NYI)
  2378. //
  2379. namespace hlsl {
  2380. struct CallNode {
  2381. FunctionDecl *CallerFn;
  2382. ::llvm::SmallPtrSet<FunctionDecl *, 4> CalleeFns;
  2383. };
  2384. typedef ::llvm::DenseMap<FunctionDecl*, CallNode> CallNodes;
  2385. typedef ::llvm::SmallPtrSet<Decl *, 8> FnCallStack;
  2386. typedef ::llvm::SmallPtrSet<FunctionDecl*, 128> FunctionSet;
  2387. typedef ::llvm::SmallVector<FunctionDecl*, 32> PendingFunctions;
  2388. // Returns the definition of a function.
  2389. // This serves two purposes - ignore built-in functions, and pick
  2390. // a single Decl * to be used in maps and sets.
  2391. static FunctionDecl *getFunctionWithBody(FunctionDecl *F) {
  2392. if (!F) return nullptr;
  2393. if (F->doesThisDeclarationHaveABody()) return F;
  2394. F = F->getFirstDecl();
  2395. for (auto &&Candidate : F->redecls()) {
  2396. if (Candidate->doesThisDeclarationHaveABody()) {
  2397. return Candidate;
  2398. }
  2399. }
  2400. return nullptr;
  2401. }
  2402. // AST visitor that maintains visited and pending collections, as well
  2403. // as recording nodes of caller/callees.
  2404. class FnReferenceVisitor : public RecursiveASTVisitor<FnReferenceVisitor> {
  2405. private:
  2406. CallNodes &m_callNodes;
  2407. FunctionSet &m_visitedFunctions;
  2408. PendingFunctions &m_pendingFunctions;
  2409. FunctionDecl *m_source;
  2410. CallNodes::iterator m_sourceIt;
  2411. public:
  2412. FnReferenceVisitor(FunctionSet &visitedFunctions,
  2413. PendingFunctions &pendingFunctions, CallNodes &callNodes)
  2414. : m_callNodes(callNodes),
  2415. m_visitedFunctions(visitedFunctions),
  2416. m_pendingFunctions(pendingFunctions) {}
  2417. void setSourceFn(FunctionDecl *F) {
  2418. F = getFunctionWithBody(F);
  2419. m_source = F;
  2420. m_sourceIt = m_callNodes.find(F);
  2421. }
  2422. bool VisitDeclRefExpr(DeclRefExpr *ref) {
  2423. ValueDecl *valueDecl = ref->getDecl();
  2424. RecordFunctionDecl(dyn_cast_or_null<FunctionDecl>(valueDecl));
  2425. return true;
  2426. }
  2427. bool VisitCXXMemberCallExpr(CXXMemberCallExpr* callExpr)
  2428. {
  2429. RecordFunctionDecl(callExpr->getMethodDecl());
  2430. return true;
  2431. }
  2432. void RecordFunctionDecl(FunctionDecl* funcDecl)
  2433. {
  2434. funcDecl = getFunctionWithBody(funcDecl);
  2435. if (funcDecl) {
  2436. if (m_sourceIt == m_callNodes.end()) {
  2437. auto result = m_callNodes.insert(
  2438. std::pair<FunctionDecl*, CallNode>(m_source, CallNode{ m_source }));
  2439. DXASSERT(result.second == true,
  2440. "else setSourceFn didn't assign m_sourceIt");
  2441. m_sourceIt = result.first;
  2442. }
  2443. m_sourceIt->second.CalleeFns.insert(funcDecl);
  2444. if (!m_visitedFunctions.count(funcDecl)) {
  2445. m_pendingFunctions.push_back(funcDecl);
  2446. }
  2447. }
  2448. }
  2449. };
  2450. // A call graph that can check for reachability and recursion efficiently.
  2451. class CallGraphWithRecurseGuard {
  2452. private:
  2453. CallNodes m_callNodes;
  2454. FunctionSet m_visitedFunctions;
  2455. FunctionDecl *CheckRecursion(FnCallStack &CallStack,
  2456. FunctionDecl *D) const {
  2457. if (CallStack.insert(D).second == false)
  2458. return D;
  2459. auto node = m_callNodes.find(D);
  2460. if (node != m_callNodes.end()) {
  2461. for (FunctionDecl *Callee : node->second.CalleeFns) {
  2462. FunctionDecl *pResult = CheckRecursion(CallStack, Callee);
  2463. if (pResult)
  2464. return pResult;
  2465. }
  2466. }
  2467. CallStack.erase(D);
  2468. return nullptr;
  2469. }
  2470. public:
  2471. void BuildForEntry(FunctionDecl *EntryFnDecl) {
  2472. DXASSERT_NOMSG(EntryFnDecl);
  2473. EntryFnDecl = getFunctionWithBody(EntryFnDecl);
  2474. PendingFunctions pendingFunctions;
  2475. FnReferenceVisitor visitor(m_visitedFunctions, pendingFunctions, m_callNodes);
  2476. pendingFunctions.push_back(EntryFnDecl);
  2477. while (!pendingFunctions.empty()) {
  2478. FunctionDecl *pendingDecl = pendingFunctions.pop_back_val();
  2479. if (m_visitedFunctions.insert(pendingDecl).second == true) {
  2480. visitor.setSourceFn(pendingDecl);
  2481. visitor.TraverseDecl(pendingDecl);
  2482. }
  2483. }
  2484. }
  2485. FunctionDecl *CheckRecursion(FunctionDecl *EntryFnDecl) const {
  2486. FnCallStack CallStack;
  2487. EntryFnDecl = getFunctionWithBody(EntryFnDecl);
  2488. return CheckRecursion(CallStack, EntryFnDecl);
  2489. }
  2490. void dump() const {
  2491. OutputDebugStringW(L"Call Nodes:\r\n");
  2492. for (auto &node : m_callNodes) {
  2493. OutputDebugFormatA("%s [%p]:\r\n", node.first->getName().str().c_str(), (void*)node.first);
  2494. for (auto callee : node.second.CalleeFns) {
  2495. OutputDebugFormatA(" %s [%p]\r\n", callee->getName().str().c_str(), (void*)callee);
  2496. }
  2497. }
  2498. }
  2499. };
  2500. }
  2501. /// <summary>Creates a Typedef in the specified ASTContext.</summary>
  2502. static
  2503. TypedefDecl *CreateGlobalTypedef(ASTContext* context, const char* ident, QualType baseType)
  2504. {
  2505. DXASSERT_NOMSG(context != nullptr);
  2506. DXASSERT_NOMSG(ident != nullptr);
  2507. DXASSERT_NOMSG(!baseType.isNull());
  2508. DeclContext* declContext = context->getTranslationUnitDecl();
  2509. TypeSourceInfo* typeSource = context->getTrivialTypeSourceInfo(baseType);
  2510. TypedefDecl* decl = TypedefDecl::Create(*context, declContext, NoLoc, NoLoc, &context->Idents.get(ident), typeSource);
  2511. declContext->addDecl(decl);
  2512. decl->setImplicit(true);
  2513. return decl;
  2514. }
  2515. class HLSLExternalSource : public ExternalSemaSource {
  2516. private:
  2517. // Inner types.
  2518. struct FindStructBasicTypeResult {
  2519. ArBasicKind Kind; // Kind of struct (eg, AR_OBJECT_TEXTURE2D)
  2520. unsigned int BasicKindsAsTypeIndex; // Index into g_ArBasicKinds*
  2521. FindStructBasicTypeResult(ArBasicKind kind,
  2522. unsigned int basicKindAsTypeIndex)
  2523. : Kind(kind), BasicKindsAsTypeIndex(basicKindAsTypeIndex) {}
  2524. bool Found() const { return Kind != AR_BASIC_UNKNOWN; }
  2525. };
  2526. // Declaration for matrix and vector templates.
  2527. ClassTemplateDecl* m_matrixTemplateDecl;
  2528. ClassTemplateDecl* m_vectorTemplateDecl;
  2529. // Namespace decl for hlsl intrin functions
  2530. NamespaceDecl* m_hlslNSDecl;
  2531. // Context being processed.
  2532. _Notnull_ ASTContext* m_context;
  2533. // Semantic analyzer being processed.
  2534. Sema* m_sema;
  2535. // Intrinsic tables available externally.
  2536. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2> m_intrinsicTables;
  2537. // Scalar types indexed by HLSLScalarType.
  2538. QualType m_scalarTypes[HLSLScalarTypeCount];
  2539. // Scalar types already built.
  2540. TypedefDecl* m_scalarTypeDefs[HLSLScalarTypeCount];
  2541. // 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.
  2542. QualType m_matrixTypes[HLSLScalarTypeCount][4][4];
  2543. // Matrix types already built, in shorthand form.
  2544. TypedefDecl* m_matrixShorthandTypes[HLSLScalarTypeCount][4][4];
  2545. // Vector types already built.
  2546. QualType m_vectorTypes[HLSLScalarTypeCount][4];
  2547. TypedefDecl* m_vectorTypedefs[HLSLScalarTypeCount][4];
  2548. // BuiltinType for each scalar type.
  2549. QualType m_baseTypes[HLSLScalarTypeCount];
  2550. // String type
  2551. QualType m_hlslStringType;
  2552. TypedefDecl* m_hlslStringTypedef;
  2553. // Built-in object types declarations, indexed by basic kind constant.
  2554. CXXRecordDecl* m_objectTypeDecls[_countof(g_ArBasicKindsAsTypes)];
  2555. // Map from object decl to the object index.
  2556. using ObjectTypeDeclMapType = std::array<std::pair<CXXRecordDecl*,unsigned>, _countof(g_ArBasicKindsAsTypes)+_countof(g_DeprecatedEffectObjectNames)>;
  2557. ObjectTypeDeclMapType m_objectTypeDeclsMap;
  2558. // Mask for object which not has methods created.
  2559. uint64_t m_objectTypeLazyInitMask;
  2560. UsedIntrinsicStore m_usedIntrinsics;
  2561. /// <summary>Add all base QualTypes for each hlsl scalar types.</summary>
  2562. void AddBaseTypes();
  2563. /// <summary>Adds all supporting declarations to reference scalar types.</summary>
  2564. void AddHLSLScalarTypes();
  2565. /// <summary>Adds string type QualType for HSLS string declarations</summary>
  2566. void AddHLSLStringType();
  2567. QualType GetTemplateObjectDataType(_In_ CXXRecordDecl* recordDecl)
  2568. {
  2569. DXASSERT_NOMSG(recordDecl != nullptr);
  2570. TemplateParameterList* parameterList = recordDecl->getTemplateParameterList(0);
  2571. NamedDecl* parameterDecl = parameterList->getParam(0);
  2572. DXASSERT(parameterDecl->getKind() == Decl::Kind::TemplateTypeParm, "otherwise recordDecl isn't one of the built-in objects with templates");
  2573. TemplateTypeParmDecl* parmDecl = dyn_cast<TemplateTypeParmDecl>(parameterDecl);
  2574. return QualType(parmDecl->getTypeForDecl(), 0);
  2575. }
  2576. // Determines whether the given intrinsic parameter type has a single QualType mapping.
  2577. QualType GetSingleQualTypeForMapping(const HLSL_INTRINSIC* intrinsic, int index)
  2578. {
  2579. int templateRef = intrinsic->pArgs[index].uTemplateId;
  2580. int componentRef = intrinsic->pArgs[index].uComponentTypeId;
  2581. const HLSL_INTRINSIC_ARGUMENT* templateArg = &intrinsic->pArgs[templateRef];
  2582. const HLSL_INTRINSIC_ARGUMENT* componentArg = &intrinsic->pArgs[componentRef];
  2583. const HLSL_INTRINSIC_ARGUMENT* matrixArg = &intrinsic->pArgs[index];
  2584. if (
  2585. templateRef >= 0 &&
  2586. templateArg->uTemplateId == templateRef &&
  2587. !DoesLegalTemplateAcceptMultipleTypes(templateArg->uLegalTemplates) &&
  2588. componentRef >= 0 &&
  2589. componentRef != INTRIN_COMPTYPE_FROM_TYPE_ELT0 &&
  2590. componentArg->uComponentTypeId == 0 &&
  2591. !DoesComponentTypeAcceptMultipleTypes(componentArg->uLegalComponentTypes) &&
  2592. !IsRowOrColumnVariable(matrixArg->uCols) &&
  2593. !IsRowOrColumnVariable(matrixArg->uRows))
  2594. {
  2595. ArTypeObjectKind templateKind = g_LegalIntrinsicTemplates[templateArg->uLegalTemplates][0];
  2596. ArBasicKind elementKind = g_LegalIntrinsicCompTypes[componentArg->uLegalComponentTypes][0];
  2597. return NewSimpleAggregateType(templateKind, elementKind, 0, matrixArg->uRows, matrixArg->uCols);
  2598. }
  2599. return QualType();
  2600. }
  2601. // Adds a new template parameter declaration to the specified array and returns the type for the parameter.
  2602. QualType AddTemplateParamToArray(_In_z_ const char* name, _Inout_ CXXRecordDecl* recordDecl, int templateDepth,
  2603. _Inout_count_c_(g_MaxIntrinsicParamCount + 1) NamedDecl* (&templateParamNamedDecls)[g_MaxIntrinsicParamCount + 1],
  2604. _Inout_ size_t* templateParamNamedDeclsCount)
  2605. {
  2606. DXASSERT_NOMSG(name != nullptr);
  2607. DXASSERT_NOMSG(recordDecl != nullptr);
  2608. DXASSERT_NOMSG(templateParamNamedDecls != nullptr);
  2609. DXASSERT_NOMSG(templateParamNamedDeclsCount != nullptr);
  2610. DXASSERT(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls), "otherwise constants should be updated");
  2611. _Analysis_assume_(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls));
  2612. // Create the declaration for the template parameter.
  2613. IdentifierInfo* id = &m_context->Idents.get(StringRef(name));
  2614. TemplateTypeParmDecl* templateTypeParmDecl =
  2615. TemplateTypeParmDecl::Create(*m_context, recordDecl, NoLoc, NoLoc, templateDepth, *templateParamNamedDeclsCount,
  2616. id, TypenameTrue, ParameterPackFalse);
  2617. templateParamNamedDecls[*templateParamNamedDeclsCount] = templateTypeParmDecl;
  2618. // Create the type that the parameter represents.
  2619. QualType result = m_context->getTemplateTypeParmType(
  2620. templateDepth, *templateParamNamedDeclsCount, ParameterPackFalse, templateTypeParmDecl);
  2621. // Increment the declaration count for the array; as long as caller passes in both arguments,
  2622. // it need not concern itself with maintaining this value.
  2623. (*templateParamNamedDeclsCount)++;
  2624. return result;
  2625. }
  2626. // Adds a function specified by the given intrinsic to a record declaration.
  2627. // The template depth will be zero for records that don't have a "template<>" line
  2628. // even if conceptual; or one if it does have one.
  2629. void AddObjectIntrinsicTemplate(_Inout_ CXXRecordDecl* recordDecl, int templateDepth, _In_ const HLSL_INTRINSIC* intrinsic)
  2630. {
  2631. DXASSERT_NOMSG(recordDecl != nullptr);
  2632. DXASSERT_NOMSG(intrinsic != nullptr);
  2633. DXASSERT(intrinsic->uNumArgs > 0, "otherwise there isn't even an intrinsic name");
  2634. DXASSERT(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1), "otherwise g_MaxIntrinsicParamCount should be updated");
  2635. // uNumArgs includes the result type, g_MaxIntrinsicParamCount doesn't, thus the +1.
  2636. _Analysis_assume_(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1));
  2637. // TODO: implement template parameter constraints for HLSL intrinsic methods in declarations
  2638. //
  2639. // Build template parameters, parameter types, and the return type.
  2640. // Parameter declarations are built after the function is created, to use it as their scope.
  2641. //
  2642. unsigned int numParams = intrinsic->uNumArgs - 1;
  2643. NamedDecl* templateParamNamedDecls[g_MaxIntrinsicParamCount + 1];
  2644. size_t templateParamNamedDeclsCount = 0;
  2645. QualType argsQTs[g_MaxIntrinsicParamCount];
  2646. StringRef argNames[g_MaxIntrinsicParamCount];
  2647. QualType functionResultQT = recordDecl->getASTContext().VoidTy;
  2648. DXASSERT(
  2649. _countof(templateParamNamedDecls) >= numParams + 1,
  2650. "need enough templates for all parameters and the return type, otherwise constants need updating");
  2651. // Handle the return type.
  2652. // functionResultQT = GetSingleQualTypeForMapping(intrinsic, 0);
  2653. // if (functionResultQT.isNull()) {
  2654. // Workaround for template parameter argument count mismatch.
  2655. // Create template parameter for return type always
  2656. // TODO: reenable the check and skip template argument.
  2657. functionResultQT = AddTemplateParamToArray(
  2658. "TResult", recordDecl, templateDepth, templateParamNamedDecls,
  2659. &templateParamNamedDeclsCount);
  2660. // }
  2661. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  2662. InitParamMods(intrinsic, paramMods);
  2663. // Consider adding more cases where return type can be handled a priori. Ultimately #260431 should do significantly better.
  2664. // Handle parameters.
  2665. for (unsigned int i = 1; i < intrinsic->uNumArgs; i++)
  2666. {
  2667. //
  2668. // GetSingleQualTypeForMapping can be used here to remove unnecessary template arguments.
  2669. //
  2670. // However this may produce template instantiations with equivalent template arguments
  2671. // for overloaded methods. It's possible to resolve some of these by generating specializations,
  2672. // but the current intrinsic table has rules that are hard to process in their current form
  2673. // to find all cases.
  2674. //
  2675. char name[g_MaxIntrinsicParamName + 2];
  2676. name[0] = 'T';
  2677. name[1] = '\0';
  2678. strcat_s(name, intrinsic->pArgs[i].pName);
  2679. argsQTs[i - 1] = AddTemplateParamToArray(name, recordDecl, templateDepth, templateParamNamedDecls, &templateParamNamedDeclsCount);
  2680. // Change out/inout param to reference type.
  2681. if (paramMods[i-1].isAnyOut())
  2682. argsQTs[i - 1] = m_context->getLValueReferenceType(argsQTs[i - 1]);
  2683. argNames[i - 1] = StringRef(intrinsic->pArgs[i].pName);
  2684. }
  2685. // Create the declaration.
  2686. IdentifierInfo* ii = &m_context->Idents.get(StringRef(intrinsic->pArgs[0].pName));
  2687. DeclarationName declarationName = DeclarationName(ii);
  2688. CXXMethodDecl* functionDecl = CreateObjectFunctionDeclarationWithParams(*m_context, recordDecl,
  2689. functionResultQT, ArrayRef<QualType>(argsQTs, numParams), ArrayRef<StringRef>(argNames, numParams),
  2690. declarationName, true);
  2691. functionDecl->setImplicit(true);
  2692. // If the function is a template function, create the declaration and cross-reference.
  2693. if (templateParamNamedDeclsCount > 0)
  2694. {
  2695. hlsl::CreateFunctionTemplateDecl(
  2696. *m_context, recordDecl, functionDecl, templateParamNamedDecls, templateParamNamedDeclsCount);
  2697. }
  2698. }
  2699. // Checks whether the two specified intrinsics generate equivalent templates.
  2700. // For example: foo (any_int) and foo (any_float) are only unambiguous in the context
  2701. // of HLSL intrinsic rules, and their difference can't be expressed with C++ templates.
  2702. bool AreIntrinsicTemplatesEquivalent(const HLSL_INTRINSIC* left, const HLSL_INTRINSIC* right)
  2703. {
  2704. if (left == right)
  2705. {
  2706. return true;
  2707. }
  2708. if (left == nullptr || right == nullptr)
  2709. {
  2710. return false;
  2711. }
  2712. return (left->uNumArgs == right->uNumArgs &&
  2713. 0 == strcmp(left->pArgs[0].pName, right->pArgs[0].pName));
  2714. }
  2715. // Adds all the intrinsic methods that correspond to the specified type.
  2716. void AddObjectMethods(ArBasicKind kind, _In_ CXXRecordDecl* recordDecl, int templateDepth)
  2717. {
  2718. DXASSERT_NOMSG(recordDecl != nullptr);
  2719. DXASSERT_NOMSG(templateDepth >= 0);
  2720. const HLSL_INTRINSIC* intrinsics;
  2721. const HLSL_INTRINSIC* prior = nullptr;
  2722. size_t intrinsicCount;
  2723. GetIntrinsicMethods(kind, &intrinsics, &intrinsicCount);
  2724. DXASSERT(
  2725. (intrinsics == nullptr) == (intrinsicCount == 0),
  2726. "intrinsic table pointer must match count (null for zero, something valid otherwise");
  2727. while (intrinsicCount--)
  2728. {
  2729. if (!AreIntrinsicTemplatesEquivalent(intrinsics, prior))
  2730. {
  2731. AddObjectIntrinsicTemplate(recordDecl, templateDepth, intrinsics);
  2732. prior = intrinsics;
  2733. }
  2734. intrinsics++;
  2735. }
  2736. }
  2737. void AddDoubleSubscriptSupport(
  2738. _In_ ClassTemplateDecl* typeDecl,
  2739. _In_ CXXRecordDecl* recordDecl,
  2740. _In_z_ const char* memberName, QualType elementType, TemplateTypeParmDecl* templateTypeParmDecl,
  2741. _In_z_ const char* type0Name,
  2742. _In_z_ const char* type1Name,
  2743. _In_z_ const char* indexer0Name, QualType indexer0Type,
  2744. _In_z_ const char* indexer1Name, QualType indexer1Type)
  2745. {
  2746. DXASSERT_NOMSG(typeDecl != nullptr);
  2747. DXASSERT_NOMSG(recordDecl != nullptr);
  2748. DXASSERT_NOMSG(memberName != nullptr);
  2749. DXASSERT_NOMSG(!elementType.isNull());
  2750. DXASSERT_NOMSG(templateTypeParmDecl != nullptr);
  2751. DXASSERT_NOMSG(type0Name != nullptr);
  2752. DXASSERT_NOMSG(type1Name != nullptr);
  2753. DXASSERT_NOMSG(indexer0Name != nullptr);
  2754. DXASSERT_NOMSG(!indexer0Type.isNull());
  2755. DXASSERT_NOMSG(indexer1Name != nullptr);
  2756. DXASSERT_NOMSG(!indexer1Type.isNull());
  2757. //
  2758. // Add inner types to the templates to represent the following C++ code inside the class.
  2759. // public:
  2760. // class sample_slice_type
  2761. // {
  2762. // public: TElement operator[](uint3 index);
  2763. // };
  2764. // class sample_type
  2765. // {
  2766. // public: sample_slice_type operator[](uint slice);
  2767. // };
  2768. // sample_type sample;
  2769. //
  2770. // Variable names reflect this structure, but this code will also produce the types
  2771. // for .mips access.
  2772. //
  2773. const bool MutableTrue = true;
  2774. DeclarationName subscriptName = m_context->DeclarationNames.getCXXOperatorName(OO_Subscript);
  2775. CXXRecordDecl* sampleSliceTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2776. &m_context->Idents.get(StringRef(type1Name)));
  2777. sampleSliceTypeDecl->setAccess(AS_public);
  2778. sampleSliceTypeDecl->setImplicit();
  2779. recordDecl->addDecl(sampleSliceTypeDecl);
  2780. sampleSliceTypeDecl->startDefinition();
  2781. const bool MutableFalse = false;
  2782. FieldDecl* sliceHandleDecl = FieldDecl::Create(*m_context, sampleSliceTypeDecl, NoLoc, NoLoc,
  2783. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2784. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2785. sliceHandleDecl->setAccess(AS_private);
  2786. sampleSliceTypeDecl->addDecl(sliceHandleDecl);
  2787. CXXMethodDecl* sampleSliceSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2788. sampleSliceTypeDecl, elementType,
  2789. ArrayRef<QualType>(indexer1Type), ArrayRef<StringRef>(StringRef(indexer1Name)), subscriptName, true);
  2790. hlsl::CreateFunctionTemplateDecl(*m_context, sampleSliceTypeDecl, sampleSliceSubscriptDecl,
  2791. reinterpret_cast<NamedDecl**>(&templateTypeParmDecl), 1);
  2792. sampleSliceTypeDecl->completeDefinition();
  2793. CXXRecordDecl* sampleTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2794. &m_context->Idents.get(StringRef(type0Name)));
  2795. sampleTypeDecl->setAccess(AS_public);
  2796. recordDecl->addDecl(sampleTypeDecl);
  2797. sampleTypeDecl->startDefinition();
  2798. sampleTypeDecl->setImplicit();
  2799. FieldDecl* sampleHandleDecl = FieldDecl::Create(*m_context, sampleTypeDecl, NoLoc, NoLoc,
  2800. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2801. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2802. sampleHandleDecl->setAccess(AS_private);
  2803. sampleTypeDecl->addDecl(sampleHandleDecl);
  2804. QualType sampleSliceType = m_context->getRecordType(sampleSliceTypeDecl);
  2805. CXXMethodDecl* sampleSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2806. sampleTypeDecl, m_context->getLValueReferenceType(sampleSliceType),
  2807. ArrayRef<QualType>(indexer0Type), ArrayRef<StringRef>(StringRef(indexer0Name)), subscriptName, true);
  2808. sampleTypeDecl->completeDefinition();
  2809. // Add subscript attribute
  2810. AddHLSLSubscriptAttr(sampleSubscriptDecl, *m_context, HLSubscriptOpcode::DoubleSubscript);
  2811. QualType sampleTypeQT = m_context->getRecordType(sampleTypeDecl);
  2812. FieldDecl* sampleFieldDecl = FieldDecl::Create(*m_context, recordDecl, NoLoc, NoLoc,
  2813. &m_context->Idents.get(StringRef(memberName)), sampleTypeQT,
  2814. m_context->CreateTypeSourceInfo(sampleTypeQT), nullptr, MutableTrue, ICIS_NoInit);
  2815. sampleFieldDecl->setAccess(AS_public);
  2816. recordDecl->addDecl(sampleFieldDecl);
  2817. }
  2818. void AddObjectSubscripts(ArBasicKind kind, _In_ ClassTemplateDecl *typeDecl,
  2819. _In_ CXXRecordDecl *recordDecl,
  2820. SubscriptOperatorRecord op) {
  2821. DXASSERT_NOMSG(typeDecl != nullptr);
  2822. DXASSERT_NOMSG(recordDecl != nullptr);
  2823. DXASSERT_NOMSG(0 <= op.SubscriptCardinality &&
  2824. op.SubscriptCardinality <= 3);
  2825. DXASSERT(op.SubscriptCardinality > 0 ||
  2826. (op.HasMips == false && op.HasSample == false),
  2827. "objects that have .mips or .sample member also have a plain "
  2828. "subscript defined (otherwise static table is "
  2829. "likely incorrect, and this function won't know the cardinality "
  2830. "of the position parameter");
  2831. bool isReadWrite = GetBasicKindProps(kind) & BPROP_RWBUFFER;
  2832. DXASSERT(!isReadWrite || (op.HasMips == false && op.HasSample == false),
  2833. "read/write objects don't have .mips or .sample members");
  2834. // Return early if there is no work to be done.
  2835. if (op.SubscriptCardinality == 0) {
  2836. return;
  2837. }
  2838. const unsigned int templateDepth = 1;
  2839. // Add an operator[].
  2840. TemplateTypeParmDecl *templateTypeParmDecl = cast<TemplateTypeParmDecl>(
  2841. typeDecl->getTemplateParameters()->getParam(0));
  2842. QualType resultType = m_context->getTemplateTypeParmType(
  2843. templateDepth, 0, ParameterPackFalse, templateTypeParmDecl);
  2844. if (!isReadWrite) resultType = m_context->getConstType(resultType);
  2845. resultType = m_context->getLValueReferenceType(resultType);
  2846. QualType indexType =
  2847. op.SubscriptCardinality == 1
  2848. ? m_context->UnsignedIntTy
  2849. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  2850. op.SubscriptCardinality);
  2851. CXXMethodDecl *functionDecl = CreateObjectFunctionDeclarationWithParams(
  2852. *m_context, recordDecl, resultType, ArrayRef<QualType>(indexType),
  2853. ArrayRef<StringRef>(StringRef("index")),
  2854. m_context->DeclarationNames.getCXXOperatorName(OO_Subscript), true);
  2855. hlsl::CreateFunctionTemplateDecl(
  2856. *m_context, recordDecl, functionDecl,
  2857. reinterpret_cast<NamedDecl **>(&templateTypeParmDecl), 1);
  2858. // Add a .mips member if necessary.
  2859. QualType uintType = m_context->UnsignedIntTy;
  2860. if (op.HasMips) {
  2861. AddDoubleSubscriptSupport(typeDecl, recordDecl, "mips", resultType,
  2862. templateTypeParmDecl, "mips_type",
  2863. "mips_slice_type", "mipSlice", uintType, "pos",
  2864. indexType);
  2865. }
  2866. // Add a .sample member if necessary.
  2867. if (op.HasSample) {
  2868. AddDoubleSubscriptSupport(typeDecl, recordDecl, "sample", resultType,
  2869. templateTypeParmDecl, "sample_type",
  2870. "sample_slice_type", "sampleSlice", uintType,
  2871. "pos", indexType);
  2872. // TODO: support operator[][](indexType, uint).
  2873. }
  2874. }
  2875. static bool ObjectTypeDeclMapTypeCmp(const std::pair<CXXRecordDecl*,unsigned> &a,
  2876. const std::pair<CXXRecordDecl*,unsigned> &b) {
  2877. return a.first < b.first;
  2878. };
  2879. int FindObjectBasicKindIndex(const CXXRecordDecl* recordDecl) {
  2880. auto begin = m_objectTypeDeclsMap.begin();
  2881. auto end = m_objectTypeDeclsMap.end();
  2882. auto val = std::make_pair(const_cast<CXXRecordDecl*>(recordDecl), 0);
  2883. auto low = std::lower_bound(begin, end, val, ObjectTypeDeclMapTypeCmp);
  2884. if (low == end)
  2885. return -1;
  2886. if (recordDecl == low->first)
  2887. return low->second;
  2888. else
  2889. return -1;
  2890. }
  2891. // Adds all built-in HLSL object types.
  2892. void AddObjectTypes()
  2893. {
  2894. DXASSERT(m_context != nullptr, "otherwise caller hasn't initialized context yet");
  2895. QualType float4Type = LookupVectorType(HLSLScalarType_float, 4);
  2896. TypeSourceInfo *float4TypeSourceInfo = m_context->getTrivialTypeSourceInfo(float4Type, NoLoc);
  2897. m_objectTypeLazyInitMask = 0;
  2898. unsigned effectKindIndex = 0;
  2899. for (unsigned i = 0; i < _countof(g_ArBasicKindsAsTypes); i++)
  2900. {
  2901. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  2902. if (kind == AR_OBJECT_WAVE) { // wave objects are currently unused
  2903. continue;
  2904. }
  2905. if (kind == AR_OBJECT_LEGACY_EFFECT)
  2906. effectKindIndex = i;
  2907. DXASSERT(kind < _countof(g_ArBasicTypeNames), "g_ArBasicTypeNames has the wrong number of entries");
  2908. _Analysis_assume_(kind < _countof(g_ArBasicTypeNames));
  2909. const char* typeName = g_ArBasicTypeNames[kind];
  2910. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  2911. CXXRecordDecl* recordDecl = nullptr;
  2912. if (kind == AR_OBJECT_RAY_DESC) {
  2913. QualType float3Ty = LookupVectorType(HLSLScalarType::HLSLScalarType_float, 3);
  2914. recordDecl = CreateRayDescStruct(*m_context, float3Ty);
  2915. } else if (kind == AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES) {
  2916. QualType float2Type = LookupVectorType(HLSLScalarType::HLSLScalarType_float, 2);
  2917. recordDecl = AddBuiltInTriangleIntersectionAttributes(*m_context, float2Type);
  2918. } else if (IsSubobjectBasicKind(kind)) {
  2919. switch (kind) {
  2920. case AR_OBJECT_STATE_OBJECT_CONFIG:
  2921. recordDecl = CreateSubobjectStateObjectConfig(*m_context);
  2922. break;
  2923. case AR_OBJECT_GLOBAL_ROOT_SIGNATURE:
  2924. recordDecl = CreateSubobjectRootSignature(*m_context, true);
  2925. break;
  2926. case AR_OBJECT_LOCAL_ROOT_SIGNATURE:
  2927. recordDecl = CreateSubobjectRootSignature(*m_context, false);
  2928. break;
  2929. case AR_OBJECT_SUBOBJECT_TO_EXPORTS_ASSOC:
  2930. recordDecl = CreateSubobjectSubobjectToExportsAssoc(*m_context);
  2931. break;
  2932. case AR_OBJECT_RAYTRACING_SHADER_CONFIG:
  2933. recordDecl = CreateSubobjectRaytracingShaderConfig(*m_context);
  2934. break;
  2935. case AR_OBJECT_RAYTRACING_PIPELINE_CONFIG:
  2936. recordDecl = CreateSubobjectRaytracingPipelineConfig(*m_context);
  2937. break;
  2938. case AR_OBJECT_TRIANGLE_HIT_GROUP:
  2939. recordDecl = CreateSubobjectTriangleHitGroup(*m_context);
  2940. break;
  2941. case AR_OBJECT_PROCEDURAL_PRIMITIVE_HIT_GROUP:
  2942. recordDecl = CreateSubobjectProceduralPrimitiveHitGroup(*m_context);
  2943. break;
  2944. case AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1:
  2945. recordDecl = CreateSubobjectRaytracingPipelineConfig1(*m_context);
  2946. break;
  2947. }
  2948. } else if (kind == AR_OBJECT_RAY_QUERY) {
  2949. recordDecl = DeclareRayQueryType(*m_context);
  2950. } else if (kind == AR_OBJECT_RESOURCE) {
  2951. recordDecl = DeclareResourceType(*m_context);
  2952. }
  2953. else if (kind == AR_OBJECT_FEEDBACKTEXTURE2D) {
  2954. recordDecl = DeclareUIntTemplatedTypeWithHandle(*m_context, "FeedbackTexture2D", "kind");
  2955. }
  2956. else if (kind == AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY) {
  2957. recordDecl = DeclareUIntTemplatedTypeWithHandle(*m_context, "FeedbackTexture2DArray", "kind");
  2958. }
  2959. else if (templateArgCount == 0) {
  2960. recordDecl = DeclareRecordTypeWithHandle(*m_context, typeName);
  2961. }
  2962. else
  2963. {
  2964. DXASSERT(templateArgCount == 1 || templateArgCount == 2, "otherwise a new case has been added");
  2965. TypeSourceInfo* typeDefault = TemplateHasDefaultType(kind) ? float4TypeSourceInfo : nullptr;
  2966. recordDecl = DeclareTemplateTypeWithHandle(*m_context, typeName, templateArgCount, typeDefault);
  2967. }
  2968. m_objectTypeDecls[i] = recordDecl;
  2969. m_objectTypeDeclsMap[i] = std::make_pair(recordDecl, i);
  2970. m_objectTypeLazyInitMask |= ((uint64_t)1)<<i;
  2971. }
  2972. // Create an alias for SamplerState. 'sampler' is very commonly used.
  2973. {
  2974. DeclContext* currentDeclContext = m_context->getTranslationUnitDecl();
  2975. IdentifierInfo& samplerId = m_context->Idents.get(StringRef("sampler"), tok::TokenKind::identifier);
  2976. TypeSourceInfo* samplerTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_SAMPLER));
  2977. TypedefDecl* samplerDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &samplerId, samplerTypeSource);
  2978. currentDeclContext->addDecl(samplerDecl);
  2979. samplerDecl->setImplicit(true);
  2980. // Create decls for each deprecated effect object type:
  2981. unsigned effectObjBase = _countof(g_ArBasicKindsAsTypes);
  2982. // TypeSourceInfo* effectObjTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_LEGACY_EFFECT));
  2983. for (unsigned i = 0; i < _countof(g_DeprecatedEffectObjectNames); i++) {
  2984. IdentifierInfo& idInfo = m_context->Idents.get(StringRef(g_DeprecatedEffectObjectNames[i]), tok::TokenKind::identifier);
  2985. //TypedefDecl* effectObjDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &idInfo, effectObjTypeSource);
  2986. CXXRecordDecl *effectObjDecl = CXXRecordDecl::Create(*m_context, TagTypeKind::TTK_Struct, currentDeclContext, NoLoc, NoLoc, &idInfo);
  2987. currentDeclContext->addDecl(effectObjDecl);
  2988. effectObjDecl->setImplicit(true);
  2989. m_objectTypeDeclsMap[i+effectObjBase] = std::make_pair(effectObjDecl, effectKindIndex);
  2990. }
  2991. }
  2992. // Make sure it's in order.
  2993. std::sort(m_objectTypeDeclsMap.begin(), m_objectTypeDeclsMap.end(), ObjectTypeDeclMapTypeCmp);
  2994. }
  2995. FunctionDecl* AddSubscriptSpecialization(
  2996. _In_ FunctionTemplateDecl* functionTemplate,
  2997. QualType objectElement,
  2998. const FindStructBasicTypeResult& findResult);
  2999. ImplicitCastExpr* CreateLValueToRValueCast(Expr* input) {
  3000. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  3001. }
  3002. ImplicitCastExpr* CreateFlatConversionCast(Expr* input) {
  3003. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  3004. }
  3005. static TYPE_CONVERSION_REMARKS RemarksUnused;
  3006. static ImplicitConversionKind ImplicitConversionKindUnused;
  3007. HRESULT CombineDimensions(QualType leftType, QualType rightType, QualType *resultType,
  3008. ImplicitConversionKind &convKind = ImplicitConversionKindUnused,
  3009. TYPE_CONVERSION_REMARKS &Remarks = RemarksUnused);
  3010. clang::TypedefDecl *LookupMatrixShorthandType(HLSLScalarType scalarType, UINT rowCount, UINT colCount) {
  3011. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  3012. rowCount <= 4 && colCount <= 4);
  3013. TypedefDecl *qts =
  3014. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1];
  3015. if (qts == nullptr) {
  3016. QualType type = LookupMatrixType(scalarType, rowCount, colCount);
  3017. qts = CreateMatrixSpecializationShorthand(*m_context, type, scalarType,
  3018. rowCount, colCount);
  3019. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1] = qts;
  3020. }
  3021. return qts;
  3022. }
  3023. clang::TypedefDecl *LookupVectorShorthandType(HLSLScalarType scalarType, UINT colCount) {
  3024. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  3025. colCount <= 4);
  3026. TypedefDecl *qts = m_vectorTypedefs[scalarType][colCount - 1];
  3027. if (qts == nullptr) {
  3028. QualType type = LookupVectorType(scalarType, colCount);
  3029. qts = CreateVectorSpecializationShorthand(*m_context, type, scalarType,
  3030. colCount);
  3031. m_vectorTypedefs[scalarType][colCount - 1] = qts;
  3032. }
  3033. return qts;
  3034. }
  3035. public:
  3036. HLSLExternalSource() :
  3037. m_matrixTemplateDecl(nullptr),
  3038. m_vectorTemplateDecl(nullptr),
  3039. m_context(nullptr),
  3040. m_sema(nullptr),
  3041. m_hlslStringTypedef(nullptr)
  3042. {
  3043. memset(m_matrixTypes, 0, sizeof(m_matrixTypes));
  3044. memset(m_matrixShorthandTypes, 0, sizeof(m_matrixShorthandTypes));
  3045. memset(m_vectorTypes, 0, sizeof(m_vectorTypes));
  3046. memset(m_vectorTypedefs, 0, sizeof(m_vectorTypedefs));
  3047. memset(m_scalarTypes, 0, sizeof(m_scalarTypes));
  3048. memset(m_scalarTypeDefs, 0, sizeof(m_scalarTypeDefs));
  3049. memset(m_baseTypes, 0, sizeof(m_baseTypes));
  3050. }
  3051. ~HLSLExternalSource() { }
  3052. static HLSLExternalSource* FromSema(_In_ Sema* self)
  3053. {
  3054. DXASSERT_NOMSG(self != nullptr);
  3055. ExternalSemaSource* externalSource = self->getExternalSource();
  3056. DXASSERT(externalSource != nullptr, "otherwise caller shouldn't call HLSL-specific function");
  3057. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  3058. return hlsl;
  3059. }
  3060. void InitializeSema(Sema& S) override
  3061. {
  3062. m_sema = &S;
  3063. S.addExternalSource(this);
  3064. AddObjectTypes();
  3065. AddStdIsEqualImplementation(S.getASTContext(), S);
  3066. for (auto && intrinsic : m_intrinsicTables) {
  3067. AddIntrinsicTableMethods(intrinsic);
  3068. }
  3069. }
  3070. void ForgetSema() override
  3071. {
  3072. m_sema = nullptr;
  3073. }
  3074. Sema* getSema() {
  3075. return m_sema;
  3076. }
  3077. TypedefDecl* LookupScalarTypeDef(HLSLScalarType scalarType) {
  3078. // We shouldn't create Typedef for built in scalar types.
  3079. // For built in scalar types, this funciton may be called for
  3080. // TypoCorrection. In that case, we return a nullptr.
  3081. if (m_scalarTypes[scalarType].isNull()) {
  3082. m_scalarTypeDefs[scalarType] = CreateGlobalTypedef(m_context, HLSLScalarTypeNames[scalarType], m_baseTypes[scalarType]);
  3083. m_scalarTypes[scalarType] = m_context->getTypeDeclType(m_scalarTypeDefs[scalarType]);
  3084. }
  3085. return m_scalarTypeDefs[scalarType];
  3086. }
  3087. QualType LookupMatrixType(HLSLScalarType scalarType, unsigned int rowCount, unsigned int colCount)
  3088. {
  3089. QualType qt = m_matrixTypes[scalarType][rowCount - 1][colCount - 1];
  3090. if (qt.isNull()) {
  3091. // lazy initialization of scalar types
  3092. if (m_scalarTypes[scalarType].isNull()) {
  3093. LookupScalarTypeDef(scalarType);
  3094. }
  3095. qt = GetOrCreateMatrixSpecialization(*m_context, m_sema, m_matrixTemplateDecl, m_scalarTypes[scalarType], rowCount, colCount);
  3096. m_matrixTypes[scalarType][rowCount - 1][colCount - 1] = qt;
  3097. }
  3098. return qt;
  3099. }
  3100. QualType LookupVectorType(HLSLScalarType scalarType, unsigned int colCount)
  3101. {
  3102. QualType qt = m_vectorTypes[scalarType][colCount - 1];
  3103. if (qt.isNull()) {
  3104. if (m_scalarTypes[scalarType].isNull()) {
  3105. LookupScalarTypeDef(scalarType);
  3106. }
  3107. qt = GetOrCreateVectorSpecialization(*m_context, m_sema, m_vectorTemplateDecl, m_scalarTypes[scalarType], colCount);
  3108. m_vectorTypes[scalarType][colCount - 1] = qt;
  3109. }
  3110. return qt;
  3111. }
  3112. TypedefDecl* GetStringTypedef() {
  3113. if (m_hlslStringTypedef == nullptr) {
  3114. m_hlslStringTypedef = CreateGlobalTypedef(m_context, "string", m_hlslStringType);
  3115. m_hlslStringType = m_context->getTypeDeclType(m_hlslStringTypedef);
  3116. }
  3117. DXASSERT_NOMSG(m_hlslStringTypedef != nullptr);
  3118. return m_hlslStringTypedef;
  3119. }
  3120. static bool IsSubobjectBasicKind(ArBasicKind kind) {
  3121. return kind >= AR_OBJECT_STATE_OBJECT_CONFIG && kind <= AR_OBJECT_RAYTRACING_PIPELINE_CONFIG1;
  3122. }
  3123. bool IsSubobjectType(QualType type) {
  3124. return IsSubobjectBasicKind(GetTypeElementKind(type));
  3125. }
  3126. bool IsRayQueryBasicKind(ArBasicKind kind) {
  3127. return kind == AR_OBJECT_RAY_QUERY;
  3128. }
  3129. bool IsRayQueryType(QualType type) {
  3130. return IsRayQueryBasicKind(GetTypeElementKind(type));
  3131. }
  3132. void WarnMinPrecision(HLSLScalarType type, SourceLocation loc) {
  3133. // TODO: enalbe this once we introduce precise master option
  3134. bool UseMinPrecision = m_context->getLangOpts().UseMinPrecision;
  3135. if (type == HLSLScalarType_int_min12) {
  3136. const char *PromotedType =
  3137. UseMinPrecision ? HLSLScalarTypeNames[HLSLScalarType_int_min16]
  3138. : HLSLScalarTypeNames[HLSLScalarType_int16];
  3139. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3140. << HLSLScalarTypeNames[type] << PromotedType;
  3141. } else if (type == HLSLScalarType_float_min10) {
  3142. const char *PromotedType =
  3143. UseMinPrecision ? HLSLScalarTypeNames[HLSLScalarType_float_min16]
  3144. : HLSLScalarTypeNames[HLSLScalarType_float16];
  3145. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3146. << HLSLScalarTypeNames[type] << PromotedType;
  3147. }
  3148. if (!UseMinPrecision) {
  3149. if (type == HLSLScalarType_float_min16) {
  3150. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3151. << HLSLScalarTypeNames[type]
  3152. << HLSLScalarTypeNames[HLSLScalarType_float16];
  3153. } else if (type == HLSLScalarType_int_min16) {
  3154. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3155. << HLSLScalarTypeNames[type]
  3156. << HLSLScalarTypeNames[HLSLScalarType_int16];
  3157. } else if (type == HLSLScalarType_uint_min16) {
  3158. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  3159. << HLSLScalarTypeNames[type]
  3160. << HLSLScalarTypeNames[HLSLScalarType_uint16];
  3161. }
  3162. }
  3163. }
  3164. bool DiagnoseHLSLScalarType(HLSLScalarType type, SourceLocation Loc) {
  3165. if (getSema()->getLangOpts().HLSLVersion < 2018) {
  3166. switch (type) {
  3167. case HLSLScalarType_float16:
  3168. case HLSLScalarType_float32:
  3169. case HLSLScalarType_float64:
  3170. case HLSLScalarType_int16:
  3171. case HLSLScalarType_int32:
  3172. case HLSLScalarType_uint16:
  3173. case HLSLScalarType_uint32:
  3174. m_sema->Diag(Loc, diag::err_hlsl_unsupported_keyword_for_version)
  3175. << HLSLScalarTypeNames[type] << "2018";
  3176. return false;
  3177. default:
  3178. break;
  3179. }
  3180. }
  3181. if (getSema()->getLangOpts().UseMinPrecision) {
  3182. switch (type) {
  3183. case HLSLScalarType_float16:
  3184. case HLSLScalarType_int16:
  3185. case HLSLScalarType_uint16:
  3186. m_sema->Diag(Loc, diag::err_hlsl_unsupported_keyword_for_min_precision)
  3187. << HLSLScalarTypeNames[type];
  3188. return false;
  3189. default:
  3190. break;
  3191. }
  3192. }
  3193. return true;
  3194. }
  3195. bool LookupUnqualified(LookupResult &R, Scope *S) override
  3196. {
  3197. const DeclarationNameInfo declName = R.getLookupNameInfo();
  3198. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  3199. if (idInfo == nullptr) {
  3200. return false;
  3201. }
  3202. // Currently template instantiation is blocked when a fatal error is
  3203. // detected. So no faulting-in types at this point, instead we simply
  3204. // back out.
  3205. if (this->m_sema->Diags.hasFatalErrorOccurred()) {
  3206. return false;
  3207. }
  3208. StringRef nameIdentifier = idInfo->getName();
  3209. HLSLScalarType parsedType;
  3210. int rowCount;
  3211. int colCount;
  3212. // Try parsing hlsl scalar types that is not initialized at AST time.
  3213. if (TryParseAny(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &rowCount, &colCount, getSema()->getLangOpts())) {
  3214. assert(parsedType != HLSLScalarType_unknown && "otherwise, TryParseHLSLScalarType should not have succeeded.");
  3215. if (rowCount == 0 && colCount == 0) { // scalar
  3216. TypedefDecl *typeDecl = LookupScalarTypeDef(parsedType);
  3217. if (!typeDecl) return false;
  3218. R.addDecl(typeDecl);
  3219. }
  3220. else if (rowCount == 0) { // vector
  3221. TypedefDecl *qts = LookupVectorShorthandType(parsedType, colCount);
  3222. R.addDecl(qts);
  3223. }
  3224. else { // matrix
  3225. TypedefDecl* qts = LookupMatrixShorthandType(parsedType, rowCount, colCount);
  3226. R.addDecl(qts);
  3227. }
  3228. return true;
  3229. }
  3230. // string
  3231. else if (TryParseString(nameIdentifier.data(), nameIdentifier.size(), getSema()->getLangOpts())) {
  3232. TypedefDecl *strDecl = GetStringTypedef();
  3233. R.addDecl(strDecl);
  3234. }
  3235. return false;
  3236. }
  3237. /// <summary>
  3238. /// Determines whether the specify record type is a matrix, another HLSL object, or a user-defined structure.
  3239. /// </sumary>
  3240. ArTypeObjectKind ClassifyRecordType(const RecordType* type)
  3241. {
  3242. DXASSERT_NOMSG(type != nullptr);
  3243. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  3244. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  3245. if (templateSpecializationDecl) {
  3246. ClassTemplateDecl *decl = templateSpecializationDecl->getSpecializedTemplate();
  3247. if (decl == m_matrixTemplateDecl)
  3248. return AR_TOBJ_MATRIX;
  3249. else if (decl == m_vectorTemplateDecl)
  3250. return AR_TOBJ_VECTOR;
  3251. else if (!decl->isImplicit())
  3252. return AR_TOBJ_COMPOUND;
  3253. return AR_TOBJ_OBJECT;
  3254. }
  3255. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  3256. if (typeRecordDecl->getDeclContext()->isFileContext()) {
  3257. int index = FindObjectBasicKindIndex(typeRecordDecl);
  3258. if (index != -1) {
  3259. ArBasicKind kind = g_ArBasicKindsAsTypes[index];
  3260. if ( AR_OBJECT_RAY_DESC == kind || AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES == kind)
  3261. return AR_TOBJ_COMPOUND;
  3262. }
  3263. return AR_TOBJ_OBJECT;
  3264. }
  3265. else
  3266. return AR_TOBJ_INNER_OBJ;
  3267. }
  3268. return AR_TOBJ_COMPOUND;
  3269. }
  3270. /// <summary>Given a Clang type, determines whether it is a built-in object type (sampler, texture, etc).</summary>
  3271. bool IsBuiltInObjectType(QualType type)
  3272. {
  3273. type = GetStructuralForm(type);
  3274. if (!type.isNull() && type->isStructureOrClassType()) {
  3275. const RecordType* recordType = type->getAs<RecordType>();
  3276. return ClassifyRecordType(recordType) == AR_TOBJ_OBJECT;
  3277. }
  3278. return false;
  3279. }
  3280. /// <summary>
  3281. /// Given the specified type (typed a DeclContext for convenience), determines its RecordDecl,
  3282. /// possibly refering to original template record if it's a specialization; this makes the result
  3283. /// suitable for looking up in initialization tables.
  3284. /// </summary>
  3285. const CXXRecordDecl* GetRecordDeclForBuiltInOrStruct(const DeclContext* context)
  3286. {
  3287. const CXXRecordDecl* recordDecl;
  3288. if (const ClassTemplateSpecializationDecl* decl = dyn_cast<ClassTemplateSpecializationDecl>(context))
  3289. {
  3290. recordDecl = decl->getSpecializedTemplate()->getTemplatedDecl();
  3291. }
  3292. else
  3293. {
  3294. recordDecl = dyn_cast<CXXRecordDecl>(context);
  3295. }
  3296. return recordDecl;
  3297. }
  3298. /// <summary>Given a Clang type, return the ArTypeObjectKind classification, (eg AR_TOBJ_VECTOR).</summary>
  3299. ArTypeObjectKind GetTypeObjectKind(QualType type)
  3300. {
  3301. DXASSERT_NOMSG(!type.isNull());
  3302. type = GetStructuralForm(type);
  3303. if (type->isVoidType()) return AR_TOBJ_VOID;
  3304. if (type->isArrayType()) {
  3305. return hlsl::IsArrayConstantStringType(type) ? AR_TOBJ_STRING : AR_TOBJ_ARRAY;
  3306. }
  3307. if (type->isPointerType()) {
  3308. return hlsl::IsPointerStringType(type) ? AR_TOBJ_STRING : AR_TOBJ_POINTER;
  3309. }
  3310. if (type->isDependentType()) {
  3311. return AR_TOBJ_DEPENDENT;
  3312. }
  3313. if (type->isStructureOrClassType()) {
  3314. const RecordType* recordType = type->getAs<RecordType>();
  3315. return ClassifyRecordType(recordType);
  3316. } else if (const InjectedClassNameType *ClassNameTy =
  3317. type->getAs<InjectedClassNameType>()) {
  3318. const CXXRecordDecl *typeRecordDecl = ClassNameTy->getDecl();
  3319. const ClassTemplateSpecializationDecl *templateSpecializationDecl =
  3320. dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  3321. if (templateSpecializationDecl) {
  3322. ClassTemplateDecl *decl =
  3323. templateSpecializationDecl->getSpecializedTemplate();
  3324. if (decl == m_matrixTemplateDecl)
  3325. return AR_TOBJ_MATRIX;
  3326. else if (decl == m_vectorTemplateDecl)
  3327. return AR_TOBJ_VECTOR;
  3328. DXASSERT(decl->isImplicit(),
  3329. "otherwise object template decl is not set to implicit");
  3330. return AR_TOBJ_OBJECT;
  3331. }
  3332. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  3333. if (typeRecordDecl->getDeclContext()->isFileContext())
  3334. return AR_TOBJ_OBJECT;
  3335. else
  3336. return AR_TOBJ_INNER_OBJ;
  3337. }
  3338. return AR_TOBJ_COMPOUND;
  3339. }
  3340. if (type->isBuiltinType()) return AR_TOBJ_BASIC;
  3341. if (type->isEnumeralType()) return AR_TOBJ_BASIC;
  3342. return AR_TOBJ_INVALID;
  3343. }
  3344. /// <summary>Gets the element type of a matrix or vector type (eg, the 'float' in 'float4x4' or 'float4').</summary>
  3345. QualType GetMatrixOrVectorElementType(QualType type)
  3346. {
  3347. type = GetStructuralForm(type);
  3348. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  3349. DXASSERT_NOMSG(typeRecordDecl);
  3350. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  3351. DXASSERT_NOMSG(templateSpecializationDecl);
  3352. DXASSERT_NOMSG(templateSpecializationDecl->getSpecializedTemplate() == m_matrixTemplateDecl ||
  3353. templateSpecializationDecl->getSpecializedTemplate() == m_vectorTemplateDecl);
  3354. return templateSpecializationDecl->getTemplateArgs().get(0).getAsType();
  3355. }
  3356. /// <summary>Gets the type with structural information (elements and shape) for the given type.</summary>
  3357. /// <remarks>This function will strip lvalue/rvalue references, attributes and qualifiers.</remarks>
  3358. QualType GetStructuralForm(QualType type)
  3359. {
  3360. if (type.isNull()) {
  3361. return type;
  3362. }
  3363. const ReferenceType *RefType = nullptr;
  3364. const AttributedType *AttrType = nullptr;
  3365. while ( (RefType = dyn_cast<ReferenceType>(type)) ||
  3366. (AttrType = dyn_cast<AttributedType>(type)))
  3367. {
  3368. type = RefType ? RefType->getPointeeType() : AttrType->getEquivalentType();
  3369. }
  3370. // Despite its name, getCanonicalTypeUnqualified will preserve const for array elements or something
  3371. return QualType(type->getCanonicalTypeUnqualified()->getTypePtr(), 0);
  3372. }
  3373. /// <summary>Given a Clang type, return the ArBasicKind classification for its contents.</summary>
  3374. ArBasicKind GetTypeElementKind(QualType type)
  3375. {
  3376. type = GetStructuralForm(type);
  3377. ArTypeObjectKind kind = GetTypeObjectKind(type);
  3378. if (kind == AR_TOBJ_MATRIX || kind == AR_TOBJ_VECTOR) {
  3379. QualType elementType = GetMatrixOrVectorElementType(type);
  3380. return GetTypeElementKind(elementType);
  3381. }
  3382. if (kind == AR_TOBJ_STRING) {
  3383. return type->isArrayType() ? AR_OBJECT_STRING_LITERAL : AR_OBJECT_STRING;
  3384. }
  3385. if (type->isArrayType()) {
  3386. const ArrayType* arrayType = type->getAsArrayTypeUnsafe();
  3387. return GetTypeElementKind(arrayType->getElementType());
  3388. }
  3389. if (kind == AR_TOBJ_INNER_OBJ) {
  3390. return AR_OBJECT_INNER;
  3391. } else if (kind == AR_TOBJ_OBJECT) {
  3392. // Classify the object as the element type.
  3393. const CXXRecordDecl* typeRecordDecl = GetRecordDeclForBuiltInOrStruct(type->getAsCXXRecordDecl());
  3394. int index = FindObjectBasicKindIndex(typeRecordDecl);
  3395. // NOTE: this will likely need to be updated for specialized records
  3396. DXASSERT(index != -1, "otherwise can't find type we already determined was an object");
  3397. return g_ArBasicKindsAsTypes[index];
  3398. }
  3399. CanQualType canType = type->getCanonicalTypeUnqualified();
  3400. return BasicTypeForScalarType(canType);
  3401. }
  3402. ArBasicKind BasicTypeForScalarType(CanQualType type)
  3403. {
  3404. if (const BuiltinType *BT = dyn_cast<BuiltinType>(type))
  3405. {
  3406. switch (BT->getKind())
  3407. {
  3408. case BuiltinType::Bool: return AR_BASIC_BOOL;
  3409. case BuiltinType::Double: return AR_BASIC_FLOAT64;
  3410. case BuiltinType::Float: return AR_BASIC_FLOAT32;
  3411. case BuiltinType::Half: return AR_BASIC_FLOAT16;
  3412. case BuiltinType::HalfFloat: return AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  3413. case BuiltinType::Int: return AR_BASIC_INT32;
  3414. case BuiltinType::UInt: return AR_BASIC_UINT32;
  3415. case BuiltinType::Short: return AR_BASIC_INT16;
  3416. case BuiltinType::UShort: return AR_BASIC_UINT16;
  3417. case BuiltinType::Long: return AR_BASIC_INT32;
  3418. case BuiltinType::ULong: return AR_BASIC_UINT32;
  3419. case BuiltinType::LongLong: return AR_BASIC_INT64;
  3420. case BuiltinType::ULongLong: return AR_BASIC_UINT64;
  3421. case BuiltinType::Min12Int: return AR_BASIC_MIN12INT;
  3422. case BuiltinType::Min16Float: return AR_BASIC_MIN16FLOAT;
  3423. case BuiltinType::Min16Int: return AR_BASIC_MIN16INT;
  3424. case BuiltinType::Min16UInt: return AR_BASIC_MIN16UINT;
  3425. case BuiltinType::Min10Float: return AR_BASIC_MIN10FLOAT;
  3426. case BuiltinType::LitFloat: return AR_BASIC_LITERAL_FLOAT;
  3427. case BuiltinType::LitInt: return AR_BASIC_LITERAL_INT;
  3428. case BuiltinType::Dependent: return AR_BASIC_DEPENDENT;
  3429. default:
  3430. // Only builtin types that have basickind equivalents.
  3431. break;
  3432. }
  3433. }
  3434. if (const EnumType *ET = dyn_cast<EnumType>(type)) {
  3435. if (ET->getDecl()->isScopedUsingClassTag())
  3436. return AR_BASIC_ENUM_CLASS;
  3437. return AR_BASIC_ENUM;
  3438. }
  3439. return AR_BASIC_UNKNOWN;
  3440. }
  3441. void AddIntrinsicTableMethods(_In_ IDxcIntrinsicTable *table) {
  3442. DXASSERT_NOMSG(table != nullptr);
  3443. // Function intrinsics are added on-demand, objects get template methods.
  3444. for (unsigned i = 0; i < _countof(g_ArBasicKindsAsTypes); i++) {
  3445. // Grab information already processed by AddObjectTypes.
  3446. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  3447. const char *typeName = g_ArBasicTypeNames[kind];
  3448. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  3449. DXASSERT(templateArgCount <= 2, "otherwise a new case has been added");
  3450. int startDepth = (templateArgCount == 0) ? 0 : 1;
  3451. CXXRecordDecl *recordDecl = m_objectTypeDecls[i];
  3452. if (recordDecl == nullptr) {
  3453. DXASSERT(kind == AR_OBJECT_WAVE, "else objects other than reserved not initialized");
  3454. continue;
  3455. }
  3456. // This is a variation of AddObjectMethods using the new table.
  3457. const HLSL_INTRINSIC *pIntrinsic = nullptr;
  3458. const HLSL_INTRINSIC *pPrior = nullptr;
  3459. UINT64 lookupCookie = 0;
  3460. CA2W wideTypeName(typeName, CP_UTF8);
  3461. HRESULT found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  3462. while (pIntrinsic != nullptr && SUCCEEDED(found)) {
  3463. if (!AreIntrinsicTemplatesEquivalent(pIntrinsic, pPrior)) {
  3464. AddObjectIntrinsicTemplate(recordDecl, startDepth, pIntrinsic);
  3465. // NOTE: this only works with the current implementation because
  3466. // intrinsics are alive as long as the table is alive.
  3467. pPrior = pIntrinsic;
  3468. }
  3469. found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  3470. }
  3471. }
  3472. }
  3473. void RegisterIntrinsicTable(_In_ IDxcIntrinsicTable *table) {
  3474. DXASSERT_NOMSG(table != nullptr);
  3475. m_intrinsicTables.push_back(table);
  3476. // If already initialized, add methods immediately.
  3477. if (m_sema != nullptr) {
  3478. AddIntrinsicTableMethods(table);
  3479. }
  3480. }
  3481. HLSLScalarType ScalarTypeForBasic(ArBasicKind kind)
  3482. {
  3483. DXASSERT(kind < AR_BASIC_COUNT, "otherwise caller didn't check that the value was in range");
  3484. switch (kind) {
  3485. case AR_BASIC_BOOL: return HLSLScalarType_bool;
  3486. case AR_BASIC_LITERAL_FLOAT: return HLSLScalarType_float_lit;
  3487. case AR_BASIC_FLOAT16: return HLSLScalarType_half;
  3488. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  3489. return HLSLScalarType_float;
  3490. case AR_BASIC_FLOAT32: return HLSLScalarType_float;
  3491. case AR_BASIC_FLOAT64: return HLSLScalarType_double;
  3492. case AR_BASIC_LITERAL_INT: return HLSLScalarType_int_lit;
  3493. case AR_BASIC_INT8: return HLSLScalarType_int;
  3494. case AR_BASIC_UINT8: return HLSLScalarType_uint;
  3495. case AR_BASIC_INT16: return HLSLScalarType_int16;
  3496. case AR_BASIC_UINT16: return HLSLScalarType_uint16;
  3497. case AR_BASIC_INT32: return HLSLScalarType_int;
  3498. case AR_BASIC_UINT32: return HLSLScalarType_uint;
  3499. case AR_BASIC_MIN10FLOAT: return HLSLScalarType_float_min10;
  3500. case AR_BASIC_MIN16FLOAT: return HLSLScalarType_float_min16;
  3501. case AR_BASIC_MIN12INT: return HLSLScalarType_int_min12;
  3502. case AR_BASIC_MIN16INT: return HLSLScalarType_int_min16;
  3503. case AR_BASIC_MIN16UINT: return HLSLScalarType_uint_min16;
  3504. case AR_BASIC_INT64: return HLSLScalarType_int64;
  3505. case AR_BASIC_UINT64: return HLSLScalarType_uint64;
  3506. case AR_BASIC_ENUM: return HLSLScalarType_int;
  3507. default:
  3508. return HLSLScalarType_unknown;
  3509. }
  3510. }
  3511. QualType GetBasicKindType(ArBasicKind kind)
  3512. {
  3513. DXASSERT_VALIDBASICKIND(kind);
  3514. switch (kind) {
  3515. case AR_OBJECT_NULL: return m_context->VoidTy;
  3516. case AR_BASIC_BOOL: return m_context->BoolTy;
  3517. case AR_BASIC_LITERAL_FLOAT: return m_context->LitFloatTy;
  3518. case AR_BASIC_FLOAT16: return m_context->HalfTy;
  3519. case AR_BASIC_FLOAT32_PARTIAL_PRECISION: return m_context->HalfFloatTy;
  3520. case AR_BASIC_FLOAT32: return m_context->FloatTy;
  3521. case AR_BASIC_FLOAT64: return m_context->DoubleTy;
  3522. case AR_BASIC_LITERAL_INT: return m_context->LitIntTy;
  3523. case AR_BASIC_INT8: return m_context->IntTy;
  3524. case AR_BASIC_UINT8: return m_context->UnsignedIntTy;
  3525. case AR_BASIC_INT16: return m_context->ShortTy;
  3526. case AR_BASIC_UINT16: return m_context->UnsignedShortTy;
  3527. case AR_BASIC_INT32: return m_context->IntTy;
  3528. case AR_BASIC_UINT32: return m_context->UnsignedIntTy;
  3529. case AR_BASIC_INT64: return m_context->LongLongTy;
  3530. case AR_BASIC_UINT64: return m_context->UnsignedLongLongTy;
  3531. case AR_BASIC_MIN10FLOAT: return m_scalarTypes[HLSLScalarType_float_min10];
  3532. case AR_BASIC_MIN16FLOAT: return m_scalarTypes[HLSLScalarType_float_min16];
  3533. case AR_BASIC_MIN12INT: return m_scalarTypes[HLSLScalarType_int_min12];
  3534. case AR_BASIC_MIN16INT: return m_scalarTypes[HLSLScalarType_int_min16];
  3535. case AR_BASIC_MIN16UINT: return m_scalarTypes[HLSLScalarType_uint_min16];
  3536. case AR_BASIC_ENUM: return m_context->IntTy;
  3537. case AR_BASIC_ENUM_CLASS: return m_context->IntTy;
  3538. case AR_OBJECT_STRING: return m_hlslStringType;
  3539. case AR_OBJECT_STRING_LITERAL:
  3540. // m_hlslStringType is defined as 'char *'.
  3541. // for STRING_LITERAL we should use 'const char *'.
  3542. return m_context->getPointerType(m_context->CharTy.withConst());
  3543. case AR_OBJECT_LEGACY_EFFECT: // used for all legacy effect object types
  3544. case AR_OBJECT_TEXTURE1D:
  3545. case AR_OBJECT_TEXTURE1D_ARRAY:
  3546. case AR_OBJECT_TEXTURE2D:
  3547. case AR_OBJECT_TEXTURE2D_ARRAY:
  3548. case AR_OBJECT_TEXTURE3D:
  3549. case AR_OBJECT_TEXTURECUBE:
  3550. case AR_OBJECT_TEXTURECUBE_ARRAY:
  3551. case AR_OBJECT_TEXTURE2DMS:
  3552. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  3553. case AR_OBJECT_SAMPLER:
  3554. case AR_OBJECT_SAMPLERCOMPARISON:
  3555. case AR_OBJECT_RESOURCE:
  3556. case AR_OBJECT_BUFFER:
  3557. case AR_OBJECT_POINTSTREAM:
  3558. case AR_OBJECT_LINESTREAM:
  3559. case AR_OBJECT_TRIANGLESTREAM:
  3560. case AR_OBJECT_INPUTPATCH:
  3561. case AR_OBJECT_OUTPUTPATCH:
  3562. case AR_OBJECT_RWTEXTURE1D:
  3563. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  3564. case AR_OBJECT_RWTEXTURE2D:
  3565. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  3566. case AR_OBJECT_RWTEXTURE3D:
  3567. case AR_OBJECT_RWBUFFER:
  3568. case AR_OBJECT_BYTEADDRESS_BUFFER:
  3569. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  3570. case AR_OBJECT_STRUCTURED_BUFFER:
  3571. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  3572. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  3573. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  3574. case AR_OBJECT_WAVE:
  3575. case AR_OBJECT_ACCELERATION_STRUCT:
  3576. case AR_OBJECT_RAY_DESC:
  3577. case AR_OBJECT_TRIANGLE_INTERSECTION_ATTRIBUTES:
  3578. {
  3579. const ArBasicKind* match = std::find(g_ArBasicKindsAsTypes, &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], kind);
  3580. DXASSERT(match != &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], "otherwise can't find constant in basic kinds");
  3581. size_t index = match - g_ArBasicKindsAsTypes;
  3582. return m_context->getTagDeclType(this->m_objectTypeDecls[index]);
  3583. }
  3584. case AR_OBJECT_SAMPLER1D:
  3585. case AR_OBJECT_SAMPLER2D:
  3586. case AR_OBJECT_SAMPLER3D:
  3587. case AR_OBJECT_SAMPLERCUBE:
  3588. // Turn dimension-typed samplers into sampler states.
  3589. return GetBasicKindType(AR_OBJECT_SAMPLER);
  3590. case AR_OBJECT_STATEBLOCK:
  3591. case AR_OBJECT_RASTERIZER:
  3592. case AR_OBJECT_DEPTHSTENCIL:
  3593. case AR_OBJECT_BLEND:
  3594. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  3595. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  3596. default:
  3597. return QualType();
  3598. }
  3599. }
  3600. /// <summary>Promotes the specified expression to an integer type if it's a boolean type.</summary
  3601. /// <param name="E">Expression to typecast.</param>
  3602. /// <returns>E typecast to a integer type if it's a valid boolean type; E otherwise.</returns>
  3603. ExprResult PromoteToIntIfBool(ExprResult& E);
  3604. QualType NewQualifiedType(UINT64 qwUsages, QualType type)
  3605. {
  3606. // NOTE: NewQualifiedType does quite a bit more in the prior compiler
  3607. (void)(qwUsages);
  3608. return type;
  3609. }
  3610. QualType NewSimpleAggregateType(
  3611. _In_ ArTypeObjectKind ExplicitKind,
  3612. _In_ ArBasicKind componentType,
  3613. _In_ UINT64 qwQual,
  3614. _In_ UINT uRows,
  3615. _In_ UINT uCols)
  3616. {
  3617. DXASSERT_VALIDBASICKIND(componentType);
  3618. QualType pType; // The type to return.
  3619. if (componentType < AR_BASIC_COUNT) {
  3620. // If basic numeric, call LookupScalarTypeDef to ensure on-demand
  3621. // initialization
  3622. LookupScalarTypeDef(ScalarTypeForBasic(componentType));
  3623. }
  3624. QualType pEltType = GetBasicKindType(componentType);
  3625. DXASSERT(!pEltType.isNull(), "otherwise caller is specifying an incorrect basic kind type");
  3626. // TODO: handle adding qualifications like const
  3627. pType = NewQualifiedType(
  3628. qwQual & ~(UINT64)(AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR),
  3629. pEltType);
  3630. if (uRows > 1 ||
  3631. uCols > 1 ||
  3632. ExplicitKind == AR_TOBJ_VECTOR ||
  3633. ExplicitKind == AR_TOBJ_MATRIX)
  3634. {
  3635. HLSLScalarType scalarType = ScalarTypeForBasic(componentType);
  3636. DXASSERT(scalarType != HLSLScalarType_unknown, "otherwise caller is specifying an incorrect type");
  3637. if ((uRows == 1 &&
  3638. ExplicitKind != AR_TOBJ_MATRIX) ||
  3639. ExplicitKind == AR_TOBJ_VECTOR)
  3640. {
  3641. pType = LookupVectorType(scalarType, uCols);
  3642. }
  3643. else
  3644. {
  3645. pType = LookupMatrixType(scalarType, uRows, uCols);
  3646. }
  3647. // TODO: handle colmajor/rowmajor
  3648. //if ((qwQual & (AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR)) != 0)
  3649. //{
  3650. // VN(pType = NewQualifiedType(pSrcLoc,
  3651. // qwQual & (AR_QUAL_COLMAJOR |
  3652. // AR_QUAL_ROWMAJOR),
  3653. // pMatrix));
  3654. //}
  3655. //else
  3656. //{
  3657. // pType = pMatrix;
  3658. //}
  3659. }
  3660. return pType;
  3661. }
  3662. /// <summary>Attempts to match Args to the signature specification in pIntrinsic.</summary>
  3663. /// <param name="pIntrinsic">Intrinsic function to match.</param>
  3664. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  3665. /// <param name="Args">Invocation arguments to match.</param>
  3666. /// <param name="argTypes">After exectuion, type of arguments.</param>
  3667. /// <param name="argCount">After execution, number of arguments in argTypes.</param>
  3668. /// <remarks>On success, argTypes includes the clang Types to use for the signature, with the first being the return type.</remarks>
  3669. bool MatchArguments(
  3670. const _In_ HLSL_INTRINSIC *pIntrinsic,
  3671. _In_ QualType objectElement,
  3672. _In_ QualType functionTemplateTypeArg,
  3673. _In_ ArrayRef<Expr *> Args,
  3674. _Out_ std::vector<QualType> *);
  3675. /// <summary>Validate object element on intrinsic to catch case like integer on Sample.</summary>
  3676. /// <param name="pIntrinsic">Intrinsic function to validate.</param>
  3677. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  3678. bool IsValidateObjectElement(
  3679. _In_ const HLSL_INTRINSIC *pIntrinsic,
  3680. _In_ QualType objectElement);
  3681. // Returns the iterator with the first entry that matches the requirement
  3682. IntrinsicDefIter FindIntrinsicByNameAndArgCount(
  3683. _In_count_(tableSize) const HLSL_INTRINSIC* table,
  3684. size_t tableSize,
  3685. StringRef typeName,
  3686. StringRef nameIdentifier,
  3687. size_t argumentCount)
  3688. {
  3689. // This is implemented by a linear scan for now.
  3690. // We tested binary search on tables, and there was no performance gain on
  3691. // samples probably for the following reasons.
  3692. // 1. The tables are not big enough to make noticable difference
  3693. // 2. The user of this function assumes that it returns the first entry in
  3694. // the table that matches name and argument count. So even in the binary
  3695. // search, we have to scan backwards until the entry does not match the name
  3696. // or arg count. For linear search this is not a problem
  3697. for (unsigned int i = 0; i < tableSize; i++) {
  3698. const HLSL_INTRINSIC* pIntrinsic = &table[i];
  3699. const bool isVariadicFn = IsVariadicIntrinsicFunction(pIntrinsic);
  3700. // Do some quick checks to verify size and name.
  3701. if (!isVariadicFn && pIntrinsic->uNumArgs != 1 + argumentCount) {
  3702. continue;
  3703. }
  3704. if (!nameIdentifier.equals(StringRef(pIntrinsic->pArgs[0].pName))) {
  3705. continue;
  3706. }
  3707. return IntrinsicDefIter::CreateStart(table, tableSize, pIntrinsic,
  3708. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  3709. }
  3710. return IntrinsicDefIter::CreateStart(table, tableSize, table + tableSize,
  3711. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  3712. }
  3713. bool AddOverloadedCallCandidates(
  3714. UnresolvedLookupExpr *ULE,
  3715. ArrayRef<Expr *> Args,
  3716. OverloadCandidateSet &CandidateSet,
  3717. bool PartialOverloading) override
  3718. {
  3719. DXASSERT_NOMSG(ULE != nullptr);
  3720. // Intrinsics live in the global namespace, so references to their names
  3721. // should be either unqualified or '::'-prefixed.
  3722. if (ULE->getQualifier() && ULE->getQualifier()->getKind() != NestedNameSpecifier::Global) {
  3723. return false;
  3724. }
  3725. const DeclarationNameInfo declName = ULE->getNameInfo();
  3726. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  3727. if (idInfo == nullptr)
  3728. {
  3729. return false;
  3730. }
  3731. StringRef nameIdentifier = idInfo->getName();
  3732. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(
  3733. g_Intrinsics, _countof(g_Intrinsics), StringRef(), nameIdentifier, Args.size());
  3734. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(
  3735. g_Intrinsics, _countof(g_Intrinsics), IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  3736. while (cursor != end)
  3737. {
  3738. // If this is the intrinsic we're interested in, build up a representation
  3739. // of the types we need.
  3740. const HLSL_INTRINSIC* pIntrinsic = *cursor;
  3741. LPCSTR tableName = cursor.GetTableName();
  3742. LPCSTR lowering = cursor.GetLoweringStrategy();
  3743. DXASSERT(
  3744. pIntrinsic->uNumArgs <= g_MaxIntrinsicParamCount + 1,
  3745. "otherwise g_MaxIntrinsicParamCount needs to be updated for wider signatures");
  3746. std::vector<QualType> functionArgTypes;
  3747. if (!MatchArguments(pIntrinsic, QualType(), QualType(), Args, &functionArgTypes))
  3748. {
  3749. ++cursor;
  3750. continue;
  3751. }
  3752. // Get or create the overload we're interested in.
  3753. FunctionDecl* intrinsicFuncDecl = nullptr;
  3754. std::pair<UsedIntrinsicStore::iterator, bool> insertResult =
  3755. m_usedIntrinsics.insert(UsedIntrinsic(pIntrinsic, functionArgTypes));
  3756. bool insertedNewValue = insertResult.second;
  3757. if (insertedNewValue)
  3758. {
  3759. DXASSERT(tableName, "otherwise IDxcIntrinsicTable::GetTableName() failed");
  3760. intrinsicFuncDecl = AddHLSLIntrinsicFunction(*m_context, m_hlslNSDecl, tableName, lowering, pIntrinsic, &functionArgTypes);
  3761. insertResult.first->setFunctionDecl(intrinsicFuncDecl);
  3762. }
  3763. else
  3764. {
  3765. intrinsicFuncDecl = (*insertResult.first).getFunctionDecl();
  3766. }
  3767. OverloadCandidate& candidate = CandidateSet.addCandidate();
  3768. candidate.Function = intrinsicFuncDecl;
  3769. candidate.FoundDecl.setDecl(intrinsicFuncDecl);
  3770. candidate.Viable = true;
  3771. return true;
  3772. }
  3773. return false;
  3774. }
  3775. bool Initialize(ASTContext& context)
  3776. {
  3777. m_context = &context;
  3778. m_hlslNSDecl = NamespaceDecl::Create(context, context.getTranslationUnitDecl(),
  3779. /*Inline*/ false, SourceLocation(),
  3780. SourceLocation(), &context.Idents.get("hlsl"),
  3781. /*PrevDecl*/ nullptr);
  3782. m_hlslNSDecl->setImplicit();
  3783. AddBaseTypes();
  3784. AddHLSLScalarTypes();
  3785. AddHLSLStringType();
  3786. AddHLSLVectorTemplate(*m_context, &m_vectorTemplateDecl);
  3787. DXASSERT(m_vectorTemplateDecl != nullptr, "AddHLSLVectorTypes failed to return the vector template declaration");
  3788. AddHLSLMatrixTemplate(*m_context, m_vectorTemplateDecl, &m_matrixTemplateDecl);
  3789. DXASSERT(m_matrixTemplateDecl != nullptr, "AddHLSLMatrixTypes failed to return the matrix template declaration");
  3790. // Initializing built in integers for ray tracing
  3791. AddRaytracingConstants(*m_context);
  3792. AddSamplerFeedbackConstants(*m_context);
  3793. return true;
  3794. }
  3795. /// <summary>Checks whether the specified type is numeric or composed of numeric elements exclusively.</summary>
  3796. bool IsTypeNumeric(QualType type, _Out_ UINT* count);
  3797. /// <summary>Checks whether the specified type is a scalar type.</summary>
  3798. bool IsScalarType(const QualType& type) {
  3799. DXASSERT(!type.isNull(), "caller should validate its type is initialized");
  3800. return BasicTypeForScalarType(type->getCanonicalTypeUnqualified()) != AR_BASIC_UNKNOWN;
  3801. }
  3802. /// <summary>Checks whether the specified value is a valid vector size.</summary>
  3803. bool IsValidVectorSize(size_t length) {
  3804. return 1 <= length && length <= 4;
  3805. }
  3806. /// <summary>Checks whether the specified value is a valid matrix row or column size.</summary>
  3807. bool IsValidMatrixColOrRowSize(size_t length) {
  3808. return 1 <= length && length <= 4;
  3809. }
  3810. bool IsValidTemplateArgumentType(SourceLocation argLoc, const QualType& type, bool requireScalar) {
  3811. if (type.isNull()) {
  3812. return false;
  3813. }
  3814. if (type.hasQualifiers()) {
  3815. return false;
  3816. }
  3817. // TemplateTypeParm here will be construction of vector return template in matrix operator[]
  3818. if (type->getTypeClass() == Type::TemplateTypeParm)
  3819. return true;
  3820. QualType qt = GetStructuralForm(type);
  3821. if (requireScalar) {
  3822. if (!IsScalarType(qt)) {
  3823. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument_requires_scalar) << type;
  3824. return false;
  3825. }
  3826. return true;
  3827. }
  3828. else {
  3829. ArTypeObjectKind objectKind = GetTypeObjectKind(qt);
  3830. if (qt->isArrayType()) {
  3831. const ArrayType* arrayType = qt->getAsArrayTypeUnsafe();
  3832. return IsValidTemplateArgumentType(argLoc, arrayType->getElementType(), false);
  3833. }
  3834. else if (objectKind == AR_TOBJ_VECTOR) {
  3835. bool valid = true;
  3836. if (!IsValidVectorSize(GetHLSLVecSize(type))) {
  3837. valid = false;
  3838. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectorsize) << type << GetHLSLVecSize(type);
  3839. }
  3840. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  3841. valid = false;
  3842. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  3843. }
  3844. return valid;
  3845. }
  3846. else if (objectKind == AR_TOBJ_MATRIX) {
  3847. bool valid = true;
  3848. UINT rowCount, colCount;
  3849. GetRowsAndCols(type, rowCount, colCount);
  3850. if (!IsValidMatrixColOrRowSize(rowCount) || !IsValidMatrixColOrRowSize(colCount)) {
  3851. valid = false;
  3852. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedmatrixsize) << type << rowCount << colCount;
  3853. }
  3854. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  3855. valid = false;
  3856. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  3857. }
  3858. return valid;
  3859. }
  3860. else if (qt->isStructureType()) {
  3861. const RecordType* recordType = qt->getAsStructureType();
  3862. objectKind = ClassifyRecordType(recordType);
  3863. switch (objectKind)
  3864. {
  3865. case AR_TOBJ_OBJECT:
  3866. m_sema->Diag(argLoc, diag::err_hlsl_objectintemplateargument) << type;
  3867. return false;
  3868. case AR_TOBJ_COMPOUND:
  3869. {
  3870. const RecordDecl* recordDecl = recordType->getDecl();
  3871. RecordDecl::field_iterator begin = recordDecl->field_begin();
  3872. RecordDecl::field_iterator end = recordDecl->field_end();
  3873. bool result = true;
  3874. while (begin != end) {
  3875. const FieldDecl* fieldDecl = *begin;
  3876. if (!IsValidTemplateArgumentType(argLoc, fieldDecl->getType(), false)) {
  3877. m_sema->Diag(argLoc, diag::note_field_type_usage)
  3878. << fieldDecl->getType() << fieldDecl->getIdentifier() << type;
  3879. result = false;
  3880. }
  3881. begin++;
  3882. }
  3883. return result;
  3884. }
  3885. default:
  3886. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  3887. return false;
  3888. }
  3889. }
  3890. else if(IsScalarType(qt)) {
  3891. return true;
  3892. }
  3893. else {
  3894. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  3895. return false;
  3896. }
  3897. }
  3898. }
  3899. /// <summary>Checks whether the source type can be converted to the target type.</summary>
  3900. bool CanConvert(SourceLocation loc, Expr* sourceExpr, QualType target, bool explicitConversion,
  3901. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  3902. _Inout_opt_ StandardConversionSequence* sequence);
  3903. void CollectInfo(QualType type, _Out_ ArTypeInfo* pTypeInfo);
  3904. void GetConversionForm(
  3905. QualType type,
  3906. bool explicitConversion,
  3907. ArTypeInfo* pTypeInfo);
  3908. bool ValidateCast(SourceLocation Loc, _In_ Expr* source, QualType target, bool explicitConversion,
  3909. bool suppressWarnings, bool suppressErrors,
  3910. _Inout_opt_ StandardConversionSequence* sequence);
  3911. bool ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind);
  3912. bool ValidateTypeRequirements(
  3913. SourceLocation loc,
  3914. ArBasicKind elementKind,
  3915. ArTypeObjectKind objectKind,
  3916. bool requiresIntegrals,
  3917. bool requiresNumerics);
  3918. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  3919. /// <param name="OpLoc">Source location for operator.</param>
  3920. /// <param name="Opc">Kind of binary operator.</param>
  3921. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  3922. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  3923. /// <param name="ResultTy">Result type for operator expression.</param>
  3924. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  3925. /// <param name="CompResultTy">Type of computation result.</param>
  3926. void CheckBinOpForHLSL(
  3927. SourceLocation OpLoc,
  3928. BinaryOperatorKind Opc,
  3929. ExprResult& LHS,
  3930. ExprResult& RHS,
  3931. QualType& ResultTy,
  3932. QualType& CompLHSTy,
  3933. QualType& CompResultTy);
  3934. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  3935. /// <param name="OpLoc">Source location for operator.</param>
  3936. /// <param name="Opc">Kind of operator.</param>
  3937. /// <param name="InputExpr">Input expression to the operator.</param>
  3938. /// <param name="VK">Value kind for resulting expression.</param>
  3939. /// <param name="OK">Object kind for resulting expression.</param>
  3940. /// <returns>The result type for the expression.</returns>
  3941. QualType CheckUnaryOpForHLSL(
  3942. SourceLocation OpLoc,
  3943. UnaryOperatorKind Opc,
  3944. ExprResult& InputExpr,
  3945. ExprValueKind& VK,
  3946. ExprObjectKind& OK);
  3947. /// <summary>Checks vector conditional operator (Cond ? LHS : RHS).</summary>
  3948. /// <param name="Cond">Vector condition expression.</param>
  3949. /// <param name="LHS">Left hand side.</param>
  3950. /// <param name="RHS">Right hand side.</param>
  3951. /// <param name="QuestionLoc">Location of question mark in operator.</param>
  3952. /// <returns>Result type of vector conditional expression.</returns>
  3953. clang::QualType CheckVectorConditional(
  3954. _In_ ExprResult &Cond,
  3955. _In_ ExprResult &LHS,
  3956. _In_ ExprResult &RHS,
  3957. _In_ SourceLocation QuestionLoc);
  3958. clang::QualType ApplyTypeSpecSignToParsedType(
  3959. _In_ clang::QualType &type,
  3960. _In_ TypeSpecifierSign TSS,
  3961. _In_ SourceLocation Loc
  3962. );
  3963. bool CheckRangedTemplateArgument(SourceLocation diagLoc, llvm::APSInt& sintValue)
  3964. {
  3965. if (!sintValue.isStrictlyPositive() || sintValue.getLimitedValue() > 4)
  3966. {
  3967. m_sema->Diag(diagLoc, diag::err_hlsl_invalid_range_1_4);
  3968. return true;
  3969. }
  3970. return false;
  3971. }
  3972. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  3973. bool
  3974. CheckTemplateArgumentListForHLSL(_In_ TemplateDecl *Template,
  3975. SourceLocation /* TemplateLoc */,
  3976. TemplateArgumentListInfo &TemplateArgList) {
  3977. DXASSERT_NOMSG(Template != nullptr);
  3978. // Determine which object type the template refers to.
  3979. StringRef templateName = Template->getName();
  3980. // NOTE: this 'escape valve' allows unit tests to perform type checks.
  3981. if (templateName.equals(StringRef("is_same"))) {
  3982. return false;
  3983. }
  3984. bool isMatrix = Template->getCanonicalDecl() ==
  3985. m_matrixTemplateDecl->getCanonicalDecl();
  3986. bool isVector = Template->getCanonicalDecl() ==
  3987. m_vectorTemplateDecl->getCanonicalDecl();
  3988. bool requireScalar = isMatrix || isVector;
  3989. // Check constraints on the type. Right now we only check that template
  3990. // types are primitive types.
  3991. for (unsigned int i = 0; i < TemplateArgList.size(); i++) {
  3992. const TemplateArgumentLoc &argLoc = TemplateArgList[i];
  3993. SourceLocation argSrcLoc = argLoc.getLocation();
  3994. const TemplateArgument &arg = argLoc.getArgument();
  3995. if (arg.getKind() == TemplateArgument::ArgKind::Type) {
  3996. QualType argType = arg.getAsType();
  3997. if (!IsValidTemplateArgumentType(argSrcLoc, argType, requireScalar)) {
  3998. // NOTE: IsValidTemplateArgumentType emits its own diagnostics
  3999. return true;
  4000. }
  4001. }
  4002. else if (arg.getKind() == TemplateArgument::ArgKind::Expression) {
  4003. if (isMatrix || isVector) {
  4004. Expr *expr = arg.getAsExpr();
  4005. llvm::APSInt constantResult;
  4006. if (expr != nullptr &&
  4007. expr->isIntegerConstantExpr(constantResult, *m_context)) {
  4008. if (CheckRangedTemplateArgument(argSrcLoc, constantResult)) {
  4009. return true;
  4010. }
  4011. }
  4012. }
  4013. }
  4014. else if (arg.getKind() == TemplateArgument::ArgKind::Integral) {
  4015. if (isMatrix || isVector) {
  4016. llvm::APSInt Val = arg.getAsIntegral();
  4017. if (CheckRangedTemplateArgument(argSrcLoc, Val)) {
  4018. return true;
  4019. }
  4020. }
  4021. }
  4022. }
  4023. return false;
  4024. }
  4025. FindStructBasicTypeResult FindStructBasicType(_In_ DeclContext* functionDeclContext);
  4026. /// <summary>Finds the table of intrinsics for the declaration context of a member function.</summary>
  4027. /// <param name="functionDeclContext">Declaration context of function.</param>
  4028. /// <param name="name">After execution, the name of the object to which the table applies.</param>
  4029. /// <param name="intrinsics">After execution, the intrinsic table.</param>
  4030. /// <param name="intrinsicCount">After execution, the count of elements in the intrinsic table.</param>
  4031. void FindIntrinsicTable(
  4032. _In_ DeclContext* functionDeclContext,
  4033. _Outptr_result_z_ const char** name,
  4034. _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics,
  4035. _Out_ size_t* intrinsicCount);
  4036. /// <summary>Deduces the template arguments by comparing the argument types and the HLSL intrinsic tables.</summary>
  4037. /// <param name="FunctionTemplate">The declaration for the function template being deduced.</param>
  4038. /// <param name="ExplicitTemplateArgs">Explicitly-provided template arguments. Should be empty for an HLSL program.</param>
  4039. /// <param name="Args">Array of expressions being used as arguments.</param>
  4040. /// <param name="Specialization">The declaration for the resolved specialization.</param>
  4041. /// <param name="Info">Provides information about an attempted template argument deduction.</param>
  4042. /// <returns>The result of the template deduction, TDK_Invalid if no HLSL-specific processing done.</returns>
  4043. Sema::TemplateDeductionResult DeduceTemplateArgumentsForHLSL(
  4044. FunctionTemplateDecl *FunctionTemplate,
  4045. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  4046. FunctionDecl *&Specialization, TemplateDeductionInfo &Info);
  4047. clang::OverloadingResult GetBestViableFunction(
  4048. clang::SourceLocation Loc,
  4049. clang::OverloadCandidateSet& set,
  4050. clang::OverloadCandidateSet::iterator& Best);
  4051. /// <summary>
  4052. /// Initializes the specified <paramref name="initSequence" /> describing how
  4053. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  4054. /// </summary>
  4055. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  4056. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  4057. /// <param name="Args">Arguments to the initialization.</param>
  4058. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  4059. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  4060. void InitializeInitSequenceForHLSL(
  4061. const InitializedEntity& Entity,
  4062. const InitializationKind& Kind,
  4063. MultiExprArg Args,
  4064. bool TopLevelOfInitList,
  4065. _Inout_ InitializationSequence* initSequence);
  4066. /// <summary>
  4067. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  4068. /// </summary>
  4069. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  4070. bool IsConversionToLessOrEqualElements(
  4071. const ExprResult& sourceExpr,
  4072. const QualType& targetType,
  4073. bool explicitConversion);
  4074. /// <summary>
  4075. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  4076. /// </summary>
  4077. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  4078. bool IsConversionToLessOrEqualElements(
  4079. const QualType& sourceType,
  4080. const QualType& targetType,
  4081. bool explicitConversion);
  4082. /// <summary>Performs a member lookup on the specified BaseExpr if it's a matrix.</summary>
  4083. /// <param name="BaseExpr">Base expression for member access.</param>
  4084. /// <param name="MemberName">Name of member to look up.</param>
  4085. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  4086. /// <param name="OpLoc">Location of access operand.</param>
  4087. /// <param name="MemberLoc">Location of member.</param>
  4088. /// <returns>Result of lookup operation.</returns>
  4089. ExprResult LookupMatrixMemberExprForHLSL(
  4090. Expr& BaseExpr,
  4091. DeclarationName MemberName,
  4092. bool IsArrow,
  4093. SourceLocation OpLoc,
  4094. SourceLocation MemberLoc);
  4095. /// <summary>Performs a member lookup on the specified BaseExpr if it's a vector.</summary>
  4096. /// <param name="BaseExpr">Base expression for member access.</param>
  4097. /// <param name="MemberName">Name of member to look up.</param>
  4098. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  4099. /// <param name="OpLoc">Location of access operand.</param>
  4100. /// <param name="MemberLoc">Location of member.</param>
  4101. /// <returns>Result of lookup operation.</returns>
  4102. ExprResult LookupVectorMemberExprForHLSL(
  4103. Expr& BaseExpr,
  4104. DeclarationName MemberName,
  4105. bool IsArrow,
  4106. SourceLocation OpLoc,
  4107. SourceLocation MemberLoc);
  4108. /// <summary>Performs a member lookup on the specified BaseExpr if it's an array.</summary>
  4109. /// <param name="BaseExpr">Base expression for member access.</param>
  4110. /// <param name="MemberName">Name of member to look up.</param>
  4111. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  4112. /// <param name="OpLoc">Location of access operand.</param>
  4113. /// <param name="MemberLoc">Location of member.</param>
  4114. /// <returns>Result of lookup operation.</returns>
  4115. ExprResult LookupArrayMemberExprForHLSL(
  4116. Expr& BaseExpr,
  4117. DeclarationName MemberName,
  4118. bool IsArrow,
  4119. SourceLocation OpLoc,
  4120. SourceLocation MemberLoc);
  4121. /// <summary>If E is a scalar, converts it to a 1-element vector.</summary>
  4122. /// <param name="E">Expression to convert.</param>
  4123. /// <returns>The result of the conversion; or E if the type is not a scalar.</returns>
  4124. ExprResult MaybeConvertScalarToVector(_In_ clang::Expr* E);
  4125. clang::Expr *HLSLImpCastToScalar(
  4126. _In_ clang::Sema* self,
  4127. _In_ clang::Expr* From,
  4128. ArTypeObjectKind FromShape,
  4129. ArBasicKind EltKind);
  4130. clang::ExprResult PerformHLSLConversion(
  4131. _In_ clang::Expr* From,
  4132. _In_ clang::QualType targetType,
  4133. _In_ const clang::StandardConversionSequence &SCS,
  4134. _In_ clang::Sema::CheckedConversionKind CCK);
  4135. /// <summary>Diagnoses an error when precessing the specified type if nesting is too deep.</summary>
  4136. void ReportUnsupportedTypeNesting(SourceLocation loc, QualType type);
  4137. /// <summary>
  4138. /// Checks if a static cast can be performed, and performs it if possible.
  4139. /// </summary>
  4140. /// <param name="SrcExpr">Expression to cast.</param>
  4141. /// <param name="DestType">Type to cast SrcExpr to.</param>
  4142. /// <param name="CCK">Kind of conversion: implicit, C-style, functional, other.</param>
  4143. /// <param name="OpRange">Source range for the cast operation.</param>
  4144. /// <param name="msg">Error message from the diag::* enumeration to fail with; zero to suppress messages.</param>
  4145. /// <param name="Kind">The kind of operation required for a conversion.</param>
  4146. /// <param name="BasePath">A simple array of base specifiers.</param>
  4147. /// <param name="ListInitialization">Whether the cast is in the context of a list initialization.</param>
  4148. /// <param name="SuppressWarnings">Whether warnings should be omitted.</param>
  4149. /// <param name="SuppressErrors">Whether errors should be omitted.</param>
  4150. bool TryStaticCastForHLSL(ExprResult &SrcExpr,
  4151. QualType DestType,
  4152. Sema::CheckedConversionKind CCK,
  4153. const SourceRange &OpRange, unsigned &msg,
  4154. CastKind &Kind, CXXCastPath &BasePath,
  4155. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  4156. _Inout_opt_ StandardConversionSequence* standard);
  4157. /// <summary>
  4158. /// Checks if a subscript index argument can be initialized from the given expression.
  4159. /// </summary>
  4160. /// <param name="SrcExpr">Source expression used as argument.</param>
  4161. /// <param name="DestType">Parameter type to initialize.</param>
  4162. /// <remarks>
  4163. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  4164. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  4165. /// </remarks>
  4166. ImplicitConversionSequence TrySubscriptIndexInitialization(_In_ clang::Expr* SrcExpr, clang::QualType DestType);
  4167. void AddHLSLObjectMethodsIfNotReady(QualType qt) {
  4168. static_assert((sizeof(uint64_t)*8) >= _countof(g_ArBasicKindsAsTypes), "Bitmask size is too small");
  4169. // Everything is ready.
  4170. if (m_objectTypeLazyInitMask == 0)
  4171. return;
  4172. CXXRecordDecl *recordDecl = const_cast<CXXRecordDecl *>(GetRecordDeclForBuiltInOrStruct(qt->getAsCXXRecordDecl()));
  4173. int idx = FindObjectBasicKindIndex(recordDecl);
  4174. // Not object type.
  4175. if (idx == -1)
  4176. return;
  4177. uint64_t bit = ((uint64_t)1)<<idx;
  4178. // Already created.
  4179. if ((m_objectTypeLazyInitMask & bit) == 0)
  4180. return;
  4181. ArBasicKind kind = g_ArBasicKindsAsTypes[idx];
  4182. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[idx];
  4183. int startDepth = 0;
  4184. if (templateArgCount > 0) {
  4185. DXASSERT(templateArgCount == 1 || templateArgCount == 2,
  4186. "otherwise a new case has been added");
  4187. ClassTemplateDecl *typeDecl = recordDecl->getDescribedClassTemplate();
  4188. AddObjectSubscripts(kind, typeDecl, recordDecl,
  4189. g_ArBasicKindsSubscripts[idx]);
  4190. startDepth = 1;
  4191. }
  4192. AddObjectMethods(kind, recordDecl, startDepth);
  4193. // Clear the object.
  4194. m_objectTypeLazyInitMask &= ~bit;
  4195. }
  4196. FunctionDecl* AddHLSLIntrinsicMethod(
  4197. LPCSTR tableName,
  4198. LPCSTR lowering,
  4199. _In_ const HLSL_INTRINSIC* intrinsic,
  4200. _In_ FunctionTemplateDecl *FunctionTemplate,
  4201. ArrayRef<Expr *> Args,
  4202. _In_count_(parameterTypeCount) QualType* parameterTypes,
  4203. size_t parameterTypeCount)
  4204. {
  4205. DXASSERT_NOMSG(intrinsic != nullptr);
  4206. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  4207. DXASSERT_NOMSG(parameterTypes != nullptr);
  4208. DXASSERT(parameterTypeCount >= 1, "otherwise caller didn't initialize - there should be at least a void return type");
  4209. // Create the template arguments.
  4210. SmallVector<TemplateArgument, g_MaxIntrinsicParamCount + 1> templateArgs;
  4211. for (size_t i = 0; i < parameterTypeCount; i++) {
  4212. templateArgs.push_back(TemplateArgument(parameterTypes[i]));
  4213. }
  4214. // Look for an existing specialization.
  4215. void *InsertPos = nullptr;
  4216. FunctionDecl *SpecFunc =
  4217. FunctionTemplate->findSpecialization(templateArgs, InsertPos);
  4218. if (SpecFunc != nullptr) {
  4219. return SpecFunc;
  4220. }
  4221. // Change return type to lvalue reference type for aggregate types
  4222. QualType retTy = parameterTypes[0];
  4223. if (hlsl::IsHLSLAggregateType(retTy))
  4224. parameterTypes[0] = m_context->getLValueReferenceType(retTy);
  4225. // Create a new specialization.
  4226. SmallVector<ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  4227. InitParamMods(intrinsic, paramMods);
  4228. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  4229. // Change out/inout parameter type to rvalue reference type.
  4230. if (paramMods[i - 1].isAnyOut()) {
  4231. parameterTypes[i] = m_context->getLValueReferenceType(parameterTypes[i]);
  4232. }
  4233. }
  4234. IntrinsicOp intrinOp = static_cast<IntrinsicOp>(intrinsic->Op);
  4235. if (intrinOp == IntrinsicOp::MOP_SampleBias) {
  4236. // Remove this when update intrinsic table not affect other things.
  4237. // Change vector<float,1> into float for bias.
  4238. const unsigned biasOperandID = 3; // return type, sampler, coord, bias.
  4239. DXASSERT(parameterTypeCount > biasOperandID,
  4240. "else operation was misrecognized");
  4241. if (const ExtVectorType *VecTy =
  4242. hlsl::ConvertHLSLVecMatTypeToExtVectorType(
  4243. *m_context, parameterTypes[biasOperandID])) {
  4244. if (VecTy->getNumElements() == 1)
  4245. parameterTypes[biasOperandID] = VecTy->getElementType();
  4246. }
  4247. }
  4248. DeclContext *owner = FunctionTemplate->getDeclContext();
  4249. TemplateArgumentList templateArgumentList(
  4250. TemplateArgumentList::OnStackType::OnStack, templateArgs.data(),
  4251. templateArgs.size());
  4252. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  4253. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner,
  4254. mlTemplateArgumentList);
  4255. FunctionProtoType::ExtProtoInfo EmptyEPI;
  4256. QualType functionType = m_context->getFunctionType(
  4257. parameterTypes[0],
  4258. ArrayRef<QualType>(parameterTypes + 1, parameterTypeCount - 1),
  4259. EmptyEPI, paramMods);
  4260. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  4261. FunctionProtoTypeLoc Proto =
  4262. TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  4263. SmallVector<ParmVarDecl*, g_MaxIntrinsicParamCount> Params;
  4264. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  4265. IdentifierInfo* id = &m_context->Idents.get(StringRef(intrinsic->pArgs[i - 1].pName));
  4266. ParmVarDecl *paramDecl = ParmVarDecl::Create(
  4267. *m_context, nullptr, NoLoc, NoLoc, id, parameterTypes[i], nullptr,
  4268. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  4269. Params.push_back(paramDecl);
  4270. }
  4271. QualType T = TInfo->getType();
  4272. DeclarationNameInfo NameInfo(FunctionTemplate->getDeclName(), NoLoc);
  4273. CXXMethodDecl* method = CXXMethodDecl::Create(
  4274. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  4275. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  4276. // Add intrinsic attr
  4277. AddHLSLIntrinsicAttr(method, *m_context, tableName, lowering, intrinsic);
  4278. // Record this function template specialization.
  4279. TemplateArgumentList *argListCopy = TemplateArgumentList::CreateCopy(
  4280. *m_context, templateArgs.data(), templateArgs.size());
  4281. method->setFunctionTemplateSpecialization(FunctionTemplate, argListCopy, 0);
  4282. // Attach the parameters
  4283. for (unsigned P = 0; P < Params.size(); ++P) {
  4284. Params[P]->setOwningFunction(method);
  4285. Proto.setParam(P, Params[P]);
  4286. }
  4287. method->setParams(Params);
  4288. // Adjust access.
  4289. method->setAccess(AccessSpecifier::AS_public);
  4290. FunctionTemplate->setAccess(method->getAccess());
  4291. return method;
  4292. }
  4293. // Overload support.
  4294. UINT64 ScoreCast(QualType leftType, QualType rightType);
  4295. UINT64 ScoreFunction(OverloadCandidateSet::iterator &Cand);
  4296. UINT64 ScoreImplicitConversionSequence(const ImplicitConversionSequence *s);
  4297. unsigned GetNumElements(QualType anyType);
  4298. unsigned GetNumBasicElements(QualType anyType);
  4299. unsigned GetNumConvertCheckElts(QualType leftType, unsigned leftSize, QualType rightType, unsigned rightSize);
  4300. QualType GetNthElementType(QualType type, unsigned index);
  4301. bool IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind);
  4302. bool IsCast(ArBasicKind leftKind, ArBasicKind rightKind);
  4303. bool IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind);
  4304. };
  4305. TYPE_CONVERSION_REMARKS HLSLExternalSource::RemarksUnused = TYPE_CONVERSION_REMARKS::TYPE_CONVERSION_NONE;
  4306. ImplicitConversionKind HLSLExternalSource::ImplicitConversionKindUnused = ImplicitConversionKind::ICK_Identity;
  4307. // Use this class to flatten a type into HLSL primitives and iterate through them.
  4308. class FlattenedTypeIterator
  4309. {
  4310. private:
  4311. enum FlattenedIterKind {
  4312. FK_Simple,
  4313. FK_Fields,
  4314. FK_Expressions,
  4315. FK_IncompleteArray,
  4316. FK_Bases,
  4317. };
  4318. // Use this struct to represent a specific point in the tracked tree.
  4319. struct FlattenedTypeTracker {
  4320. QualType Type; // Type at this position in the tree.
  4321. unsigned int Count; // Count of consecutive types
  4322. CXXRecordDecl::base_class_iterator CurrentBase; // Current base for a structure type.
  4323. CXXRecordDecl::base_class_iterator EndBase; // STL-style end of bases.
  4324. RecordDecl::field_iterator CurrentField; // Current field in for a structure type.
  4325. RecordDecl::field_iterator EndField; // STL-style end of fields.
  4326. MultiExprArg::iterator CurrentExpr; // Current expression (advanceable for a list of expressions).
  4327. MultiExprArg::iterator EndExpr; // STL-style end of expressions.
  4328. FlattenedIterKind IterKind; // Kind of tracker.
  4329. bool IsConsidered; // If a FlattenedTypeTracker already been considered.
  4330. FlattenedTypeTracker(QualType type)
  4331. : Type(type), Count(0), CurrentExpr(nullptr),
  4332. IterKind(FK_IncompleteArray), IsConsidered(false) {}
  4333. FlattenedTypeTracker(QualType type, unsigned int count,
  4334. MultiExprArg::iterator expression)
  4335. : Type(type), Count(count), CurrentExpr(expression),
  4336. IterKind(FK_Simple), IsConsidered(false) {}
  4337. FlattenedTypeTracker(QualType type, RecordDecl::field_iterator current,
  4338. RecordDecl::field_iterator end)
  4339. : Type(type), Count(0), CurrentField(current), EndField(end),
  4340. CurrentExpr(nullptr), IterKind(FK_Fields), IsConsidered(false) {}
  4341. FlattenedTypeTracker(MultiExprArg::iterator current,
  4342. MultiExprArg::iterator end)
  4343. : Count(0), CurrentExpr(current), EndExpr(end),
  4344. IterKind(FK_Expressions), IsConsidered(false) {}
  4345. FlattenedTypeTracker(QualType type,
  4346. CXXRecordDecl::base_class_iterator current,
  4347. CXXRecordDecl::base_class_iterator end)
  4348. : Count(0), CurrentBase(current), EndBase(end), CurrentExpr(nullptr),
  4349. IterKind(FK_Bases), IsConsidered(false) {}
  4350. /// <summary>Gets the current expression if one is available.</summary>
  4351. Expr* getExprOrNull() const { return CurrentExpr ? *CurrentExpr : nullptr; }
  4352. /// <summary>Replaces the current expression.</summary>
  4353. void replaceExpr(Expr* e) { *CurrentExpr = e; }
  4354. };
  4355. HLSLExternalSource& m_source; // Source driving the iteration.
  4356. SmallVector<FlattenedTypeTracker, 4> m_typeTrackers; // Active stack of trackers.
  4357. bool m_draining; // Whether the iterator is meant to drain (will not generate new elements in incomplete arrays).
  4358. bool m_springLoaded; // Whether the current element has been set up by an incomplete array but hasn't been used yet.
  4359. unsigned int m_incompleteCount; // The number of elements in an incomplete array.
  4360. size_t m_typeDepth; // Depth of type analysis, to avoid stack overflows.
  4361. QualType m_firstType; // Name of first type found, used for diagnostics.
  4362. SourceLocation m_loc; // Location used for diagnostics.
  4363. static const size_t MaxTypeDepth = 100;
  4364. void advanceLeafTracker();
  4365. /// <summary>Consumes leaves.</summary>
  4366. void consumeLeaf();
  4367. /// <summary>Considers whether the leaf has a usable expression without consuming anything.</summary>
  4368. bool considerLeaf();
  4369. /// <summary>Pushes a tracker for the specified expression; returns true if there is something to evaluate.</summary>
  4370. bool pushTrackerForExpression(MultiExprArg::iterator expression);
  4371. /// <summary>Pushes a tracker for the specified type; returns true if there is something to evaluate.</summary>
  4372. bool pushTrackerForType(QualType type, _In_opt_ MultiExprArg::iterator expression);
  4373. public:
  4374. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  4375. FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source);
  4376. /// <summary>Constructs a FlattenedTypeIterator for the specified arguments.</summary>
  4377. FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source);
  4378. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  4379. QualType getCurrentElement() const;
  4380. /// <summary>Get the number of repeated current elements.</summary>
  4381. unsigned int getCurrentElementSize() const;
  4382. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  4383. bool hasCurrentElement() const;
  4384. /// <summary>Consumes count elements on this iterator.</summary>
  4385. void advanceCurrentElement(unsigned int count);
  4386. /// <summary>Counts the remaining elements in this iterator (consuming all elements).</summary>
  4387. unsigned int countRemaining();
  4388. /// <summary>Gets the current expression if one is available.</summary>
  4389. Expr* getExprOrNull() const { return m_typeTrackers.back().getExprOrNull(); }
  4390. /// <summary>Replaces the current expression.</summary>
  4391. void replaceExpr(Expr* e) { m_typeTrackers.back().replaceExpr(e); }
  4392. struct ComparisonResult
  4393. {
  4394. unsigned int LeftCount;
  4395. unsigned int RightCount;
  4396. /// <summary>Whether elements from right sequence are identical into left sequence elements.</summary>
  4397. bool AreElementsEqual;
  4398. /// <summary>Whether elements from right sequence can be converted into left sequence elements.</summary>
  4399. bool CanConvertElements;
  4400. /// <summary>Whether the elements can be converted and the sequences have the same length.</summary>
  4401. bool IsConvertibleAndEqualLength() const {
  4402. return CanConvertElements && LeftCount == RightCount;
  4403. }
  4404. /// <summary>Whether the elements can be converted but the left-hand sequence is longer.</summary>
  4405. bool IsConvertibleAndLeftLonger() const {
  4406. return CanConvertElements && LeftCount > RightCount;
  4407. }
  4408. bool IsRightLonger() const {
  4409. return RightCount > LeftCount;
  4410. }
  4411. bool IsEqualLength() const {
  4412. return LeftCount == RightCount;
  4413. }
  4414. };
  4415. static ComparisonResult CompareIterators(
  4416. HLSLExternalSource& source, SourceLocation loc,
  4417. FlattenedTypeIterator& leftIter, FlattenedTypeIterator& rightIter);
  4418. static ComparisonResult CompareTypes(
  4419. HLSLExternalSource& source,
  4420. SourceLocation leftLoc, SourceLocation rightLoc,
  4421. QualType left, QualType right);
  4422. // Compares the arguments to initialize the left type, modifying them if necessary.
  4423. static ComparisonResult CompareTypesForInit(
  4424. HLSLExternalSource& source, QualType left, MultiExprArg args,
  4425. SourceLocation leftLoc, SourceLocation rightLoc);
  4426. };
  4427. static
  4428. QualType GetFirstElementTypeFromDecl(const Decl* decl)
  4429. {
  4430. const ClassTemplateSpecializationDecl* specialization = dyn_cast<ClassTemplateSpecializationDecl>(decl);
  4431. if (specialization) {
  4432. const TemplateArgumentList& list = specialization->getTemplateArgs();
  4433. if (list.size()) {
  4434. if (list[0].getKind() == TemplateArgument::ArgKind::Type)
  4435. return list[0].getAsType();
  4436. }
  4437. }
  4438. return QualType();
  4439. }
  4440. void HLSLExternalSource::AddBaseTypes()
  4441. {
  4442. DXASSERT(m_baseTypes[HLSLScalarType_unknown].isNull(), "otherwise unknown was initialized to an actual type");
  4443. m_baseTypes[HLSLScalarType_bool] = m_context->BoolTy;
  4444. m_baseTypes[HLSLScalarType_int] = m_context->IntTy;
  4445. m_baseTypes[HLSLScalarType_uint] = m_context->UnsignedIntTy;
  4446. m_baseTypes[HLSLScalarType_dword] = m_context->UnsignedIntTy;
  4447. m_baseTypes[HLSLScalarType_half] = m_context->getLangOpts().UseMinPrecision ? m_context->HalfFloatTy : m_context->HalfTy;
  4448. m_baseTypes[HLSLScalarType_float] = m_context->FloatTy;
  4449. m_baseTypes[HLSLScalarType_double] = m_context->DoubleTy;
  4450. m_baseTypes[HLSLScalarType_float_min10] = m_context->Min10FloatTy;
  4451. m_baseTypes[HLSLScalarType_float_min16] = m_context->Min16FloatTy;
  4452. m_baseTypes[HLSLScalarType_int_min12] = m_context->Min12IntTy;
  4453. m_baseTypes[HLSLScalarType_int_min16] = m_context->Min16IntTy;
  4454. m_baseTypes[HLSLScalarType_uint_min16] = m_context->Min16UIntTy;
  4455. m_baseTypes[HLSLScalarType_float_lit] = m_context->LitFloatTy;
  4456. m_baseTypes[HLSLScalarType_int_lit] = m_context->LitIntTy;
  4457. m_baseTypes[HLSLScalarType_int16] = m_context->ShortTy;
  4458. m_baseTypes[HLSLScalarType_int32] = m_context->IntTy;
  4459. m_baseTypes[HLSLScalarType_int64] = m_context->LongLongTy;
  4460. m_baseTypes[HLSLScalarType_uint16] = m_context->UnsignedShortTy;
  4461. m_baseTypes[HLSLScalarType_uint32] = m_context->UnsignedIntTy;
  4462. m_baseTypes[HLSLScalarType_uint64] = m_context->UnsignedLongLongTy;
  4463. m_baseTypes[HLSLScalarType_float16] = m_context->HalfTy;
  4464. m_baseTypes[HLSLScalarType_float32] = m_context->FloatTy;
  4465. m_baseTypes[HLSLScalarType_float64] = m_context->DoubleTy;
  4466. }
  4467. void HLSLExternalSource::AddHLSLScalarTypes()
  4468. {
  4469. DXASSERT(m_scalarTypes[HLSLScalarType_unknown].isNull(), "otherwise unknown was initialized to an actual type");
  4470. m_scalarTypes[HLSLScalarType_bool] = m_baseTypes[HLSLScalarType_bool];
  4471. m_scalarTypes[HLSLScalarType_int] = m_baseTypes[HLSLScalarType_int];
  4472. m_scalarTypes[HLSLScalarType_float] = m_baseTypes[HLSLScalarType_float];
  4473. m_scalarTypes[HLSLScalarType_double] = m_baseTypes[HLSLScalarType_double];
  4474. m_scalarTypes[HLSLScalarType_float_lit] = m_baseTypes[HLSLScalarType_float_lit];
  4475. m_scalarTypes[HLSLScalarType_int_lit] = m_baseTypes[HLSLScalarType_int_lit];
  4476. }
  4477. void HLSLExternalSource::AddHLSLStringType() {
  4478. m_hlslStringType = m_context->HLSLStringTy;
  4479. }
  4480. FunctionDecl* HLSLExternalSource::AddSubscriptSpecialization(
  4481. _In_ FunctionTemplateDecl* functionTemplate,
  4482. QualType objectElement,
  4483. const FindStructBasicTypeResult& findResult)
  4484. {
  4485. DXASSERT_NOMSG(functionTemplate != nullptr);
  4486. DXASSERT_NOMSG(!objectElement.isNull());
  4487. DXASSERT_NOMSG(findResult.Found());
  4488. DXASSERT(
  4489. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality > 0,
  4490. "otherwise the template shouldn't have an operator[] that the caller is trying to specialize");
  4491. // Subscript is templated only on its return type.
  4492. // Create the template argument.
  4493. bool isReadWrite = GetBasicKindProps(findResult.Kind) & BPROP_RWBUFFER;
  4494. QualType resultType = objectElement;
  4495. if (!isReadWrite) resultType = m_context->getConstType(resultType);
  4496. resultType = m_context->getLValueReferenceType(resultType);
  4497. TemplateArgument templateArgument(resultType);
  4498. unsigned subscriptCardinality =
  4499. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality;
  4500. QualType subscriptIndexType =
  4501. subscriptCardinality == 1
  4502. ? m_context->UnsignedIntTy
  4503. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  4504. subscriptCardinality);
  4505. // Look for an existing specialization.
  4506. void* InsertPos = nullptr;
  4507. FunctionDecl *SpecFunc = functionTemplate->findSpecialization(ArrayRef<TemplateArgument>(&templateArgument, 1), InsertPos);
  4508. if (SpecFunc != nullptr) {
  4509. return SpecFunc;
  4510. }
  4511. // Create a new specialization.
  4512. DeclContext* owner = functionTemplate->getDeclContext();
  4513. TemplateArgumentList templateArgumentList(
  4514. TemplateArgumentList::OnStackType::OnStack, &templateArgument, 1);
  4515. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  4516. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner, mlTemplateArgumentList);
  4517. const FunctionType *templateFnType = functionTemplate->getTemplatedDecl()->getType()->getAs<FunctionType>();
  4518. const FunctionProtoType *protoType = dyn_cast<FunctionProtoType>(templateFnType);
  4519. FunctionProtoType::ExtProtoInfo templateEPI = protoType->getExtProtoInfo();
  4520. QualType functionType = m_context->getFunctionType(
  4521. resultType, subscriptIndexType, templateEPI, None);
  4522. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  4523. FunctionProtoTypeLoc Proto = TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  4524. IdentifierInfo* id = &m_context->Idents.get(StringRef("index"));
  4525. ParmVarDecl* indexerParam = ParmVarDecl::Create(
  4526. *m_context, nullptr, NoLoc, NoLoc, id, subscriptIndexType, nullptr, StorageClass::SC_None, nullptr);
  4527. QualType T = TInfo->getType();
  4528. DeclarationNameInfo NameInfo(functionTemplate->getDeclName(), NoLoc);
  4529. CXXMethodDecl* method = CXXMethodDecl::Create(
  4530. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  4531. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  4532. // Add subscript attribute
  4533. AddHLSLSubscriptAttr(method, *m_context, HLSubscriptOpcode::DefaultSubscript);
  4534. // Record this function template specialization.
  4535. method->setFunctionTemplateSpecialization(functionTemplate,
  4536. TemplateArgumentList::CreateCopy(*m_context, &templateArgument, 1), 0);
  4537. // Attach the parameters
  4538. indexerParam->setOwningFunction(method);
  4539. Proto.setParam(0, indexerParam);
  4540. method->setParams(ArrayRef<ParmVarDecl*>(indexerParam));
  4541. // Adjust access.
  4542. method->setAccess(AccessSpecifier::AS_public);
  4543. functionTemplate->setAccess(method->getAccess());
  4544. return method;
  4545. }
  4546. /// <summary>
  4547. /// This routine combines Source into Target. If you have a symmetric operation
  4548. /// and want to treat either side equally you should call it twice, swapping the
  4549. /// parameter order.
  4550. /// </summary>
  4551. static bool CombineObjectTypes(ArBasicKind Target, _In_ ArBasicKind Source,
  4552. _Out_opt_ ArBasicKind *pCombined) {
  4553. if (Target == Source) {
  4554. AssignOpt(Target, pCombined);
  4555. return true;
  4556. }
  4557. if (Source == AR_OBJECT_NULL) {
  4558. // NULL is valid for any object type.
  4559. AssignOpt(Target, pCombined);
  4560. return true;
  4561. }
  4562. switch (Target) {
  4563. AR_BASIC_ROBJECT_CASES:
  4564. if (Source == AR_OBJECT_STATEBLOCK) {
  4565. AssignOpt(Target, pCombined);
  4566. return true;
  4567. }
  4568. break;
  4569. AR_BASIC_TEXTURE_CASES:
  4570. AR_BASIC_NON_CMP_SAMPLER_CASES:
  4571. if (Source == AR_OBJECT_SAMPLER || Source == AR_OBJECT_STATEBLOCK) {
  4572. AssignOpt(Target, pCombined);
  4573. return true;
  4574. }
  4575. break;
  4576. case AR_OBJECT_SAMPLERCOMPARISON:
  4577. if (Source == AR_OBJECT_STATEBLOCK) {
  4578. AssignOpt(Target, pCombined);
  4579. return true;
  4580. }
  4581. break;
  4582. default:
  4583. // Not a combinable target.
  4584. break;
  4585. }
  4586. AssignOpt(AR_BASIC_UNKNOWN, pCombined);
  4587. return false;
  4588. }
  4589. static ArBasicKind LiteralToConcrete(Expr *litExpr,
  4590. HLSLExternalSource *pHLSLExternalSource) {
  4591. if (IntegerLiteral *intLit = dyn_cast<IntegerLiteral>(litExpr)) {
  4592. llvm::APInt val = intLit->getValue();
  4593. unsigned width = val.getActiveBits();
  4594. bool isNeg = val.isNegative();
  4595. if (isNeg) {
  4596. // Signed.
  4597. if (width <= 32)
  4598. return ArBasicKind::AR_BASIC_INT32;
  4599. else
  4600. return ArBasicKind::AR_BASIC_INT64;
  4601. } else {
  4602. // Unsigned.
  4603. if (width <= 32)
  4604. return ArBasicKind::AR_BASIC_UINT32;
  4605. else
  4606. return ArBasicKind::AR_BASIC_UINT64;
  4607. }
  4608. } else if (FloatingLiteral *floatLit = dyn_cast<FloatingLiteral>(litExpr)) {
  4609. llvm::APFloat val = floatLit->getValue();
  4610. unsigned width = val.getSizeInBits(val.getSemantics());
  4611. if (width <= 16)
  4612. return ArBasicKind::AR_BASIC_FLOAT16;
  4613. else if (width <= 32)
  4614. return ArBasicKind::AR_BASIC_FLOAT32;
  4615. else
  4616. return AR_BASIC_FLOAT64;
  4617. } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(litExpr)) {
  4618. ArBasicKind kind = LiteralToConcrete(UO->getSubExpr(), pHLSLExternalSource);
  4619. if (UO->getOpcode() == UnaryOperator::Opcode::UO_Minus) {
  4620. if (kind == ArBasicKind::AR_BASIC_UINT32)
  4621. kind = ArBasicKind::AR_BASIC_INT32;
  4622. else if (kind == ArBasicKind::AR_BASIC_UINT64)
  4623. kind = ArBasicKind::AR_BASIC_INT64;
  4624. }
  4625. return kind;
  4626. } else if (HLSLVectorElementExpr *VEE = dyn_cast<HLSLVectorElementExpr>(litExpr)) {
  4627. return pHLSLExternalSource->GetTypeElementKind(VEE->getType());
  4628. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(litExpr)) {
  4629. ArBasicKind kind = LiteralToConcrete(BO->getLHS(), pHLSLExternalSource);
  4630. ArBasicKind kind1 = LiteralToConcrete(BO->getRHS(), pHLSLExternalSource);
  4631. CombineBasicTypes(kind, kind1, &kind);
  4632. return kind;
  4633. } else if (ParenExpr *PE = dyn_cast<ParenExpr>(litExpr)) {
  4634. ArBasicKind kind = LiteralToConcrete(PE->getSubExpr(), pHLSLExternalSource);
  4635. return kind;
  4636. } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(litExpr)) {
  4637. ArBasicKind kind = LiteralToConcrete(CO->getLHS(), pHLSLExternalSource);
  4638. ArBasicKind kind1 = LiteralToConcrete(CO->getRHS(), pHLSLExternalSource);
  4639. CombineBasicTypes(kind, kind1, &kind);
  4640. return kind;
  4641. } else if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(litExpr)) {
  4642. // Use target Type for cast.
  4643. ArBasicKind kind = pHLSLExternalSource->GetTypeElementKind(IC->getType());
  4644. return kind;
  4645. } else {
  4646. // Could only be function call.
  4647. CallExpr *CE = cast<CallExpr>(litExpr);
  4648. // TODO: calculate the function call result.
  4649. if (CE->getNumArgs() == 1)
  4650. return LiteralToConcrete(CE->getArg(0), pHLSLExternalSource);
  4651. else {
  4652. ArBasicKind kind = LiteralToConcrete(CE->getArg(0), pHLSLExternalSource);
  4653. for (unsigned i = 1; i < CE->getNumArgs(); i++) {
  4654. ArBasicKind kindI = LiteralToConcrete(CE->getArg(i), pHLSLExternalSource);
  4655. CombineBasicTypes(kind, kindI, &kind);
  4656. }
  4657. return kind;
  4658. }
  4659. }
  4660. }
  4661. static bool SearchTypeInTable(ArBasicKind kind, const ArBasicKind *pCT) {
  4662. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4663. if (kind == *pCT)
  4664. return true;
  4665. pCT++;
  4666. }
  4667. return false;
  4668. }
  4669. static ArBasicKind
  4670. ConcreteLiteralType(Expr *litExpr, ArBasicKind kind,
  4671. unsigned uLegalComponentTypes,
  4672. HLSLExternalSource *pHLSLExternalSource) {
  4673. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[uLegalComponentTypes];
  4674. ArBasicKind defaultKind = *pCT;
  4675. // Use first none literal kind as defaultKind.
  4676. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4677. ArBasicKind kind = *pCT;
  4678. pCT++;
  4679. // Skip literal type.
  4680. if (kind == AR_BASIC_LITERAL_INT || kind == AR_BASIC_LITERAL_FLOAT)
  4681. continue;
  4682. defaultKind = kind;
  4683. break;
  4684. }
  4685. ArBasicKind litKind = LiteralToConcrete(litExpr, pHLSLExternalSource);
  4686. if (kind == AR_BASIC_LITERAL_INT) {
  4687. // Search for match first.
  4688. // For literal arg which don't affect return type, the search should always success.
  4689. // Unless use literal int on a float parameter.
  4690. if (SearchTypeInTable(litKind, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4691. return litKind;
  4692. // Return the default.
  4693. return defaultKind;
  4694. }
  4695. else {
  4696. // Search for float32 first.
  4697. if (SearchTypeInTable(AR_BASIC_FLOAT32, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4698. return AR_BASIC_FLOAT32;
  4699. // Search for float64.
  4700. if (SearchTypeInTable(AR_BASIC_FLOAT64, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4701. return AR_BASIC_FLOAT64;
  4702. // return default.
  4703. return defaultKind;
  4704. }
  4705. }
  4706. _Use_decl_annotations_ bool
  4707. HLSLExternalSource::IsValidateObjectElement(const HLSL_INTRINSIC *pIntrinsic,
  4708. QualType objectElement) {
  4709. IntrinsicOp op = static_cast<IntrinsicOp>(pIntrinsic->Op);
  4710. switch (op) {
  4711. case IntrinsicOp::MOP_Sample:
  4712. case IntrinsicOp::MOP_SampleBias:
  4713. case IntrinsicOp::MOP_SampleCmp:
  4714. case IntrinsicOp::MOP_SampleCmpLevelZero:
  4715. case IntrinsicOp::MOP_SampleGrad:
  4716. case IntrinsicOp::MOP_SampleLevel: {
  4717. ArBasicKind kind = GetTypeElementKind(objectElement);
  4718. UINT uBits = GET_BPROP_BITS(kind);
  4719. return IS_BASIC_FLOAT(kind) && uBits != BPROP_BITS64;
  4720. } break;
  4721. default:
  4722. return true;
  4723. }
  4724. }
  4725. _Use_decl_annotations_
  4726. bool HLSLExternalSource::MatchArguments(
  4727. const HLSL_INTRINSIC* pIntrinsic,
  4728. QualType objectElement,
  4729. QualType functionTemplateTypeArg,
  4730. ArrayRef<Expr *> Args,
  4731. std::vector<QualType> *argTypesVector)
  4732. {
  4733. DXASSERT_NOMSG(pIntrinsic != nullptr);
  4734. DXASSERT_NOMSG(argTypesVector != nullptr);
  4735. std::vector<QualType> &argTypes = *argTypesVector;
  4736. argTypes.clear();
  4737. argTypes.resize(1 + Args.size()); // +1 for return type
  4738. const bool isVariadic = IsVariadicIntrinsicFunction(pIntrinsic);
  4739. static const UINT UnusedSize = 0xFF;
  4740. static const BYTE MaxIntrinsicArgs = g_MaxIntrinsicParamCount + 1;
  4741. #define CAB(_) { if (!(_)) return false; }
  4742. ArTypeObjectKind Template[MaxIntrinsicArgs]; // Template type for each argument, AR_TOBJ_UNKNOWN if unspecified.
  4743. ArBasicKind ComponentType[MaxIntrinsicArgs]; // Component type for each argument, AR_BASIC_UNKNOWN if unspecified.
  4744. UINT uSpecialSize[IA_SPECIAL_SLOTS]; // row/col matching types, UNUSED_INDEX32 if unspecified.
  4745. // Reset infos
  4746. std::fill(Template, Template + _countof(Template), AR_TOBJ_UNKNOWN);
  4747. std::fill(ComponentType, ComponentType + _countof(ComponentType), AR_BASIC_UNKNOWN);
  4748. std::fill(uSpecialSize, uSpecialSize + _countof(uSpecialSize), UnusedSize);
  4749. const unsigned retArgIdx = 0;
  4750. unsigned retTypeIdx = pIntrinsic->pArgs[retArgIdx].uComponentTypeId;
  4751. // Populate the template for each argument.
  4752. ArrayRef<Expr*>::iterator iterArg = Args.begin();
  4753. ArrayRef<Expr*>::iterator end = Args.end();
  4754. unsigned int iArg = 1;
  4755. for (; iterArg != end; ++iterArg) {
  4756. Expr* pCallArg = *iterArg;
  4757. // If vararg is reached, we can break out of this loop.
  4758. if(pIntrinsic->pArgs[iArg].uTemplateId == INTRIN_TEMPLATE_VARARGS)
  4759. break;
  4760. // Check bounds for non-variadic functions.
  4761. if (iArg >= _countof(Template) || iArg > pIntrinsic->uNumArgs) {
  4762. return false;
  4763. }
  4764. const HLSL_INTRINSIC_ARGUMENT *pIntrinsicArg;
  4765. pIntrinsicArg = &pIntrinsic->pArgs[iArg];
  4766. DXASSERT(isVariadic ||
  4767. pIntrinsicArg->uTemplateId != INTRIN_TEMPLATE_VARARGS,
  4768. "found vararg for non-variadic function");
  4769. QualType pType = pCallArg->getType();
  4770. ArTypeObjectKind TypeInfoShapeKind = GetTypeObjectKind(pType);
  4771. ArBasicKind TypeInfoEltKind = GetTypeElementKind(pType);
  4772. if (pIntrinsicArg->uLegalComponentTypes == LICOMPTYPE_RAYDESC) {
  4773. if (TypeInfoShapeKind == AR_TOBJ_COMPOUND) {
  4774. if (CXXRecordDecl *pDecl = pType->getAsCXXRecordDecl()) {
  4775. int index = FindObjectBasicKindIndex(pDecl);
  4776. if (index != -1 && AR_OBJECT_RAY_DESC == g_ArBasicKindsAsTypes[index]) {
  4777. ++iArg;
  4778. continue;
  4779. }
  4780. }
  4781. }
  4782. m_sema->Diag(pCallArg->getExprLoc(),
  4783. diag::err_hlsl_ray_desc_required);
  4784. return false;
  4785. }
  4786. if (pIntrinsicArg->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  4787. DXASSERT(objectElement.isNull(), "");
  4788. QualType Ty = pCallArg->getType();
  4789. // Must be user define type for LICOMPTYPE_USER_DEFINED_TYPE arg.
  4790. if (TypeInfoShapeKind != AR_TOBJ_COMPOUND) {
  4791. m_sema->Diag(pCallArg->getExprLoc(),
  4792. diag::err_hlsl_no_struct_user_defined_type);
  4793. return false;
  4794. }
  4795. objectElement = Ty;
  4796. ++iArg;
  4797. continue;
  4798. }
  4799. // If we are a type and templateID requires one, this isn't a match.
  4800. if (pIntrinsicArg->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE
  4801. || pIntrinsicArg->uTemplateId == INTRIN_TEMPLATE_FROM_FUNCTION) {
  4802. ++iArg;
  4803. continue;
  4804. }
  4805. if (TypeInfoEltKind == AR_BASIC_LITERAL_INT ||
  4806. TypeInfoEltKind == AR_BASIC_LITERAL_FLOAT) {
  4807. bool affectRetType =
  4808. (iArg != retArgIdx && retTypeIdx == pIntrinsicArg->uComponentTypeId);
  4809. // For literal arg which don't affect return type, find concrete type.
  4810. // For literal arg affect return type,
  4811. // TryEvalIntrinsic in CGHLSLMS.cpp will take care of cases
  4812. // where all argumentss are literal.
  4813. // CombineBasicTypes will cover the rest cases.
  4814. if (!affectRetType) {
  4815. TypeInfoEltKind = ConcreteLiteralType(
  4816. pCallArg, TypeInfoEltKind, pIntrinsicArg->uLegalComponentTypes, this);
  4817. }
  4818. }
  4819. UINT TypeInfoCols = 1;
  4820. UINT TypeInfoRows = 1;
  4821. switch (TypeInfoShapeKind) {
  4822. case AR_TOBJ_MATRIX:
  4823. GetRowsAndCols(pType, TypeInfoRows, TypeInfoCols);
  4824. break;
  4825. case AR_TOBJ_VECTOR:
  4826. TypeInfoCols = GetHLSLVecSize(pType);
  4827. break;
  4828. case AR_TOBJ_BASIC:
  4829. case AR_TOBJ_OBJECT:
  4830. case AR_TOBJ_STRING:
  4831. break;
  4832. default:
  4833. return false; // no struct, arrays or void
  4834. }
  4835. DXASSERT(
  4836. pIntrinsicArg->uTemplateId < MaxIntrinsicArgs,
  4837. "otherwise intrinsic table was modified and g_MaxIntrinsicParamCount was not updated (or uTemplateId is out of bounds)");
  4838. // Compare template
  4839. if ((AR_TOBJ_UNKNOWN == Template[pIntrinsicArg->uTemplateId]) ||
  4840. ((AR_TOBJ_SCALAR == Template[pIntrinsicArg->uTemplateId]) &&
  4841. (AR_TOBJ_VECTOR == TypeInfoShapeKind || AR_TOBJ_MATRIX == TypeInfoShapeKind))) {
  4842. Template[pIntrinsicArg->uTemplateId] = TypeInfoShapeKind;
  4843. }
  4844. else if (AR_TOBJ_SCALAR == TypeInfoShapeKind) {
  4845. if (AR_TOBJ_SCALAR != Template[pIntrinsicArg->uTemplateId] &&
  4846. AR_TOBJ_VECTOR != Template[pIntrinsicArg->uTemplateId] &&
  4847. AR_TOBJ_MATRIX != Template[pIntrinsicArg->uTemplateId]) {
  4848. return false;
  4849. }
  4850. }
  4851. else {
  4852. if (TypeInfoShapeKind != Template[pIntrinsicArg->uTemplateId]) {
  4853. return false;
  4854. }
  4855. }
  4856. DXASSERT(
  4857. pIntrinsicArg->uComponentTypeId < MaxIntrinsicArgs,
  4858. "otherwise intrinsic table was modified and MaxIntrinsicArgs was not updated (or uComponentTypeId is out of bounds)");
  4859. // Merge ComponentTypes
  4860. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsicArg->uComponentTypeId]) {
  4861. ComponentType[pIntrinsicArg->uComponentTypeId] = TypeInfoEltKind;
  4862. }
  4863. else {
  4864. if (!CombineBasicTypes(
  4865. ComponentType[pIntrinsicArg->uComponentTypeId],
  4866. TypeInfoEltKind,
  4867. &ComponentType[pIntrinsicArg->uComponentTypeId])) {
  4868. return false;
  4869. }
  4870. }
  4871. // Rows
  4872. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  4873. if (pIntrinsicArg->uRows >= IA_SPECIAL_BASE) {
  4874. UINT uSpecialId = pIntrinsicArg->uRows - IA_SPECIAL_BASE;
  4875. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4876. if (uSpecialSize[uSpecialId] > TypeInfoRows) {
  4877. uSpecialSize[uSpecialId] = TypeInfoRows;
  4878. }
  4879. }
  4880. else {
  4881. if (TypeInfoRows < pIntrinsicArg->uRows) {
  4882. return false;
  4883. }
  4884. }
  4885. }
  4886. // Columns
  4887. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  4888. if (pIntrinsicArg->uCols >= IA_SPECIAL_BASE) {
  4889. UINT uSpecialId = pIntrinsicArg->uCols - IA_SPECIAL_BASE;
  4890. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4891. if (uSpecialSize[uSpecialId] > TypeInfoCols) {
  4892. uSpecialSize[uSpecialId] = TypeInfoCols;
  4893. }
  4894. }
  4895. else {
  4896. if (TypeInfoCols < pIntrinsicArg->uCols) {
  4897. return false;
  4898. }
  4899. }
  4900. }
  4901. // Usage
  4902. if (pIntrinsicArg->qwUsage & AR_QUAL_OUT) {
  4903. if (pCallArg->getType().isConstQualified()) {
  4904. // Can't use a const type in an out or inout parameter.
  4905. return false;
  4906. }
  4907. }
  4908. iArg++;
  4909. }
  4910. DXASSERT(isVariadic || iterArg == end,
  4911. "otherwise the argument list wasn't fully processed");
  4912. // Default template and component type for return value
  4913. if (pIntrinsic->pArgs[0].qwUsage
  4914. && pIntrinsic->pArgs[0].uTemplateId != INTRIN_TEMPLATE_FROM_TYPE
  4915. && pIntrinsic->pArgs[0].uTemplateId != INTRIN_TEMPLATE_FROM_FUNCTION) {
  4916. CAB(pIntrinsic->pArgs[0].uTemplateId < MaxIntrinsicArgs);
  4917. if (AR_TOBJ_UNKNOWN == Template[pIntrinsic->pArgs[0].uTemplateId]) {
  4918. Template[pIntrinsic->pArgs[0].uTemplateId] =
  4919. g_LegalIntrinsicTemplates[pIntrinsic->pArgs[0].uLegalTemplates][0];
  4920. if (pIntrinsic->pArgs[0].uComponentTypeId != INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  4921. DXASSERT_NOMSG(pIntrinsic->pArgs[0].uComponentTypeId < MaxIntrinsicArgs);
  4922. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsic->pArgs[0].uComponentTypeId]) {
  4923. // half return type should map to float for min precision
  4924. if (pIntrinsic->pArgs[0].uLegalComponentTypes ==
  4925. LEGAL_INTRINSIC_COMPTYPES::LICOMPTYPE_FLOAT16 &&
  4926. getSema()->getLangOpts().UseMinPrecision) {
  4927. ComponentType[pIntrinsic->pArgs[0].uComponentTypeId] =
  4928. ArBasicKind::AR_BASIC_FLOAT32;
  4929. }
  4930. else {
  4931. ComponentType[pIntrinsic->pArgs[0].uComponentTypeId] =
  4932. g_LegalIntrinsicCompTypes[pIntrinsic->pArgs[0].uLegalComponentTypes][0];
  4933. }
  4934. }
  4935. }
  4936. }
  4937. }
  4938. // Make sure all template, component type, and texture type selections are valid.
  4939. for (size_t i = 0; i < Args.size() + 1; i++) {
  4940. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  4941. // If vararg is reached, we can break out of this loop.
  4942. if(pIntrinsic->pArgs[i].uTemplateId == INTRIN_TEMPLATE_VARARGS)
  4943. break;
  4944. // Check template.
  4945. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE
  4946. || pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_FUNCTION) {
  4947. continue; // Already verified that this is available.
  4948. }
  4949. if (pArgument->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  4950. continue;
  4951. }
  4952. const ArTypeObjectKind *pTT = g_LegalIntrinsicTemplates[pArgument->uLegalTemplates];
  4953. if (AR_TOBJ_UNKNOWN != Template[i]) {
  4954. if ((AR_TOBJ_SCALAR == Template[i]) && (AR_TOBJ_VECTOR == *pTT || AR_TOBJ_MATRIX == *pTT)) {
  4955. Template[i] = *pTT;
  4956. }
  4957. else if(AR_TOBJ_STRING == Template[i] && *pTT == AR_TOBJ_OBJECT) {
  4958. Template[i] = *pTT;
  4959. }
  4960. else {
  4961. while (AR_TOBJ_UNKNOWN != *pTT) {
  4962. if (Template[i] == *pTT)
  4963. break;
  4964. pTT++;
  4965. }
  4966. }
  4967. if (AR_TOBJ_UNKNOWN == *pTT)
  4968. return false;
  4969. }
  4970. else if (pTT) {
  4971. Template[i] = *pTT;
  4972. }
  4973. // Check component type.
  4974. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes];
  4975. if (AR_BASIC_UNKNOWN != ComponentType[i]) {
  4976. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4977. if (ComponentType[i] == *pCT)
  4978. break;
  4979. pCT++;
  4980. }
  4981. // has to be a strict match
  4982. if (*pCT == AR_BASIC_NOCAST)
  4983. return false;
  4984. // If it is an object, see if it can be cast to the first thing in the
  4985. // list, otherwise move on to next intrinsic.
  4986. if (AR_TOBJ_OBJECT == Template[i] && AR_BASIC_UNKNOWN == *pCT) {
  4987. if (!CombineObjectTypes(g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0], ComponentType[i], nullptr)) {
  4988. return false;
  4989. }
  4990. }
  4991. if (AR_BASIC_UNKNOWN == *pCT) {
  4992. ComponentType[i] = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0];
  4993. }
  4994. }
  4995. else if (pCT) {
  4996. ComponentType[i] = *pCT;
  4997. }
  4998. }
  4999. // Default to a void return type.
  5000. argTypes[0] = m_context->VoidTy;
  5001. // Default specials sizes.
  5002. for (UINT i = 0; i < IA_SPECIAL_SLOTS; i++) {
  5003. if (UnusedSize == uSpecialSize[i]) {
  5004. uSpecialSize[i] = 1;
  5005. }
  5006. }
  5007. // Populate argTypes.
  5008. for (size_t i = 0; i <= Args.size(); i++) {
  5009. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  5010. // If vararg is reached, we can break out of this loop.
  5011. if (pArgument->uTemplateId == INTRIN_TEMPLATE_VARARGS)
  5012. break;
  5013. if (!pArgument->qwUsage)
  5014. continue;
  5015. QualType pNewType;
  5016. unsigned int quals = 0; // qualifications for this argument
  5017. // If we have no type, set it to our input type (templatized)
  5018. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  5019. // Use the templated input type, but resize it if the
  5020. // intrinsic's rows/cols isn't 0
  5021. if (pArgument->uRows && pArgument->uCols) {
  5022. UINT uRows, uCols = 0;
  5023. // if type is overriden, use new type size, for
  5024. // now it only supports scalars
  5025. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  5026. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  5027. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  5028. uRows = uSpecialSize[uSpecialId];
  5029. }
  5030. else if (pArgument->uRows > 0) {
  5031. uRows = pArgument->uRows;
  5032. }
  5033. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  5034. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  5035. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  5036. uCols = uSpecialSize[uSpecialId];
  5037. }
  5038. else if (pArgument->uCols > 0) {
  5039. uCols = pArgument->uCols;
  5040. }
  5041. // 1x1 numeric outputs are always scalar.. since these
  5042. // are most flexible
  5043. if ((1 == uCols) && (1 == uRows)) {
  5044. pNewType = objectElement;
  5045. if (pNewType.isNull()) {
  5046. return false;
  5047. }
  5048. }
  5049. else {
  5050. // non-scalars unsupported right now since nothing
  5051. // uses it, would have to create either a type
  5052. // list for sub-structures or just resize the
  5053. // given type
  5054. // VH(E_NOTIMPL);
  5055. return false;
  5056. }
  5057. }
  5058. else {
  5059. DXASSERT_NOMSG(!pArgument->uRows && !pArgument->uCols);
  5060. if (objectElement.isNull()) {
  5061. return false;
  5062. }
  5063. pNewType = objectElement;
  5064. }
  5065. }
  5066. else if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_FUNCTION) {
  5067. if (functionTemplateTypeArg.isNull()) {
  5068. if (i == 0) {
  5069. // [RW]ByteAddressBuffer.Load, default to uint
  5070. pNewType = m_context->UnsignedIntTy;
  5071. }
  5072. else {
  5073. // [RW]ByteAddressBuffer.Store, default to argument type
  5074. pNewType = Args[i - 1]->getType().getNonReferenceType();
  5075. if (const BuiltinType *BuiltinTy = pNewType->getAs<BuiltinType>()) {
  5076. // For backcompat, ensure that Store(0, 42 or 42.0) matches a uint/float overload
  5077. // rather than a uint64_t/double one.
  5078. if (BuiltinTy->getKind() == BuiltinType::LitInt) {
  5079. pNewType = m_context->UnsignedIntTy;
  5080. } else if (BuiltinTy->getKind() == BuiltinType::LitFloat) {
  5081. pNewType = m_context->FloatTy;
  5082. }
  5083. }
  5084. }
  5085. }
  5086. else {
  5087. pNewType = functionTemplateTypeArg;
  5088. }
  5089. }
  5090. else if (pArgument->uLegalComponentTypes == LICOMPTYPE_USER_DEFINED_TYPE) {
  5091. if (objectElement.isNull()) {
  5092. return false;
  5093. }
  5094. pNewType = objectElement;
  5095. }
  5096. else if (pArgument->uLegalComponentTypes == LICOMPTYPE_TEXTURE2D
  5097. || pArgument->uLegalComponentTypes == LICOMPTYPE_TEXTURE2DARRAY) {
  5098. pNewType = Args[i - 1]->getType().getNonReferenceType();
  5099. }
  5100. else {
  5101. ArBasicKind pEltType;
  5102. // ComponentType, if the Id is special then it gets the
  5103. // component type from the first component of the type, if
  5104. // we need more (for the second component, e.g.), then we
  5105. // can use more specials, etc.
  5106. if (pArgument->uComponentTypeId == INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  5107. if (objectElement.isNull()) {
  5108. return false;
  5109. }
  5110. pEltType = GetTypeElementKind(objectElement);
  5111. if (!IsValidBasicKind(pEltType)) {
  5112. // This can happen with Texture2D<Struct> or other invalid declarations
  5113. return false;
  5114. }
  5115. }
  5116. else {
  5117. pEltType = ComponentType[pArgument->uComponentTypeId];
  5118. DXASSERT_VALIDBASICKIND(pEltType);
  5119. }
  5120. UINT uRows, uCols;
  5121. // Rows
  5122. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  5123. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  5124. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  5125. uRows = uSpecialSize[uSpecialId];
  5126. }
  5127. else {
  5128. uRows = pArgument->uRows;
  5129. }
  5130. // Cols
  5131. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  5132. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  5133. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  5134. uCols = uSpecialSize[uSpecialId];
  5135. }
  5136. else {
  5137. uCols = pArgument->uCols;
  5138. }
  5139. // Verify that the final results are in bounds.
  5140. CAB(uCols > 0 && uCols <= MaxVectorSize && uRows > 0 && uRows <= MaxVectorSize);
  5141. // Const
  5142. UINT64 qwQual = pArgument->qwUsage & (AR_QUAL_ROWMAJOR | AR_QUAL_COLMAJOR);
  5143. if ((0 == i) || !(pArgument->qwUsage & AR_QUAL_OUT))
  5144. qwQual |= AR_QUAL_CONST;
  5145. DXASSERT_VALIDBASICKIND(pEltType);
  5146. pNewType = NewSimpleAggregateType(Template[pArgument->uTemplateId], pEltType, qwQual, uRows, uCols);
  5147. }
  5148. DXASSERT(!pNewType.isNull(), "otherwise there's a branch in this function that fails to assign this");
  5149. argTypes[i] = QualType(pNewType.getTypePtr(), quals);
  5150. // TODO: support out modifier
  5151. //if (pArgument->qwUsage & AR_QUAL_OUT) {
  5152. // argTypes[i] = m_context->getLValueReferenceType(argTypes[i].withConst());
  5153. //}
  5154. }
  5155. // For variadic functions, we need to add the additional arguments here.
  5156. if(isVariadic) {
  5157. for (; iArg <= Args.size(); ++iArg) {
  5158. argTypes[iArg] = Args[iArg - 1]->getType().getNonReferenceType();
  5159. }
  5160. } else {
  5161. DXASSERT(iArg == pIntrinsic->uNumArgs,
  5162. "In the absence of varargs, a successful match would indicate we "
  5163. "have as many arguments and types as the intrinsic template");
  5164. }
  5165. return true;
  5166. #undef CAB
  5167. }
  5168. _Use_decl_annotations_
  5169. HLSLExternalSource::FindStructBasicTypeResult
  5170. HLSLExternalSource::FindStructBasicType(DeclContext* functionDeclContext)
  5171. {
  5172. DXASSERT_NOMSG(functionDeclContext != nullptr);
  5173. // functionDeclContext may be a specialization of a template, such as AppendBuffer<MY_STRUCT>, or it
  5174. // may be a simple class, such as RWByteAddressBuffer.
  5175. const CXXRecordDecl* recordDecl = GetRecordDeclForBuiltInOrStruct(functionDeclContext);
  5176. // We save the caller from filtering out other types of context (like the translation unit itself).
  5177. if (recordDecl != nullptr)
  5178. {
  5179. int index = FindObjectBasicKindIndex(recordDecl);
  5180. if (index != -1) {
  5181. ArBasicKind kind = g_ArBasicKindsAsTypes[index];
  5182. return HLSLExternalSource::FindStructBasicTypeResult(kind, index);
  5183. }
  5184. }
  5185. return HLSLExternalSource::FindStructBasicTypeResult(AR_BASIC_UNKNOWN, 0);
  5186. }
  5187. _Use_decl_annotations_
  5188. void HLSLExternalSource::FindIntrinsicTable(DeclContext* functionDeclContext, const char** name, const HLSL_INTRINSIC** intrinsics, size_t* intrinsicCount)
  5189. {
  5190. DXASSERT_NOMSG(functionDeclContext != nullptr);
  5191. DXASSERT_NOMSG(name != nullptr);
  5192. DXASSERT_NOMSG(intrinsics != nullptr);
  5193. DXASSERT_NOMSG(intrinsicCount != nullptr);
  5194. *intrinsics = nullptr;
  5195. *intrinsicCount = 0;
  5196. *name = nullptr;
  5197. HLSLExternalSource::FindStructBasicTypeResult lookup = FindStructBasicType(functionDeclContext);
  5198. if (lookup.Found()) {
  5199. GetIntrinsicMethods(lookup.Kind, intrinsics, intrinsicCount);
  5200. *name = g_ArBasicTypeNames[lookup.Kind];
  5201. }
  5202. }
  5203. static bool BinaryOperatorKindIsArithmetic(BinaryOperatorKind Opc)
  5204. {
  5205. return
  5206. // Arithmetic operators.
  5207. Opc == BinaryOperatorKind::BO_Add ||
  5208. Opc == BinaryOperatorKind::BO_AddAssign ||
  5209. Opc == BinaryOperatorKind::BO_Sub ||
  5210. Opc == BinaryOperatorKind::BO_SubAssign ||
  5211. Opc == BinaryOperatorKind::BO_Rem ||
  5212. Opc == BinaryOperatorKind::BO_RemAssign ||
  5213. Opc == BinaryOperatorKind::BO_Div ||
  5214. Opc == BinaryOperatorKind::BO_DivAssign ||
  5215. Opc == BinaryOperatorKind::BO_Mul ||
  5216. Opc == BinaryOperatorKind::BO_MulAssign;
  5217. }
  5218. static bool BinaryOperatorKindIsCompoundAssignment(BinaryOperatorKind Opc)
  5219. {
  5220. return
  5221. // Arithmetic-and-assignment operators.
  5222. Opc == BinaryOperatorKind::BO_AddAssign ||
  5223. Opc == BinaryOperatorKind::BO_SubAssign ||
  5224. Opc == BinaryOperatorKind::BO_RemAssign ||
  5225. Opc == BinaryOperatorKind::BO_DivAssign ||
  5226. Opc == BinaryOperatorKind::BO_MulAssign ||
  5227. // Bitwise-and-assignment operators.
  5228. Opc == BinaryOperatorKind::BO_ShlAssign ||
  5229. Opc == BinaryOperatorKind::BO_ShrAssign ||
  5230. Opc == BinaryOperatorKind::BO_AndAssign ||
  5231. Opc == BinaryOperatorKind::BO_OrAssign ||
  5232. Opc == BinaryOperatorKind::BO_XorAssign;
  5233. }
  5234. static bool BinaryOperatorKindIsCompoundAssignmentForBool(BinaryOperatorKind Opc)
  5235. {
  5236. return
  5237. Opc == BinaryOperatorKind::BO_AndAssign ||
  5238. Opc == BinaryOperatorKind::BO_OrAssign ||
  5239. Opc == BinaryOperatorKind::BO_XorAssign;
  5240. }
  5241. static bool BinaryOperatorKindIsBitwise(BinaryOperatorKind Opc)
  5242. {
  5243. return
  5244. Opc == BinaryOperatorKind::BO_Shl ||
  5245. Opc == BinaryOperatorKind::BO_ShlAssign ||
  5246. Opc == BinaryOperatorKind::BO_Shr ||
  5247. Opc == BinaryOperatorKind::BO_ShrAssign ||
  5248. Opc == BinaryOperatorKind::BO_And ||
  5249. Opc == BinaryOperatorKind::BO_AndAssign ||
  5250. Opc == BinaryOperatorKind::BO_Or ||
  5251. Opc == BinaryOperatorKind::BO_OrAssign ||
  5252. Opc == BinaryOperatorKind::BO_Xor ||
  5253. Opc == BinaryOperatorKind::BO_XorAssign;
  5254. }
  5255. static bool BinaryOperatorKindIsBitwiseShift(BinaryOperatorKind Opc)
  5256. {
  5257. return
  5258. Opc == BinaryOperatorKind::BO_Shl ||
  5259. Opc == BinaryOperatorKind::BO_ShlAssign ||
  5260. Opc == BinaryOperatorKind::BO_Shr ||
  5261. Opc == BinaryOperatorKind::BO_ShrAssign;
  5262. }
  5263. static bool BinaryOperatorKindIsEqualComparison(BinaryOperatorKind Opc)
  5264. {
  5265. return
  5266. Opc == BinaryOperatorKind::BO_EQ ||
  5267. Opc == BinaryOperatorKind::BO_NE;
  5268. }
  5269. static bool BinaryOperatorKindIsOrderComparison(BinaryOperatorKind Opc)
  5270. {
  5271. return
  5272. Opc == BinaryOperatorKind::BO_LT ||
  5273. Opc == BinaryOperatorKind::BO_GT ||
  5274. Opc == BinaryOperatorKind::BO_LE ||
  5275. Opc == BinaryOperatorKind::BO_GE;
  5276. }
  5277. static bool BinaryOperatorKindIsComparison(BinaryOperatorKind Opc)
  5278. {
  5279. return BinaryOperatorKindIsEqualComparison(Opc) || BinaryOperatorKindIsOrderComparison(Opc);
  5280. }
  5281. static bool BinaryOperatorKindIsLogical(BinaryOperatorKind Opc)
  5282. {
  5283. return
  5284. Opc == BinaryOperatorKind::BO_LAnd ||
  5285. Opc == BinaryOperatorKind::BO_LOr;
  5286. }
  5287. static bool BinaryOperatorKindRequiresNumeric(BinaryOperatorKind Opc)
  5288. {
  5289. return
  5290. BinaryOperatorKindIsArithmetic(Opc) ||
  5291. BinaryOperatorKindIsOrderComparison(Opc) ||
  5292. BinaryOperatorKindIsLogical(Opc);
  5293. }
  5294. static bool BinaryOperatorKindRequiresIntegrals(BinaryOperatorKind Opc)
  5295. {
  5296. return BinaryOperatorKindIsBitwise(Opc);
  5297. }
  5298. static bool BinaryOperatorKindRequiresBoolAsNumeric(BinaryOperatorKind Opc)
  5299. {
  5300. return
  5301. BinaryOperatorKindIsBitwise(Opc) ||
  5302. BinaryOperatorKindIsArithmetic(Opc);
  5303. }
  5304. static bool UnaryOperatorKindRequiresIntegrals(UnaryOperatorKind Opc)
  5305. {
  5306. return Opc == UnaryOperatorKind::UO_Not;
  5307. }
  5308. static bool UnaryOperatorKindRequiresNumerics(UnaryOperatorKind Opc)
  5309. {
  5310. return
  5311. Opc == UnaryOperatorKind::UO_LNot ||
  5312. Opc == UnaryOperatorKind::UO_Plus ||
  5313. Opc == UnaryOperatorKind::UO_Minus ||
  5314. // The omission in fxc caused objects and structs to accept this.
  5315. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  5316. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  5317. }
  5318. static bool UnaryOperatorKindRequiresModifiableValue(UnaryOperatorKind Opc)
  5319. {
  5320. return
  5321. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  5322. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  5323. }
  5324. static bool UnaryOperatorKindRequiresBoolAsNumeric(UnaryOperatorKind Opc)
  5325. {
  5326. return
  5327. Opc == UnaryOperatorKind::UO_Not ||
  5328. Opc == UnaryOperatorKind::UO_Plus ||
  5329. Opc == UnaryOperatorKind::UO_Minus;
  5330. }
  5331. static bool UnaryOperatorKindDisallowsBool(UnaryOperatorKind Opc)
  5332. {
  5333. return
  5334. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  5335. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  5336. }
  5337. static bool IsIncrementOp(UnaryOperatorKind Opc) {
  5338. return Opc == UnaryOperatorKind::UO_PreInc || Opc == UnaryOperatorKind::UO_PostInc;
  5339. }
  5340. /// <summary>
  5341. /// Checks whether the specified AR_TOBJ* value is a primitive or aggregate of primitive elements
  5342. /// (as opposed to a built-in object like a sampler or texture, or a void type).
  5343. /// </summary>
  5344. static bool IsObjectKindPrimitiveAggregate(ArTypeObjectKind value)
  5345. {
  5346. return
  5347. value == AR_TOBJ_BASIC ||
  5348. value == AR_TOBJ_MATRIX ||
  5349. value == AR_TOBJ_VECTOR;
  5350. }
  5351. static bool IsBasicKindIntegral(ArBasicKind value)
  5352. {
  5353. return IS_BASIC_AINT(value) || IS_BASIC_BOOL(value);
  5354. }
  5355. static bool IsBasicKindIntMinPrecision(ArBasicKind kind)
  5356. {
  5357. return IS_BASIC_SINT(kind) && IS_BASIC_MIN_PRECISION(kind);
  5358. }
  5359. static bool IsBasicKindNumeric(ArBasicKind value)
  5360. {
  5361. return GetBasicKindProps(value) & BPROP_NUMERIC;
  5362. }
  5363. ExprResult HLSLExternalSource::PromoteToIntIfBool(ExprResult& E)
  5364. {
  5365. // An invalid expression is pass-through at this point.
  5366. if (E.isInvalid())
  5367. {
  5368. return E;
  5369. }
  5370. QualType qt = E.get()->getType();
  5371. ArBasicKind elementKind = this->GetTypeElementKind(qt);
  5372. if (elementKind != AR_BASIC_BOOL)
  5373. {
  5374. return E;
  5375. }
  5376. // Construct a scalar/vector/matrix type with the same shape as E.
  5377. ArTypeObjectKind objectKind = this->GetTypeObjectKind(qt);
  5378. QualType targetType;
  5379. UINT colCount, rowCount;
  5380. GetRowsAndColsForAny(qt, rowCount, colCount);
  5381. targetType = NewSimpleAggregateType(objectKind, AR_BASIC_INT32, 0, rowCount, colCount)->getCanonicalTypeInternal();
  5382. if (E.get()->isLValue()) {
  5383. E = m_sema->DefaultLvalueConversion(E.get()).get();
  5384. }
  5385. switch (objectKind)
  5386. {
  5387. case AR_TOBJ_SCALAR:
  5388. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  5389. case AR_TOBJ_ARRAY:
  5390. case AR_TOBJ_VECTOR:
  5391. case AR_TOBJ_MATRIX:
  5392. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLCC_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  5393. default:
  5394. DXASSERT(false, "unsupported objectKind for PromoteToIntIfBool");
  5395. }
  5396. return E;
  5397. }
  5398. _Use_decl_annotations_
  5399. void HLSLExternalSource::CollectInfo(QualType type, ArTypeInfo* pTypeInfo)
  5400. {
  5401. DXASSERT_NOMSG(pTypeInfo != nullptr);
  5402. DXASSERT_NOMSG(!type.isNull());
  5403. memset(pTypeInfo, 0, sizeof(*pTypeInfo));
  5404. // TODO: Get* functions used here add up to a bunch of redundant code.
  5405. // Try to inline that here, making it cheaper to use this function
  5406. // when retrieving multiple properties.
  5407. pTypeInfo->ObjKind = GetTypeElementKind(type);
  5408. pTypeInfo->EltKind = pTypeInfo->ObjKind;
  5409. pTypeInfo->ShapeKind = GetTypeObjectKind(type);
  5410. GetRowsAndColsForAny(type, pTypeInfo->uRows, pTypeInfo->uCols);
  5411. pTypeInfo->uTotalElts = pTypeInfo->uRows * pTypeInfo->uCols;
  5412. }
  5413. // Highest possible score (i.e., worst possible score).
  5414. static const UINT64 SCORE_MAX = 0xFFFFFFFFFFFFFFFF;
  5415. // Leave the first two score bits to handle higher-level
  5416. // variations like target type.
  5417. #define SCORE_MIN_SHIFT 2
  5418. // Space out scores to allow up to 128 parameters to
  5419. // vary between score sets spill into each other.
  5420. #define SCORE_PARAM_SHIFT 7
  5421. unsigned HLSLExternalSource::GetNumElements(QualType anyType) {
  5422. if (anyType.isNull()) {
  5423. return 0;
  5424. }
  5425. anyType = GetStructuralForm(anyType);
  5426. ArTypeObjectKind kind = GetTypeObjectKind(anyType);
  5427. switch (kind) {
  5428. case AR_TOBJ_BASIC:
  5429. case AR_TOBJ_OBJECT:
  5430. case AR_TOBJ_STRING:
  5431. return 1;
  5432. case AR_TOBJ_COMPOUND: {
  5433. // TODO: consider caching this value for perf
  5434. unsigned total = 0;
  5435. const RecordType *recordType = anyType->getAs<RecordType>();
  5436. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  5437. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  5438. while (fi != fend) {
  5439. total += GetNumElements(fi->getType());
  5440. ++fi;
  5441. }
  5442. return total;
  5443. }
  5444. case AR_TOBJ_ARRAY:
  5445. case AR_TOBJ_MATRIX:
  5446. case AR_TOBJ_VECTOR:
  5447. return GetElementCount(anyType);
  5448. default:
  5449. DXASSERT(kind == AR_TOBJ_VOID,
  5450. "otherwise the type cannot be classified or is not supported");
  5451. return 0;
  5452. }
  5453. }
  5454. unsigned HLSLExternalSource::GetNumBasicElements(QualType anyType) {
  5455. if (anyType.isNull()) {
  5456. return 0;
  5457. }
  5458. anyType = GetStructuralForm(anyType);
  5459. ArTypeObjectKind kind = GetTypeObjectKind(anyType);
  5460. switch (kind) {
  5461. case AR_TOBJ_BASIC:
  5462. case AR_TOBJ_OBJECT:
  5463. case AR_TOBJ_STRING:
  5464. return 1;
  5465. case AR_TOBJ_COMPOUND: {
  5466. // TODO: consider caching this value for perf
  5467. unsigned total = 0;
  5468. const RecordType *recordType = anyType->getAs<RecordType>();
  5469. RecordDecl * RD = recordType->getDecl();
  5470. // Take care base.
  5471. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  5472. if (CXXRD->getNumBases()) {
  5473. for (const auto &I : CXXRD->bases()) {
  5474. const CXXRecordDecl *BaseDecl =
  5475. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  5476. if (BaseDecl->field_empty())
  5477. continue;
  5478. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  5479. total += GetNumBasicElements(parentTy);
  5480. }
  5481. }
  5482. }
  5483. RecordDecl::field_iterator fi = RD->field_begin();
  5484. RecordDecl::field_iterator fend = RD->field_end();
  5485. while (fi != fend) {
  5486. total += GetNumBasicElements(fi->getType());
  5487. ++fi;
  5488. }
  5489. return total;
  5490. }
  5491. case AR_TOBJ_ARRAY: {
  5492. unsigned arraySize = GetElementCount(anyType);
  5493. unsigned eltSize = GetNumBasicElements(
  5494. QualType(anyType->getArrayElementTypeNoTypeQual(), 0));
  5495. return arraySize * eltSize;
  5496. }
  5497. case AR_TOBJ_MATRIX:
  5498. case AR_TOBJ_VECTOR:
  5499. return GetElementCount(anyType);
  5500. default:
  5501. DXASSERT(kind == AR_TOBJ_VOID,
  5502. "otherwise the type cannot be classified or is not supported");
  5503. return 0;
  5504. }
  5505. }
  5506. unsigned HLSLExternalSource::GetNumConvertCheckElts(QualType leftType,
  5507. unsigned leftSize,
  5508. QualType rightType,
  5509. unsigned rightSize) {
  5510. // We can convert from a larger type to a smaller
  5511. // but not a smaller type to a larger so default
  5512. // to just comparing the destination size.
  5513. unsigned uElts = leftSize;
  5514. leftType = GetStructuralForm(leftType);
  5515. rightType = GetStructuralForm(rightType);
  5516. if (leftType->isArrayType() && rightType->isArrayType()) {
  5517. //
  5518. // If we're comparing arrays we don't
  5519. // need to compare every element of
  5520. // the arrays since all elements
  5521. // will have the same type.
  5522. // We only need to compare enough
  5523. // elements that we've tried every
  5524. // possible mix of dst and src elements.
  5525. //
  5526. // TODO: handle multidimensional arrays and arrays of arrays
  5527. QualType pDstElt = leftType->getAsArrayTypeUnsafe()->getElementType();
  5528. unsigned uDstEltSize = GetNumElements(pDstElt);
  5529. QualType pSrcElt = rightType->getAsArrayTypeUnsafe()->getElementType();
  5530. unsigned uSrcEltSize = GetNumElements(pSrcElt);
  5531. if (uDstEltSize == uSrcEltSize) {
  5532. uElts = uDstEltSize;
  5533. } else if (uDstEltSize > uSrcEltSize) {
  5534. // If one size is not an even multiple of the other we need to let the
  5535. // full compare run in order to try all alignments.
  5536. if (uSrcEltSize && (uDstEltSize % uSrcEltSize) == 0) {
  5537. uElts = uDstEltSize;
  5538. }
  5539. } else if (uDstEltSize && (uSrcEltSize % uDstEltSize) == 0) {
  5540. uElts = uSrcEltSize;
  5541. }
  5542. }
  5543. return uElts;
  5544. }
  5545. QualType HLSLExternalSource::GetNthElementType(QualType type, unsigned index) {
  5546. if (type.isNull()) {
  5547. return type;
  5548. }
  5549. ArTypeObjectKind kind = GetTypeObjectKind(type);
  5550. switch (kind) {
  5551. case AR_TOBJ_BASIC:
  5552. case AR_TOBJ_OBJECT:
  5553. case AR_TOBJ_STRING:
  5554. return (index == 0) ? type : QualType();
  5555. case AR_TOBJ_COMPOUND: {
  5556. // TODO: consider caching this value for perf
  5557. const RecordType *recordType = type->getAsStructureType();
  5558. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  5559. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  5560. while (fi != fend) {
  5561. if (!fi->getType().isNull()) {
  5562. unsigned subElements = GetNumElements(fi->getType());
  5563. if (index < subElements) {
  5564. return GetNthElementType(fi->getType(), index);
  5565. } else {
  5566. index -= subElements;
  5567. }
  5568. }
  5569. ++fi;
  5570. }
  5571. return QualType();
  5572. }
  5573. case AR_TOBJ_ARRAY: {
  5574. unsigned arraySize;
  5575. QualType elementType;
  5576. unsigned elementCount;
  5577. elementType = type.getNonReferenceType()->getAsArrayTypeUnsafe()->getElementType();
  5578. elementCount = GetElementCount(elementType);
  5579. if (index < elementCount) {
  5580. return GetNthElementType(elementType, index);
  5581. }
  5582. arraySize = GetArraySize(type);
  5583. if (index >= arraySize * elementCount) {
  5584. return QualType();
  5585. }
  5586. return GetNthElementType(elementType, index % elementCount);
  5587. }
  5588. case AR_TOBJ_MATRIX:
  5589. case AR_TOBJ_VECTOR:
  5590. return (index < GetElementCount(type)) ? GetMatrixOrVectorElementType(type)
  5591. : QualType();
  5592. default:
  5593. DXASSERT(kind == AR_TOBJ_VOID,
  5594. "otherwise the type cannot be classified or is not supported");
  5595. return QualType();
  5596. }
  5597. }
  5598. bool HLSLExternalSource::IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind) {
  5599. // Eliminate exact matches first, then check for promotions.
  5600. if (leftKind == rightKind) {
  5601. return false;
  5602. }
  5603. switch (rightKind) {
  5604. case AR_BASIC_FLOAT16:
  5605. switch (leftKind) {
  5606. case AR_BASIC_FLOAT32:
  5607. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  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_PARTIAL_PRECISION:
  5615. switch (leftKind) {
  5616. case AR_BASIC_FLOAT32:
  5617. case AR_BASIC_FLOAT64:
  5618. return true;
  5619. default:
  5620. return false; // No other type is a promotion.
  5621. }
  5622. break;
  5623. case AR_BASIC_FLOAT32:
  5624. switch (leftKind) {
  5625. case AR_BASIC_FLOAT64:
  5626. return true;
  5627. default:
  5628. return false; // No other type is a promotion.
  5629. }
  5630. break;
  5631. case AR_BASIC_MIN10FLOAT:
  5632. switch (leftKind) {
  5633. case AR_BASIC_MIN16FLOAT:
  5634. case AR_BASIC_FLOAT16:
  5635. case AR_BASIC_FLOAT32:
  5636. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5637. case AR_BASIC_FLOAT64:
  5638. return true;
  5639. default:
  5640. return false; // No other type is a promotion.
  5641. }
  5642. break;
  5643. case AR_BASIC_MIN16FLOAT:
  5644. switch (leftKind) {
  5645. case AR_BASIC_FLOAT16:
  5646. case AR_BASIC_FLOAT32:
  5647. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5648. case AR_BASIC_FLOAT64:
  5649. return true;
  5650. default:
  5651. return false; // No other type is a promotion.
  5652. }
  5653. break;
  5654. case AR_BASIC_INT8:
  5655. case AR_BASIC_UINT8:
  5656. // For backwards compat we consider signed/unsigned the same.
  5657. switch (leftKind) {
  5658. case AR_BASIC_INT16:
  5659. case AR_BASIC_INT32:
  5660. case AR_BASIC_INT64:
  5661. case AR_BASIC_UINT16:
  5662. case AR_BASIC_UINT32:
  5663. case AR_BASIC_UINT64:
  5664. return true;
  5665. default:
  5666. return false; // No other type is a promotion.
  5667. }
  5668. break;
  5669. case AR_BASIC_INT16:
  5670. case AR_BASIC_UINT16:
  5671. // For backwards compat we consider signed/unsigned the same.
  5672. switch (leftKind) {
  5673. case AR_BASIC_INT32:
  5674. case AR_BASIC_INT64:
  5675. case AR_BASIC_UINT32:
  5676. case AR_BASIC_UINT64:
  5677. return true;
  5678. default:
  5679. return false; // No other type is a promotion.
  5680. }
  5681. break;
  5682. case AR_BASIC_INT32:
  5683. case AR_BASIC_UINT32:
  5684. // For backwards compat we consider signed/unsigned the same.
  5685. switch (leftKind) {
  5686. case AR_BASIC_INT64:
  5687. case AR_BASIC_UINT64:
  5688. return true;
  5689. default:
  5690. return false; // No other type is a promotion.
  5691. }
  5692. break;
  5693. case AR_BASIC_MIN12INT:
  5694. switch (leftKind) {
  5695. case AR_BASIC_MIN16INT:
  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_MIN16INT:
  5704. switch (leftKind) {
  5705. case AR_BASIC_INT32:
  5706. case AR_BASIC_INT64:
  5707. return true;
  5708. default:
  5709. return false; // No other type is a promotion.
  5710. }
  5711. break;
  5712. case AR_BASIC_MIN16UINT:
  5713. switch (leftKind) {
  5714. case AR_BASIC_UINT32:
  5715. case AR_BASIC_UINT64:
  5716. return true;
  5717. default:
  5718. return false; // No other type is a promotion.
  5719. }
  5720. break;
  5721. }
  5722. return false;
  5723. }
  5724. bool HLSLExternalSource::IsCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  5725. // Eliminate exact matches first, then check for casts.
  5726. if (leftKind == rightKind) {
  5727. return false;
  5728. }
  5729. //
  5730. // All minimum-bits types are only considered matches of themselves
  5731. // and thus are not in this table.
  5732. //
  5733. switch (leftKind) {
  5734. case AR_BASIC_LITERAL_INT:
  5735. switch (rightKind) {
  5736. case AR_BASIC_INT8:
  5737. case AR_BASIC_INT16:
  5738. case AR_BASIC_INT32:
  5739. case AR_BASIC_INT64:
  5740. case AR_BASIC_UINT8:
  5741. case AR_BASIC_UINT16:
  5742. case AR_BASIC_UINT32:
  5743. case AR_BASIC_UINT64:
  5744. return false;
  5745. default:
  5746. break; // No other valid cast types
  5747. }
  5748. break;
  5749. case AR_BASIC_INT8:
  5750. switch (rightKind) {
  5751. // For backwards compat we consider signed/unsigned the same.
  5752. case AR_BASIC_LITERAL_INT:
  5753. case AR_BASIC_UINT8:
  5754. return false;
  5755. default:
  5756. break; // No other valid cast types
  5757. }
  5758. break;
  5759. case AR_BASIC_INT16:
  5760. switch (rightKind) {
  5761. // For backwards compat we consider signed/unsigned the same.
  5762. case AR_BASIC_LITERAL_INT:
  5763. case AR_BASIC_UINT16:
  5764. return false;
  5765. default:
  5766. break; // No other valid cast types
  5767. }
  5768. break;
  5769. case AR_BASIC_INT32:
  5770. switch (rightKind) {
  5771. // For backwards compat we consider signed/unsigned the same.
  5772. case AR_BASIC_LITERAL_INT:
  5773. case AR_BASIC_UINT32:
  5774. return false;
  5775. default:
  5776. break; // No other valid cast types.
  5777. }
  5778. break;
  5779. case AR_BASIC_INT64:
  5780. switch (rightKind) {
  5781. // For backwards compat we consider signed/unsigned the same.
  5782. case AR_BASIC_LITERAL_INT:
  5783. case AR_BASIC_UINT64:
  5784. return false;
  5785. default:
  5786. break; // No other valid cast types.
  5787. }
  5788. break;
  5789. case AR_BASIC_UINT8:
  5790. switch (rightKind) {
  5791. // For backwards compat we consider signed/unsigned the same.
  5792. case AR_BASIC_LITERAL_INT:
  5793. case AR_BASIC_INT8:
  5794. return false;
  5795. default:
  5796. break; // No other valid cast types.
  5797. }
  5798. break;
  5799. case AR_BASIC_UINT16:
  5800. switch (rightKind) {
  5801. // For backwards compat we consider signed/unsigned the same.
  5802. case AR_BASIC_LITERAL_INT:
  5803. case AR_BASIC_INT16:
  5804. return false;
  5805. default:
  5806. break; // No other valid cast types.
  5807. }
  5808. break;
  5809. case AR_BASIC_UINT32:
  5810. switch (rightKind) {
  5811. // For backwards compat we consider signed/unsigned the same.
  5812. case AR_BASIC_LITERAL_INT:
  5813. case AR_BASIC_INT32:
  5814. return false;
  5815. default:
  5816. break; // No other valid cast types.
  5817. }
  5818. break;
  5819. case AR_BASIC_UINT64:
  5820. switch (rightKind) {
  5821. // For backwards compat we consider signed/unsigned the same.
  5822. case AR_BASIC_LITERAL_INT:
  5823. case AR_BASIC_INT64:
  5824. return false;
  5825. default:
  5826. break; // No other valid cast types.
  5827. }
  5828. break;
  5829. case AR_BASIC_LITERAL_FLOAT:
  5830. switch (rightKind) {
  5831. case AR_BASIC_LITERAL_FLOAT:
  5832. case AR_BASIC_FLOAT16:
  5833. case AR_BASIC_FLOAT32:
  5834. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5835. case AR_BASIC_FLOAT64:
  5836. return false;
  5837. default:
  5838. break; // No other valid cast types.
  5839. }
  5840. break;
  5841. case AR_BASIC_FLOAT16:
  5842. switch (rightKind) {
  5843. case AR_BASIC_LITERAL_FLOAT:
  5844. return false;
  5845. default:
  5846. break; // No other valid cast types.
  5847. }
  5848. break;
  5849. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5850. switch (rightKind) {
  5851. case AR_BASIC_LITERAL_FLOAT:
  5852. return false;
  5853. default:
  5854. break; // No other valid cast types.
  5855. }
  5856. break;
  5857. case AR_BASIC_FLOAT32:
  5858. switch (rightKind) {
  5859. case AR_BASIC_LITERAL_FLOAT:
  5860. return false;
  5861. default:
  5862. break; // No other valid cast types.
  5863. }
  5864. break;
  5865. case AR_BASIC_FLOAT64:
  5866. switch (rightKind) {
  5867. case AR_BASIC_LITERAL_FLOAT:
  5868. return false;
  5869. default:
  5870. break; // No other valid cast types.
  5871. }
  5872. break;
  5873. default:
  5874. break; // No other relevant targets.
  5875. }
  5876. return true;
  5877. }
  5878. bool HLSLExternalSource::IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  5879. // Eliminate exact matches first, then check for casts.
  5880. if (leftKind == rightKind) {
  5881. return false;
  5882. }
  5883. //
  5884. // All minimum-bits types are only considered matches of themselves
  5885. // and thus are not in this table.
  5886. //
  5887. switch (leftKind) {
  5888. case AR_BASIC_LITERAL_INT:
  5889. switch (rightKind) {
  5890. case AR_BASIC_INT8:
  5891. case AR_BASIC_INT16:
  5892. case AR_BASIC_INT32:
  5893. case AR_BASIC_INT64:
  5894. case AR_BASIC_UINT8:
  5895. case AR_BASIC_UINT16:
  5896. case AR_BASIC_UINT32:
  5897. case AR_BASIC_UINT64:
  5898. return false;
  5899. default:
  5900. break; // No other valid conversions
  5901. }
  5902. break;
  5903. case AR_BASIC_INT8:
  5904. case AR_BASIC_INT16:
  5905. case AR_BASIC_INT32:
  5906. case AR_BASIC_INT64:
  5907. case AR_BASIC_UINT8:
  5908. case AR_BASIC_UINT16:
  5909. case AR_BASIC_UINT32:
  5910. case AR_BASIC_UINT64:
  5911. switch (rightKind) {
  5912. case AR_BASIC_LITERAL_INT:
  5913. return false;
  5914. default:
  5915. break; // No other valid conversions
  5916. }
  5917. break;
  5918. case AR_BASIC_LITERAL_FLOAT:
  5919. switch (rightKind) {
  5920. case AR_BASIC_LITERAL_FLOAT:
  5921. case AR_BASIC_FLOAT16:
  5922. case AR_BASIC_FLOAT32:
  5923. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5924. case AR_BASIC_FLOAT64:
  5925. return false;
  5926. default:
  5927. break; // No other valid conversions
  5928. }
  5929. break;
  5930. case AR_BASIC_FLOAT16:
  5931. case AR_BASIC_FLOAT32:
  5932. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5933. case AR_BASIC_FLOAT64:
  5934. switch (rightKind) {
  5935. case AR_BASIC_LITERAL_FLOAT:
  5936. return false;
  5937. default:
  5938. break; // No other valid conversions
  5939. }
  5940. break;
  5941. default:
  5942. // No other relevant targets
  5943. break;
  5944. }
  5945. return true;
  5946. }
  5947. UINT64 HLSLExternalSource::ScoreCast(QualType pLType, QualType pRType)
  5948. {
  5949. if (pLType.getCanonicalType() == pRType.getCanonicalType()) {
  5950. return 0;
  5951. }
  5952. UINT64 uScore = 0;
  5953. UINT uLSize = GetNumElements(pLType);
  5954. UINT uRSize = GetNumElements(pRType);
  5955. UINT uCompareSize;
  5956. bool bLCast = false;
  5957. bool bRCast = false;
  5958. bool bLIntCast = false;
  5959. bool bRIntCast = false;
  5960. bool bLPromo = false;
  5961. bool bRPromo = false;
  5962. uCompareSize = GetNumConvertCheckElts(pLType, uLSize, pRType, uRSize);
  5963. if (uCompareSize > uRSize) {
  5964. uCompareSize = uRSize;
  5965. }
  5966. for (UINT i = 0; i < uCompareSize; i++) {
  5967. ArBasicKind LeftElementKind, RightElementKind;
  5968. ArBasicKind CombinedKind = AR_BASIC_BOOL;
  5969. QualType leftSub = GetNthElementType(pLType, i);
  5970. QualType rightSub = GetNthElementType(pRType, i);
  5971. ArTypeObjectKind leftKind = GetTypeObjectKind(leftSub);
  5972. ArTypeObjectKind rightKind = GetTypeObjectKind(rightSub);
  5973. LeftElementKind = GetTypeElementKind(leftSub);
  5974. RightElementKind = GetTypeElementKind(rightSub);
  5975. // CollectInfo is called with AR_TINFO_ALLOW_OBJECTS, and the resulting
  5976. // information needed is the ShapeKind, EltKind and ObjKind.
  5977. if (!leftSub.isNull() && !rightSub.isNull() && leftKind != AR_TOBJ_INVALID && rightKind != AR_TOBJ_INVALID) {
  5978. bool bCombine;
  5979. if (leftKind == AR_TOBJ_OBJECT || rightKind == AR_TOBJ_OBJECT) {
  5980. DXASSERT(rightKind == AR_TOBJ_OBJECT, "otherwise prior check is incorrect");
  5981. ArBasicKind LeftObjKind = LeftElementKind; // actually LeftElementKind would have been the element
  5982. ArBasicKind RightObjKind = RightElementKind;
  5983. LeftElementKind = LeftObjKind;
  5984. RightElementKind = RightObjKind;
  5985. if (leftKind != rightKind) {
  5986. bCombine = false;
  5987. }
  5988. else if (!(bCombine = CombineObjectTypes(LeftObjKind, RightObjKind, &CombinedKind))) {
  5989. bCombine = CombineObjectTypes(RightObjKind, LeftObjKind, &CombinedKind);
  5990. }
  5991. }
  5992. else {
  5993. bCombine = CombineBasicTypes(LeftElementKind, RightElementKind, &CombinedKind);
  5994. }
  5995. if (bCombine && IsPromotion(LeftElementKind, CombinedKind)) {
  5996. bLPromo = true;
  5997. }
  5998. else if (!bCombine || IsCast(LeftElementKind, CombinedKind)) {
  5999. bLCast = true;
  6000. }
  6001. else if (IsIntCast(LeftElementKind, CombinedKind)) {
  6002. bLIntCast = true;
  6003. }
  6004. if (bCombine && IsPromotion(CombinedKind, RightElementKind)) {
  6005. bRPromo = true;
  6006. } else if (!bCombine || IsCast(CombinedKind, RightElementKind)) {
  6007. bRCast = true;
  6008. } else if (IsIntCast(CombinedKind, RightElementKind)) {
  6009. bRIntCast = true;
  6010. }
  6011. } else {
  6012. bLCast = true;
  6013. bRCast = true;
  6014. }
  6015. }
  6016. #define SCORE_COND(shift, cond) { \
  6017. if (cond) uScore += 1ULL << (SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * shift); }
  6018. SCORE_COND(0, uRSize < uLSize);
  6019. SCORE_COND(1, bLPromo);
  6020. SCORE_COND(2, bRPromo);
  6021. SCORE_COND(3, bLIntCast);
  6022. SCORE_COND(4, bRIntCast);
  6023. SCORE_COND(5, bLCast);
  6024. SCORE_COND(6, bRCast);
  6025. SCORE_COND(7, uLSize < uRSize);
  6026. #undef SCORE_COND
  6027. // Make sure our scores fit in a UINT64.
  6028. C_ASSERT(SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * 8 <= 64);
  6029. return uScore;
  6030. }
  6031. UINT64 HLSLExternalSource::ScoreImplicitConversionSequence(const ImplicitConversionSequence *ics) {
  6032. DXASSERT(ics, "otherwise conversion has not been initialized");
  6033. if (!ics->isInitialized()) {
  6034. return 0;
  6035. }
  6036. if (!ics->isStandard()) {
  6037. return SCORE_MAX;
  6038. }
  6039. QualType fromType = ics->Standard.getFromType();
  6040. QualType toType = ics->Standard.getToType(2); // final type
  6041. return ScoreCast(toType, fromType);
  6042. }
  6043. UINT64 HLSLExternalSource::ScoreFunction(OverloadCandidateSet::iterator &Cand) {
  6044. // Ignore target version mismatches.
  6045. // in/out considerations have been taken care of by viability.
  6046. // 'this' considerations don't matter without inheritance, other
  6047. // than lookup and viability.
  6048. UINT64 result = 0;
  6049. for (unsigned convIdx = 0; convIdx < Cand->NumConversions; ++convIdx) {
  6050. UINT64 score;
  6051. score = ScoreImplicitConversionSequence(Cand->Conversions + convIdx);
  6052. if (score == SCORE_MAX) {
  6053. return SCORE_MAX;
  6054. }
  6055. result += score;
  6056. score = ScoreImplicitConversionSequence(Cand->OutConversions + convIdx);
  6057. if (score == SCORE_MAX) {
  6058. return SCORE_MAX;
  6059. }
  6060. result += score;
  6061. }
  6062. return result;
  6063. }
  6064. OverloadingResult HLSLExternalSource::GetBestViableFunction(
  6065. SourceLocation Loc,
  6066. OverloadCandidateSet& set,
  6067. OverloadCandidateSet::iterator& Best)
  6068. {
  6069. UINT64 bestScore = SCORE_MAX;
  6070. unsigned scoreMatch = 0;
  6071. Best = set.end();
  6072. if (set.size() == 1 && set.begin()->Viable) {
  6073. Best = set.begin();
  6074. return OR_Success;
  6075. }
  6076. for (OverloadCandidateSet::iterator Cand = set.begin(); Cand != set.end(); ++Cand) {
  6077. if (Cand->Viable) {
  6078. UINT64 score = ScoreFunction(Cand);
  6079. if (score != SCORE_MAX) {
  6080. if (score == bestScore) {
  6081. ++scoreMatch;
  6082. } else if (score < bestScore) {
  6083. Best = Cand;
  6084. scoreMatch = 1;
  6085. bestScore = score;
  6086. }
  6087. }
  6088. }
  6089. }
  6090. if (Best == set.end()) {
  6091. return OR_No_Viable_Function;
  6092. }
  6093. if (scoreMatch > 1) {
  6094. Best = set.end();
  6095. return OR_Ambiguous;
  6096. }
  6097. // No need to check for deleted functions to yield OR_Deleted.
  6098. return OR_Success;
  6099. }
  6100. /// <summary>
  6101. /// Initializes the specified <paramref name="initSequence" /> describing how
  6102. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  6103. /// </summary>
  6104. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  6105. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  6106. /// <param name="Args">Arguments to the initialization.</param>
  6107. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  6108. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  6109. void HLSLExternalSource::InitializeInitSequenceForHLSL(
  6110. const InitializedEntity& Entity,
  6111. const InitializationKind& Kind,
  6112. MultiExprArg Args,
  6113. bool TopLevelOfInitList,
  6114. _Inout_ InitializationSequence* initSequence)
  6115. {
  6116. DXASSERT_NOMSG(initSequence != nullptr);
  6117. // In HLSL there are no default initializers, eg float4x4 m();
  6118. // Except for RayQuery constructor (also handle InitializationKind::IK_Value)
  6119. if (Kind.getKind() == InitializationKind::IK_Default ||
  6120. Kind.getKind() == InitializationKind::IK_Value) {
  6121. QualType destBaseType = m_context->getBaseElementType(Entity.getType());
  6122. ArTypeObjectKind destBaseShape = GetTypeObjectKind(destBaseType);
  6123. if (destBaseShape == AR_TOBJ_OBJECT) {
  6124. const CXXRecordDecl *typeRecordDecl = destBaseType->getAsCXXRecordDecl();
  6125. int index = FindObjectBasicKindIndex(GetRecordDeclForBuiltInOrStruct(typeRecordDecl));
  6126. DXASSERT(index != -1, "otherwise can't find type we already determined was an object");
  6127. if (g_ArBasicKindsAsTypes[index] == AR_OBJECT_RAY_QUERY) {
  6128. CXXConstructorDecl *Constructor = *typeRecordDecl->ctor_begin();
  6129. initSequence->AddConstructorInitializationStep(
  6130. Constructor, AccessSpecifier::AS_public, destBaseType, false, false, false);
  6131. return;
  6132. }
  6133. }
  6134. // Value initializers occur for temporaries with empty parens or braces.
  6135. if (Kind.getKind() == InitializationKind::IK_Value) {
  6136. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_type_empty_init) << Entity.getType();
  6137. SilenceSequenceDiagnostics(initSequence);
  6138. }
  6139. return;
  6140. }
  6141. // If we have a DirectList, we should have a single InitListExprClass argument.
  6142. DXASSERT(
  6143. Kind.getKind() != InitializationKind::IK_DirectList ||
  6144. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass),
  6145. "otherwise caller is passing in incorrect initialization configuration");
  6146. bool isCast = Kind.isCStyleCast();
  6147. QualType destType = Entity.getType();
  6148. ArTypeObjectKind destShape = GetTypeObjectKind(destType);
  6149. // Direct initialization occurs for explicit constructor arguments.
  6150. // E.g.: http://en.cppreference.com/w/cpp/language/direct_initialization
  6151. if (Kind.getKind() == InitializationKind::IK_Direct && destShape == AR_TOBJ_COMPOUND &&
  6152. !Kind.isCStyleOrFunctionalCast()) {
  6153. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_require_numeric_base_for_ctor);
  6154. SilenceSequenceDiagnostics(initSequence);
  6155. return;
  6156. }
  6157. bool flatten =
  6158. (Kind.getKind() == InitializationKind::IK_Direct && !isCast) ||
  6159. Kind.getKind() == InitializationKind::IK_DirectList ||
  6160. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass);
  6161. if (flatten) {
  6162. // TODO: InitializationSequence::Perform in SemaInit should take the arity of incomplete
  6163. // array types to adjust the value - we do calculate this as part of type analysis.
  6164. // Until this is done, s_arr_i_f arr_struct_none[] = { }; succeeds when it should instead fail.
  6165. FlattenedTypeIterator::ComparisonResult comparisonResult =
  6166. FlattenedTypeIterator::CompareTypesForInit(
  6167. *this, destType, Args,
  6168. Kind.getLocation(), Kind.getLocation());
  6169. if (comparisonResult.IsConvertibleAndEqualLength() ||
  6170. (isCast && comparisonResult.IsConvertibleAndLeftLonger()))
  6171. {
  6172. initSequence->AddListInitializationStep(destType);
  6173. }
  6174. else
  6175. {
  6176. SourceLocation diagLocation;
  6177. if (Args.size() > 0)
  6178. {
  6179. diagLocation = Args.front()->getLocStart();
  6180. }
  6181. else
  6182. {
  6183. diagLocation = Entity.getDiagLoc();
  6184. }
  6185. if (comparisonResult.IsEqualLength()) {
  6186. m_sema->Diag(diagLocation, diag::err_hlsl_type_mismatch);
  6187. }
  6188. else {
  6189. m_sema->Diag(diagLocation,
  6190. diag::err_incorrect_num_initializers)
  6191. << (comparisonResult.RightCount < comparisonResult.LeftCount)
  6192. << IsSubobjectType(destType)
  6193. << comparisonResult.LeftCount << comparisonResult.RightCount;
  6194. }
  6195. SilenceSequenceDiagnostics(initSequence);
  6196. }
  6197. }
  6198. else {
  6199. DXASSERT(Args.size() == 1, "otherwise this was mis-parsed or should be a list initialization");
  6200. Expr* firstArg = Args.front();
  6201. if (IsExpressionBinaryComma(firstArg)) {
  6202. m_sema->Diag(firstArg->getExprLoc(), diag::warn_hlsl_comma_in_init);
  6203. }
  6204. ExprResult expr = ExprResult(firstArg);
  6205. Sema::CheckedConversionKind cck = Kind.isExplicitCast() ?
  6206. Sema::CheckedConversionKind::CCK_CStyleCast :
  6207. Sema::CheckedConversionKind::CCK_ImplicitConversion;
  6208. unsigned int msg = 0;
  6209. CastKind castKind;
  6210. CXXCastPath basePath;
  6211. SourceRange range = Kind.getRange();
  6212. ImplicitConversionSequence ics;
  6213. ics.setStandard();
  6214. bool castWorked = TryStaticCastForHLSL(
  6215. expr, destType, cck, range, msg, castKind, basePath, ListInitializationFalse, SuppressWarningsFalse, SuppressErrorsTrue, &ics.Standard);
  6216. if (castWorked) {
  6217. if (destType.getCanonicalType() ==
  6218. firstArg->getType().getCanonicalType() &&
  6219. (ics.Standard).First != ICK_Lvalue_To_Rvalue) {
  6220. initSequence->AddCAssignmentStep(destType);
  6221. } else {
  6222. initSequence->AddConversionSequenceStep(ics, destType.getNonReferenceType(), TopLevelOfInitList);
  6223. }
  6224. }
  6225. else {
  6226. initSequence->SetFailed(InitializationSequence::FK_ConversionFailed);
  6227. }
  6228. }
  6229. }
  6230. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  6231. const QualType& sourceType,
  6232. const QualType& targetType,
  6233. bool explicitConversion)
  6234. {
  6235. DXASSERT_NOMSG(!sourceType.isNull());
  6236. DXASSERT_NOMSG(!targetType.isNull());
  6237. ArTypeInfo sourceTypeInfo;
  6238. ArTypeInfo targetTypeInfo;
  6239. GetConversionForm(sourceType, explicitConversion, &sourceTypeInfo);
  6240. GetConversionForm(targetType, explicitConversion, &targetTypeInfo);
  6241. if (sourceTypeInfo.EltKind != targetTypeInfo.EltKind)
  6242. {
  6243. return false;
  6244. }
  6245. bool isVecMatTrunc = sourceTypeInfo.ShapeKind == AR_TOBJ_VECTOR &&
  6246. targetTypeInfo.ShapeKind == AR_TOBJ_BASIC;
  6247. if (sourceTypeInfo.ShapeKind != targetTypeInfo.ShapeKind &&
  6248. !isVecMatTrunc)
  6249. {
  6250. return false;
  6251. }
  6252. if (sourceTypeInfo.ShapeKind == AR_TOBJ_OBJECT &&
  6253. sourceTypeInfo.ObjKind == targetTypeInfo.ObjKind) {
  6254. return true;
  6255. }
  6256. // Same struct is eqaul.
  6257. if (sourceTypeInfo.ShapeKind == AR_TOBJ_COMPOUND &&
  6258. sourceType.getCanonicalType().getUnqualifiedType() ==
  6259. targetType.getCanonicalType().getUnqualifiedType()) {
  6260. return true;
  6261. }
  6262. // DerivedFrom is less.
  6263. if (sourceTypeInfo.ShapeKind == AR_TOBJ_COMPOUND ||
  6264. GetTypeObjectKind(sourceType) == AR_TOBJ_COMPOUND) {
  6265. const RecordType *targetRT = targetType->getAsStructureType();
  6266. if (!targetRT)
  6267. targetRT = dyn_cast<RecordType>(targetType);
  6268. const RecordType *sourceRT = sourceType->getAsStructureType();
  6269. if (!sourceRT)
  6270. sourceRT = dyn_cast<RecordType>(sourceType);
  6271. if (targetRT && sourceRT) {
  6272. RecordDecl *targetRD = targetRT->getDecl();
  6273. RecordDecl *sourceRD = sourceRT->getDecl();
  6274. const CXXRecordDecl *targetCXXRD = dyn_cast<CXXRecordDecl>(targetRD);
  6275. const CXXRecordDecl *sourceCXXRD = dyn_cast<CXXRecordDecl>(sourceRD);
  6276. if (targetCXXRD && sourceCXXRD) {
  6277. if (sourceCXXRD->isDerivedFrom(targetCXXRD))
  6278. return true;
  6279. }
  6280. }
  6281. }
  6282. if (sourceTypeInfo.ShapeKind != AR_TOBJ_SCALAR &&
  6283. sourceTypeInfo.ShapeKind != AR_TOBJ_VECTOR &&
  6284. sourceTypeInfo.ShapeKind != AR_TOBJ_MATRIX)
  6285. {
  6286. return false;
  6287. }
  6288. return targetTypeInfo.uTotalElts <= sourceTypeInfo.uTotalElts;
  6289. }
  6290. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  6291. const ExprResult& sourceExpr,
  6292. const QualType& targetType,
  6293. bool explicitConversion)
  6294. {
  6295. if (sourceExpr.isInvalid() || targetType.isNull())
  6296. {
  6297. return false;
  6298. }
  6299. return IsConversionToLessOrEqualElements(sourceExpr.get()->getType(), targetType, explicitConversion);
  6300. }
  6301. bool HLSLExternalSource::IsTypeNumeric(QualType type, UINT* count)
  6302. {
  6303. DXASSERT_NOMSG(!type.isNull());
  6304. DXASSERT_NOMSG(count != nullptr);
  6305. *count = 0;
  6306. UINT subCount = 0;
  6307. ArTypeObjectKind shapeKind = GetTypeObjectKind(type);
  6308. switch (shapeKind)
  6309. {
  6310. case AR_TOBJ_ARRAY:
  6311. if (IsTypeNumeric(m_context->getAsArrayType(type)->getElementType(), &subCount))
  6312. {
  6313. *count = subCount * GetArraySize(type);
  6314. return true;
  6315. }
  6316. return false;
  6317. case AR_TOBJ_COMPOUND:
  6318. {
  6319. UINT maxCount = 0;
  6320. { // Determine maximum count to prevent infinite loop on incomplete array
  6321. FlattenedTypeIterator itCount(SourceLocation(), type, *this);
  6322. maxCount = itCount.countRemaining();
  6323. if (!maxCount) {
  6324. return false; // empty struct.
  6325. }
  6326. }
  6327. FlattenedTypeIterator it(SourceLocation(), type, *this);
  6328. while (it.hasCurrentElement()) {
  6329. bool isFieldNumeric = IsTypeNumeric(it.getCurrentElement(), &subCount);
  6330. if (!isFieldNumeric) {
  6331. return false;
  6332. }
  6333. if (*count >= maxCount) {
  6334. // this element is an incomplete array at the end; iterator will not advance past this element.
  6335. // don't add to *count either, so *count will represent minimum size of the structure.
  6336. break;
  6337. }
  6338. *count += (subCount * it.getCurrentElementSize());
  6339. it.advanceCurrentElement(it.getCurrentElementSize());
  6340. }
  6341. return true;
  6342. }
  6343. default:
  6344. DXASSERT(false, "unreachable");
  6345. case AR_TOBJ_BASIC:
  6346. case AR_TOBJ_MATRIX:
  6347. case AR_TOBJ_VECTOR:
  6348. *count = GetElementCount(type);
  6349. return IsBasicKindNumeric(GetTypeElementKind(type));
  6350. case AR_TOBJ_OBJECT:
  6351. case AR_TOBJ_STRING:
  6352. return false;
  6353. }
  6354. }
  6355. enum MatrixMemberAccessError {
  6356. MatrixMemberAccessError_None, // No errors found.
  6357. MatrixMemberAccessError_BadFormat, // Formatting error (non-digit).
  6358. MatrixMemberAccessError_MixingRefs, // Mix of zero-based and one-based references.
  6359. MatrixMemberAccessError_Empty, // No members specified.
  6360. MatrixMemberAccessError_ZeroInOneBased, // A zero was used in a one-based reference.
  6361. MatrixMemberAccessError_FourInZeroBased, // A four was used in a zero-based reference.
  6362. MatrixMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  6363. };
  6364. static
  6365. MatrixMemberAccessError TryConsumeMatrixDigit(const char*& memberText, uint32_t* value)
  6366. {
  6367. DXASSERT_NOMSG(memberText != nullptr);
  6368. DXASSERT_NOMSG(value != nullptr);
  6369. if ('0' <= *memberText && *memberText <= '9')
  6370. {
  6371. *value = (*memberText) - '0';
  6372. }
  6373. else
  6374. {
  6375. return MatrixMemberAccessError_BadFormat;
  6376. }
  6377. memberText++;
  6378. return MatrixMemberAccessError_None;
  6379. }
  6380. static
  6381. MatrixMemberAccessError TryParseMatrixMemberAccess(_In_z_ const char* memberText, _Out_ MatrixMemberAccessPositions* value)
  6382. {
  6383. DXASSERT_NOMSG(memberText != nullptr);
  6384. DXASSERT_NOMSG(value != nullptr);
  6385. MatrixMemberAccessPositions result;
  6386. bool zeroBasedDecided = false;
  6387. bool zeroBased = false;
  6388. // Set the output value to invalid to allow early exits when errors are found.
  6389. value->IsValid = 0;
  6390. // Assume this is true until proven otherwise.
  6391. result.IsValid = 1;
  6392. result.Count = 0;
  6393. while (*memberText)
  6394. {
  6395. // Check for a leading underscore.
  6396. if (*memberText != '_')
  6397. {
  6398. return MatrixMemberAccessError_BadFormat;
  6399. }
  6400. ++memberText;
  6401. // Check whether we have an 'm' or a digit.
  6402. if (*memberText == 'm')
  6403. {
  6404. if (zeroBasedDecided && !zeroBased)
  6405. {
  6406. return MatrixMemberAccessError_MixingRefs;
  6407. }
  6408. zeroBased = true;
  6409. zeroBasedDecided = true;
  6410. ++memberText;
  6411. }
  6412. else if (!('0' <= *memberText && *memberText <= '9'))
  6413. {
  6414. return MatrixMemberAccessError_BadFormat;
  6415. }
  6416. else
  6417. {
  6418. if (zeroBasedDecided && zeroBased)
  6419. {
  6420. return MatrixMemberAccessError_MixingRefs;
  6421. }
  6422. zeroBased = false;
  6423. zeroBasedDecided = true;
  6424. }
  6425. // Consume two digits for the position.
  6426. uint32_t rowPosition;
  6427. uint32_t colPosition;
  6428. MatrixMemberAccessError digitError;
  6429. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &rowPosition)))
  6430. {
  6431. return digitError;
  6432. }
  6433. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &colPosition)))
  6434. {
  6435. return digitError;
  6436. }
  6437. // Look for specific common errors (developer likely mixed up reference style).
  6438. if (zeroBased)
  6439. {
  6440. if (rowPosition == 4 || colPosition == 4)
  6441. {
  6442. return MatrixMemberAccessError_FourInZeroBased;
  6443. }
  6444. }
  6445. else
  6446. {
  6447. if (rowPosition == 0 || colPosition == 0)
  6448. {
  6449. return MatrixMemberAccessError_ZeroInOneBased;
  6450. }
  6451. // SetPosition will use zero-based indices.
  6452. --rowPosition;
  6453. --colPosition;
  6454. }
  6455. if (result.Count == 4)
  6456. {
  6457. return MatrixMemberAccessError_TooManyPositions;
  6458. }
  6459. result.SetPosition(result.Count, rowPosition, colPosition);
  6460. result.Count++;
  6461. }
  6462. if (result.Count == 0)
  6463. {
  6464. return MatrixMemberAccessError_Empty;
  6465. }
  6466. *value = result;
  6467. return MatrixMemberAccessError_None;
  6468. }
  6469. ExprResult HLSLExternalSource::LookupMatrixMemberExprForHLSL(
  6470. Expr& BaseExpr,
  6471. DeclarationName MemberName,
  6472. bool IsArrow,
  6473. SourceLocation OpLoc,
  6474. SourceLocation MemberLoc)
  6475. {
  6476. QualType BaseType = BaseExpr.getType();
  6477. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  6478. DXASSERT(GetTypeObjectKind(BaseType) == AR_TOBJ_MATRIX, "Should only be called on known matrix types");
  6479. QualType elementType;
  6480. UINT rowCount, colCount;
  6481. GetRowsAndCols(BaseType, rowCount, colCount);
  6482. elementType = GetMatrixOrVectorElementType(BaseType);
  6483. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  6484. const char *memberText = member->getNameStart();
  6485. MatrixMemberAccessPositions positions;
  6486. MatrixMemberAccessError memberAccessError;
  6487. unsigned msg = 0;
  6488. memberAccessError = TryParseMatrixMemberAccess(memberText, &positions);
  6489. switch (memberAccessError)
  6490. {
  6491. case MatrixMemberAccessError_BadFormat:
  6492. msg = diag::err_hlsl_matrix_member_bad_format;
  6493. break;
  6494. case MatrixMemberAccessError_Empty:
  6495. msg = diag::err_hlsl_matrix_member_empty;
  6496. break;
  6497. case MatrixMemberAccessError_FourInZeroBased:
  6498. msg = diag::err_hlsl_matrix_member_four_in_zero_based;
  6499. break;
  6500. case MatrixMemberAccessError_MixingRefs:
  6501. msg = diag::err_hlsl_matrix_member_mixing_refs;
  6502. break;
  6503. case MatrixMemberAccessError_None:
  6504. msg = 0;
  6505. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6506. // Check the position with the type now.
  6507. for (unsigned int i = 0; i < positions.Count; i++)
  6508. {
  6509. uint32_t rowPos, colPos;
  6510. positions.GetPosition(i, &rowPos, &colPos);
  6511. if (rowPos >= rowCount || colPos >= colCount)
  6512. {
  6513. msg = diag::err_hlsl_matrix_member_out_of_bounds;
  6514. break;
  6515. }
  6516. }
  6517. break;
  6518. case MatrixMemberAccessError_TooManyPositions:
  6519. msg = diag::err_hlsl_matrix_member_too_many_positions;
  6520. break;
  6521. case MatrixMemberAccessError_ZeroInOneBased:
  6522. msg = diag::err_hlsl_matrix_member_zero_in_one_based;
  6523. break;
  6524. default:
  6525. llvm_unreachable("Unknown MatrixMemberAccessError value");
  6526. }
  6527. if (msg != 0)
  6528. {
  6529. m_sema->Diag(MemberLoc, msg) << memberText;
  6530. // It's possible that it's a simple out-of-bounds condition. In this case,
  6531. // generate the member access expression with the correct arity and continue
  6532. // processing.
  6533. if (!positions.IsValid)
  6534. {
  6535. return ExprError();
  6536. }
  6537. }
  6538. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6539. // Consume elements
  6540. QualType resultType;
  6541. if (positions.Count == 1)
  6542. resultType = elementType;
  6543. else
  6544. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  6545. // Add qualifiers from BaseType.
  6546. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  6547. ExprValueKind VK =
  6548. positions.ContainsDuplicateElements() ? VK_RValue :
  6549. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  6550. ExtMatrixElementExpr* matrixExpr = new (m_context)ExtMatrixElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  6551. return matrixExpr;
  6552. }
  6553. enum VectorMemberAccessError {
  6554. VectorMemberAccessError_None, // No errors found.
  6555. VectorMemberAccessError_BadFormat, // Formatting error (not in 'rgba' or 'xyzw').
  6556. VectorMemberAccessError_MixingStyles, // Mix of rgba and xyzw swizzle styles.
  6557. VectorMemberAccessError_Empty, // No members specified.
  6558. VectorMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  6559. };
  6560. static
  6561. VectorMemberAccessError TryConsumeVectorDigit(const char*& memberText, uint32_t* value, bool &rgbaStyle) {
  6562. DXASSERT_NOMSG(memberText != nullptr);
  6563. DXASSERT_NOMSG(value != nullptr);
  6564. rgbaStyle = false;
  6565. switch (*memberText) {
  6566. case 'r':
  6567. rgbaStyle = true;
  6568. case 'x':
  6569. *value = 0;
  6570. break;
  6571. case 'g':
  6572. rgbaStyle = true;
  6573. case 'y':
  6574. *value = 1;
  6575. break;
  6576. case 'b':
  6577. rgbaStyle = true;
  6578. case 'z':
  6579. *value = 2;
  6580. break;
  6581. case 'a':
  6582. rgbaStyle = true;
  6583. case 'w':
  6584. *value = 3;
  6585. break;
  6586. default:
  6587. return VectorMemberAccessError_BadFormat;
  6588. }
  6589. memberText++;
  6590. return VectorMemberAccessError_None;
  6591. }
  6592. static
  6593. VectorMemberAccessError TryParseVectorMemberAccess(_In_z_ const char* memberText, _Out_ VectorMemberAccessPositions* value) {
  6594. DXASSERT_NOMSG(memberText != nullptr);
  6595. DXASSERT_NOMSG(value != nullptr);
  6596. VectorMemberAccessPositions result;
  6597. bool rgbaStyleDecided = false;
  6598. bool rgbaStyle = false;
  6599. // Set the output value to invalid to allow early exits when errors are found.
  6600. value->IsValid = 0;
  6601. // Assume this is true until proven otherwise.
  6602. result.IsValid = 1;
  6603. result.Count = 0;
  6604. while (*memberText) {
  6605. // Consume one character for the swizzle.
  6606. uint32_t colPosition;
  6607. VectorMemberAccessError digitError;
  6608. bool rgbaStyleTmp = false;
  6609. if (VectorMemberAccessError_None != (digitError = TryConsumeVectorDigit(memberText, &colPosition, rgbaStyleTmp))) {
  6610. return digitError;
  6611. }
  6612. if (rgbaStyleDecided && rgbaStyleTmp != rgbaStyle) {
  6613. return VectorMemberAccessError_MixingStyles;
  6614. }
  6615. else {
  6616. rgbaStyleDecided = true;
  6617. rgbaStyle = rgbaStyleTmp;
  6618. }
  6619. if (result.Count == 4) {
  6620. return VectorMemberAccessError_TooManyPositions;
  6621. }
  6622. result.SetPosition(result.Count, colPosition);
  6623. result.Count++;
  6624. }
  6625. if (result.Count == 0) {
  6626. return VectorMemberAccessError_Empty;
  6627. }
  6628. *value = result;
  6629. return VectorMemberAccessError_None;
  6630. }
  6631. bool IsExprAccessingOutIndicesArray(Expr* BaseExpr) {
  6632. switch(BaseExpr->getStmtClass()) {
  6633. case Stmt::ArraySubscriptExprClass: {
  6634. ArraySubscriptExpr* ase = cast<ArraySubscriptExpr>(BaseExpr);
  6635. return IsExprAccessingOutIndicesArray(ase->getBase());
  6636. }
  6637. case Stmt::ImplicitCastExprClass: {
  6638. ImplicitCastExpr* ice = cast<ImplicitCastExpr>(BaseExpr);
  6639. return IsExprAccessingOutIndicesArray(ice->getSubExpr());
  6640. }
  6641. case Stmt::DeclRefExprClass: {
  6642. DeclRefExpr* dre = cast<DeclRefExpr>(BaseExpr);
  6643. ValueDecl* vd = dre->getDecl();
  6644. if (vd->getAttr<HLSLIndicesAttr>() && vd->getAttr<HLSLOutAttr>()) {
  6645. return true;
  6646. }
  6647. return false;
  6648. }
  6649. default:
  6650. return false;
  6651. }
  6652. }
  6653. ExprResult HLSLExternalSource::LookupVectorMemberExprForHLSL(
  6654. Expr& BaseExpr,
  6655. DeclarationName MemberName,
  6656. bool IsArrow,
  6657. SourceLocation OpLoc,
  6658. SourceLocation MemberLoc) {
  6659. QualType BaseType = BaseExpr.getType();
  6660. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  6661. DXASSERT(GetTypeObjectKind(BaseType) == AR_TOBJ_VECTOR, "Should only be called on known vector types");
  6662. QualType elementType;
  6663. UINT colCount = GetHLSLVecSize(BaseType);
  6664. elementType = GetMatrixOrVectorElementType(BaseType);
  6665. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  6666. const char *memberText = member->getNameStart();
  6667. VectorMemberAccessPositions positions;
  6668. VectorMemberAccessError memberAccessError;
  6669. unsigned msg = 0;
  6670. memberAccessError = TryParseVectorMemberAccess(memberText, &positions);
  6671. switch (memberAccessError) {
  6672. case VectorMemberAccessError_BadFormat:
  6673. msg = diag::err_hlsl_vector_member_bad_format;
  6674. break;
  6675. case VectorMemberAccessError_Empty:
  6676. msg = diag::err_hlsl_vector_member_empty;
  6677. break;
  6678. case VectorMemberAccessError_MixingStyles:
  6679. msg = diag::err_ext_vector_component_name_mixedsets;
  6680. break;
  6681. case VectorMemberAccessError_None:
  6682. msg = 0;
  6683. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6684. // Check the position with the type now.
  6685. for (unsigned int i = 0; i < positions.Count; i++) {
  6686. uint32_t colPos;
  6687. positions.GetPosition(i, &colPos);
  6688. if (colPos >= colCount) {
  6689. msg = diag::err_hlsl_vector_member_out_of_bounds;
  6690. break;
  6691. }
  6692. }
  6693. break;
  6694. case VectorMemberAccessError_TooManyPositions:
  6695. msg = diag::err_hlsl_vector_member_too_many_positions;
  6696. break;
  6697. default:
  6698. llvm_unreachable("Unknown VectorMemberAccessError value");
  6699. }
  6700. if (msg != 0) {
  6701. m_sema->Diag(MemberLoc, msg) << memberText;
  6702. // It's possible that it's a simple out-of-bounds condition. In this case,
  6703. // generate the member access expression with the correct arity and continue
  6704. // processing.
  6705. if (!positions.IsValid) {
  6706. return ExprError();
  6707. }
  6708. }
  6709. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6710. // Disallow component access for out indices for DXIL path. We still allow
  6711. // this in SPIR-V path.
  6712. if (!m_sema->getLangOpts().SPIRV &&
  6713. IsExprAccessingOutIndicesArray(&BaseExpr) && positions.Count < colCount) {
  6714. m_sema->Diag(MemberLoc, diag::err_hlsl_out_indices_array_incorrect_access);
  6715. return ExprError();
  6716. }
  6717. // Consume elements
  6718. QualType resultType;
  6719. if (positions.Count == 1)
  6720. resultType = elementType;
  6721. else
  6722. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  6723. // Add qualifiers from BaseType.
  6724. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  6725. ExprValueKind VK =
  6726. positions.ContainsDuplicateElements() ? VK_RValue :
  6727. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  6728. HLSLVectorElementExpr* vectorExpr = new (m_context)HLSLVectorElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  6729. return vectorExpr;
  6730. }
  6731. ExprResult HLSLExternalSource::LookupArrayMemberExprForHLSL(
  6732. Expr& BaseExpr,
  6733. DeclarationName MemberName,
  6734. bool IsArrow,
  6735. SourceLocation OpLoc,
  6736. SourceLocation MemberLoc) {
  6737. QualType BaseType = BaseExpr.getType();
  6738. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  6739. DXASSERT(GetTypeObjectKind(BaseType) == AR_TOBJ_ARRAY, "Should only be called on known array types");
  6740. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  6741. const char *memberText = member->getNameStart();
  6742. // The only property available on arrays is Length; it is deprecated and available only on HLSL version <=2018
  6743. if (member->getLength() == 6 && 0 == strcmp(memberText, "Length")) {
  6744. if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(BaseType)) {
  6745. // check version support
  6746. unsigned hlslVer = getSema()->getLangOpts().HLSLVersion;
  6747. if (hlslVer > 2016) {
  6748. m_sema->Diag(MemberLoc, diag::err_hlsl_unsupported_for_version_lower) << "Length" << "2016";
  6749. return ExprError();
  6750. }
  6751. if (hlslVer == 2016) {
  6752. m_sema->Diag(MemberLoc, diag::warn_deprecated) << "Length";
  6753. }
  6754. UnaryExprOrTypeTraitExpr *arrayLenExpr = new (m_context) UnaryExprOrTypeTraitExpr(
  6755. UETT_ArrayLength, &BaseExpr, m_context->getSizeType(), MemberLoc, BaseExpr.getSourceRange().getEnd());
  6756. return arrayLenExpr;
  6757. }
  6758. }
  6759. m_sema->Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
  6760. << BaseType << BaseExpr.getSourceRange() << MemberLoc;
  6761. return ExprError();
  6762. }
  6763. ExprResult HLSLExternalSource::MaybeConvertScalarToVector(_In_ clang::Expr* E) {
  6764. DXASSERT_NOMSG(E != nullptr);
  6765. ArBasicKind basic = GetTypeElementKind(E->getType());
  6766. if (!IS_BASIC_PRIMITIVE(basic)) {
  6767. return E;
  6768. }
  6769. ArTypeObjectKind kind = GetTypeObjectKind(E->getType());
  6770. if (kind != AR_TOBJ_SCALAR) {
  6771. return E;
  6772. }
  6773. QualType targetType = NewSimpleAggregateType(AR_TOBJ_VECTOR, basic, 0, 1, 1);
  6774. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLVectorSplat, E, nullptr, E->getValueKind());
  6775. }
  6776. static clang::CastKind ImplicitConversionKindToCastKind(
  6777. clang::ImplicitConversionKind ICK,
  6778. ArBasicKind FromKind,
  6779. ArBasicKind ToKind) {
  6780. // TODO: Shouldn't we have more specific ICK enums so we don't have to re-evaluate
  6781. // based on from/to kinds in order to determine CastKind?
  6782. // There's a FIXME note in PerformImplicitConversion that calls out exactly this
  6783. // problem.
  6784. switch (ICK) {
  6785. case ICK_Integral_Promotion:
  6786. case ICK_Integral_Conversion:
  6787. return CK_IntegralCast;
  6788. case ICK_Floating_Promotion:
  6789. case ICK_Floating_Conversion:
  6790. return CK_FloatingCast;
  6791. case ICK_Floating_Integral:
  6792. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_AINT(ToKind))
  6793. return CK_FloatingToIntegral;
  6794. else if ((IS_BASIC_AINT(FromKind) || IS_BASIC_BOOL(FromKind)) && IS_BASIC_FLOAT(ToKind))
  6795. return CK_IntegralToFloating;
  6796. break;
  6797. case ICK_Boolean_Conversion:
  6798. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_BOOL(ToKind))
  6799. return CK_FloatingToBoolean;
  6800. else if (IS_BASIC_AINT(FromKind) && IS_BASIC_BOOL(ToKind))
  6801. return CK_IntegralToBoolean;
  6802. break;
  6803. default:
  6804. // Only covers implicit conversions with cast kind equivalents.
  6805. return CK_Invalid;
  6806. }
  6807. return CK_Invalid;
  6808. }
  6809. static clang::CastKind ConvertToComponentCastKind(clang::CastKind CK) {
  6810. switch (CK) {
  6811. case CK_IntegralCast:
  6812. return CK_HLSLCC_IntegralCast;
  6813. case CK_FloatingCast:
  6814. return CK_HLSLCC_FloatingCast;
  6815. case CK_FloatingToIntegral:
  6816. return CK_HLSLCC_FloatingToIntegral;
  6817. case CK_IntegralToFloating:
  6818. return CK_HLSLCC_IntegralToFloating;
  6819. case CK_FloatingToBoolean:
  6820. return CK_HLSLCC_FloatingToBoolean;
  6821. case CK_IntegralToBoolean:
  6822. return CK_HLSLCC_IntegralToBoolean;
  6823. default:
  6824. // Only HLSLCC castkinds are relevant. Ignore the rest.
  6825. return CK_Invalid;
  6826. }
  6827. return CK_Invalid;
  6828. }
  6829. clang::Expr *HLSLExternalSource::HLSLImpCastToScalar(
  6830. _In_ clang::Sema* self,
  6831. _In_ clang::Expr* From,
  6832. ArTypeObjectKind FromShape,
  6833. ArBasicKind EltKind)
  6834. {
  6835. clang::CastKind CK = CK_Invalid;
  6836. if (AR_TOBJ_MATRIX == FromShape)
  6837. CK = CK_HLSLMatrixToScalarCast;
  6838. if (AR_TOBJ_VECTOR == FromShape)
  6839. CK = CK_HLSLVectorToScalarCast;
  6840. if (CK_Invalid != CK) {
  6841. return self->ImpCastExprToType(From,
  6842. NewSimpleAggregateType(AR_TOBJ_BASIC, EltKind, 0, 1, 1), CK, From->getValueKind()).get();
  6843. }
  6844. return From;
  6845. }
  6846. clang::ExprResult HLSLExternalSource::PerformHLSLConversion(
  6847. _In_ clang::Expr* From,
  6848. _In_ clang::QualType targetType,
  6849. _In_ const clang::StandardConversionSequence &SCS,
  6850. _In_ clang::Sema::CheckedConversionKind CCK)
  6851. {
  6852. QualType sourceType = From->getType();
  6853. sourceType = GetStructuralForm(sourceType);
  6854. targetType = GetStructuralForm(targetType);
  6855. ArTypeInfo SourceInfo, TargetInfo;
  6856. CollectInfo(sourceType, &SourceInfo);
  6857. CollectInfo(targetType, &TargetInfo);
  6858. clang::CastKind CK = CK_Invalid;
  6859. QualType intermediateTarget;
  6860. // TODO: construct vector/matrix and component cast expressions
  6861. switch (SCS.Second) {
  6862. case ICK_Flat_Conversion: {
  6863. // TODO: determine how to handle individual component conversions:
  6864. // - have an array of conversions for ComponentConversion in SCS?
  6865. // convert that to an array of casts under a special kind of flat
  6866. // flat conversion node? What do component conversion casts cast
  6867. // from? We don't have a From expression for individiual components.
  6868. From = m_sema->ImpCastExprToType(From, targetType.getUnqualifiedType(), CK_FlatConversion, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6869. break;
  6870. }
  6871. case ICK_HLSL_Derived_To_Base: {
  6872. CXXCastPath BasePath;
  6873. if (m_sema->CheckDerivedToBaseConversion(
  6874. sourceType, targetType.getNonReferenceType(), From->getLocStart(),
  6875. From->getSourceRange(), &BasePath, /*IgnoreAccess=*/true))
  6876. return ExprError();
  6877. From = m_sema->ImpCastExprToType(From, targetType.getUnqualifiedType(), CK_HLSLDerivedToBase, From->getValueKind(), &BasePath, CCK).get();
  6878. break;
  6879. }
  6880. case ICK_HLSLVector_Splat: {
  6881. // 1. optionally convert from vec1 or mat1x1 to scalar
  6882. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6883. // 2. optionally convert component type
  6884. if (ICK_Identity != SCS.ComponentConversion) {
  6885. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6886. if (CK_Invalid != CK) {
  6887. From = m_sema->ImpCastExprToType(From,
  6888. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6889. }
  6890. }
  6891. // 3. splat scalar to final vector or matrix
  6892. CK = CK_Invalid;
  6893. if (AR_TOBJ_VECTOR == TargetInfo.ShapeKind)
  6894. CK = CK_HLSLVectorSplat;
  6895. else if (AR_TOBJ_MATRIX == TargetInfo.ShapeKind)
  6896. CK = CK_HLSLMatrixSplat;
  6897. if (CK_Invalid != CK) {
  6898. From = m_sema->ImpCastExprToType(From,
  6899. NewSimpleAggregateType(TargetInfo.ShapeKind, TargetInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6900. }
  6901. break;
  6902. }
  6903. case ICK_HLSLVector_Scalar: {
  6904. // 1. select vector or matrix component
  6905. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6906. // 2. optionally convert component type
  6907. if (ICK_Identity != SCS.ComponentConversion) {
  6908. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6909. if (CK_Invalid != CK) {
  6910. From = m_sema->ImpCastExprToType(From,
  6911. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6912. }
  6913. }
  6914. break;
  6915. }
  6916. // The following two (three if we re-introduce ICK_HLSLComponent_Conversion) steps
  6917. // can be done with case fall-through, since this is the order in which we want to
  6918. // do the conversion operations.
  6919. case ICK_HLSLVector_Truncation: {
  6920. // 1. dimension truncation
  6921. // vector truncation or matrix truncation?
  6922. if (SourceInfo.ShapeKind == AR_TOBJ_VECTOR) {
  6923. From = m_sema->ImpCastExprToType(From,
  6924. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, 1, TargetInfo.uTotalElts),
  6925. CK_HLSLVectorTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6926. } else if (SourceInfo.ShapeKind == AR_TOBJ_MATRIX) {
  6927. if (TargetInfo.ShapeKind == AR_TOBJ_VECTOR && 1 == SourceInfo.uCols) {
  6928. // Handle the column to vector case
  6929. From = m_sema->ImpCastExprToType(From,
  6930. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uCols, 1),
  6931. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6932. } else {
  6933. From = m_sema->ImpCastExprToType(From,
  6934. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6935. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6936. }
  6937. } else {
  6938. DXASSERT(false, "PerformHLSLConversion: Invalid source type for truncation cast");
  6939. }
  6940. }
  6941. __fallthrough;
  6942. case ICK_HLSLVector_Conversion: {
  6943. // 2. Do ShapeKind conversion if necessary
  6944. if (SourceInfo.ShapeKind != TargetInfo.ShapeKind) {
  6945. switch (TargetInfo.ShapeKind) {
  6946. case AR_TOBJ_VECTOR:
  6947. DXASSERT(AR_TOBJ_MATRIX == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  6948. From = m_sema->ImpCastExprToType(From,
  6949. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6950. CK_HLSLMatrixToVectorCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6951. break;
  6952. case AR_TOBJ_MATRIX:
  6953. DXASSERT(AR_TOBJ_VECTOR == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  6954. From = m_sema->ImpCastExprToType(From,
  6955. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6956. CK_HLSLVectorToMatrixCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6957. break;
  6958. case AR_TOBJ_BASIC:
  6959. // Truncation may be followed by cast to scalar
  6960. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6961. break;
  6962. default:
  6963. DXASSERT(false, "otherwise, invalid casting sequence");
  6964. break;
  6965. }
  6966. }
  6967. // 3. Do component type conversion
  6968. if (ICK_Identity != SCS.ComponentConversion) {
  6969. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6970. if (TargetInfo.ShapeKind != AR_TOBJ_BASIC)
  6971. CK = ConvertToComponentCastKind(CK);
  6972. if (CK_Invalid != CK) {
  6973. From = m_sema->ImpCastExprToType(From, targetType, CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6974. }
  6975. }
  6976. break;
  6977. }
  6978. case ICK_Identity:
  6979. // Nothing to do.
  6980. break;
  6981. default:
  6982. DXASSERT(false, "PerformHLSLConversion: Invalid SCS.Second conversion kind");
  6983. }
  6984. return From;
  6985. }
  6986. void HLSLExternalSource::GetConversionForm(
  6987. QualType type,
  6988. bool explicitConversion,
  6989. ArTypeInfo* pTypeInfo)
  6990. {
  6991. //if (!CollectInfo(AR_TINFO_ALLOW_ALL, pTypeInfo))
  6992. CollectInfo(type, pTypeInfo);
  6993. // The fxc implementation reported pTypeInfo->ShapeKind separately in an output argument,
  6994. // but that value is only used for pointer conversions.
  6995. // When explicitly converting types complex aggregates can be treated
  6996. // as vectors if they are entirely numeric.
  6997. switch (pTypeInfo->ShapeKind)
  6998. {
  6999. case AR_TOBJ_COMPOUND:
  7000. case AR_TOBJ_ARRAY:
  7001. if (explicitConversion && IsTypeNumeric(type, &pTypeInfo->uTotalElts))
  7002. {
  7003. pTypeInfo->ShapeKind = AR_TOBJ_VECTOR;
  7004. }
  7005. else
  7006. {
  7007. pTypeInfo->ShapeKind = AR_TOBJ_COMPOUND;
  7008. }
  7009. DXASSERT_NOMSG(pTypeInfo->uRows == 1);
  7010. pTypeInfo->uCols = pTypeInfo->uTotalElts;
  7011. break;
  7012. case AR_TOBJ_VECTOR:
  7013. case AR_TOBJ_MATRIX:
  7014. // Convert 1x1 types to scalars.
  7015. if (pTypeInfo->uCols == 1 && pTypeInfo->uRows == 1)
  7016. {
  7017. pTypeInfo->ShapeKind = AR_TOBJ_BASIC;
  7018. }
  7019. break;
  7020. default:
  7021. // Only convertable shapekinds are relevant.
  7022. break;
  7023. }
  7024. }
  7025. static
  7026. bool HandleVoidConversion(QualType source, QualType target, bool explicitConversion, _Out_ bool* allowed)
  7027. {
  7028. DXASSERT_NOMSG(allowed != nullptr);
  7029. bool applicable = true;
  7030. *allowed = true;
  7031. if (explicitConversion) {
  7032. // (void) non-void
  7033. if (target->isVoidType()) {
  7034. DXASSERT_NOMSG(*allowed);
  7035. }
  7036. // (non-void) void
  7037. else if (source->isVoidType()) {
  7038. *allowed = false;
  7039. }
  7040. else {
  7041. applicable = false;
  7042. }
  7043. }
  7044. else {
  7045. // (void) void
  7046. if (source->isVoidType() && target->isVoidType()) {
  7047. DXASSERT_NOMSG(*allowed);
  7048. }
  7049. // (void) non-void, (non-void) void
  7050. else if (source->isVoidType() || target->isVoidType()) {
  7051. *allowed = false;
  7052. }
  7053. else {
  7054. applicable = false;
  7055. }
  7056. }
  7057. return applicable;
  7058. }
  7059. static bool ConvertDimensions(ArTypeInfo TargetInfo, ArTypeInfo SourceInfo,
  7060. ImplicitConversionKind &Second,
  7061. TYPE_CONVERSION_REMARKS &Remarks) {
  7062. // The rules for aggregate conversions are:
  7063. // 1. A scalar can be replicated to any layout.
  7064. // 2. Any type may be truncated to anything else with one component.
  7065. // 3. A vector may be truncated to a smaller vector.
  7066. // 4. A matrix may be truncated to a smaller matrix.
  7067. // 5. The result of a vector and a matrix is:
  7068. // a. If the matrix has one row it's a vector-sized
  7069. // piece of the row.
  7070. // b. If the matrix has one column it's a vector-sized
  7071. // piece of the column.
  7072. // c. Otherwise the number of elements in the vector
  7073. // and matrix must match and the result is the vector.
  7074. // 6. The result of a matrix and a vector is similar to #5.
  7075. switch (TargetInfo.ShapeKind) {
  7076. case AR_TOBJ_BASIC:
  7077. switch (SourceInfo.ShapeKind)
  7078. {
  7079. case AR_TOBJ_BASIC:
  7080. Second = ICK_Identity;
  7081. break;
  7082. case AR_TOBJ_VECTOR:
  7083. if (1 < SourceInfo.uCols)
  7084. Second = ICK_HLSLVector_Truncation;
  7085. else
  7086. Second = ICK_HLSLVector_Scalar;
  7087. break;
  7088. case AR_TOBJ_MATRIX:
  7089. if (1 < SourceInfo.uRows * SourceInfo.uCols)
  7090. Second = ICK_HLSLVector_Truncation;
  7091. else
  7092. Second = ICK_HLSLVector_Scalar;
  7093. break;
  7094. default:
  7095. return false;
  7096. }
  7097. break;
  7098. case AR_TOBJ_VECTOR:
  7099. switch (SourceInfo.ShapeKind)
  7100. {
  7101. case AR_TOBJ_BASIC:
  7102. // Conversions between scalars and aggregates are always supported.
  7103. Second = ICK_HLSLVector_Splat;
  7104. break;
  7105. case AR_TOBJ_VECTOR:
  7106. if (TargetInfo.uCols > SourceInfo.uCols) {
  7107. if (SourceInfo.uCols == 1) {
  7108. Second = ICK_HLSLVector_Splat;
  7109. }
  7110. else {
  7111. return false;
  7112. }
  7113. }
  7114. else if (TargetInfo.uCols < SourceInfo.uCols) {
  7115. Second = ICK_HLSLVector_Truncation;
  7116. }
  7117. else {
  7118. Second = ICK_Identity;
  7119. }
  7120. break;
  7121. case AR_TOBJ_MATRIX: {
  7122. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  7123. if (1 == SourceComponents && TargetInfo.uCols != 1) {
  7124. // splat: matrix<[..], 1, 1> -> vector<[..], O>
  7125. Second = ICK_HLSLVector_Splat;
  7126. }
  7127. else if (1 == SourceInfo.uRows || 1 == SourceInfo.uCols) {
  7128. // cases for: matrix<[..], M, N> -> vector<[..], O>, where N == 1 or M == 1
  7129. if (TargetInfo.uCols > SourceComponents) // illegal: O > N*M
  7130. return false;
  7131. else if (TargetInfo.uCols < SourceComponents) // truncation: O < N*M
  7132. Second = ICK_HLSLVector_Truncation;
  7133. else // equalivalent: O == N*M
  7134. Second = ICK_HLSLVector_Conversion;
  7135. }
  7136. else if (TargetInfo.uCols == 1 && SourceComponents > 1) {
  7137. Second = ICK_HLSLVector_Truncation;
  7138. }
  7139. else if (TargetInfo.uCols != SourceComponents) {
  7140. // illegal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O != N*M
  7141. return false;
  7142. }
  7143. else {
  7144. // legal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O == N*M
  7145. Second = ICK_HLSLVector_Conversion;
  7146. }
  7147. break;
  7148. }
  7149. default:
  7150. return false;
  7151. }
  7152. break;
  7153. case AR_TOBJ_MATRIX: {
  7154. UINT TargetComponents = TargetInfo.uRows * TargetInfo.uCols;
  7155. switch (SourceInfo.ShapeKind)
  7156. {
  7157. case AR_TOBJ_BASIC:
  7158. // Conversions between scalars and aggregates are always supported.
  7159. Second = ICK_HLSLVector_Splat;
  7160. break;
  7161. case AR_TOBJ_VECTOR: {
  7162. // We can only convert vector to matrix in following cases:
  7163. // - splat from vector<...,1>
  7164. // - same number of components
  7165. // - one target component (truncate to scalar)
  7166. // - matrix has one row or one column, and fewer components (truncation)
  7167. // Other cases disallowed even if implicitly convertable in two steps (truncation+conversion).
  7168. if (1 == SourceInfo.uCols && TargetComponents != 1) {
  7169. // splat: vector<[..], 1> -> matrix<[..], M, N>
  7170. Second = ICK_HLSLVector_Splat;
  7171. }
  7172. else if (TargetComponents == SourceInfo.uCols) {
  7173. // legal: vector<[..], O> -> matrix<[..], M, N> where N != 1 and M != 1 and O == N*M
  7174. Second = ICK_HLSLVector_Conversion;
  7175. }
  7176. else if (1 == TargetComponents) {
  7177. // truncate to scalar: matrix<[..], 1, 1>
  7178. Second = ICK_HLSLVector_Truncation;
  7179. }
  7180. else if ((1 == TargetInfo.uRows || 1 == TargetInfo.uCols) &&
  7181. TargetComponents < SourceInfo.uCols) {
  7182. Second = ICK_HLSLVector_Truncation;
  7183. }
  7184. else {
  7185. // illegal: change in components without going to or from scalar equivalent
  7186. return false;
  7187. }
  7188. break;
  7189. }
  7190. case AR_TOBJ_MATRIX: {
  7191. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  7192. if (1 == SourceComponents && TargetComponents != 1) {
  7193. // splat: matrix<[..], 1, 1> -> matrix<[..], M, N>
  7194. Second = ICK_HLSLVector_Splat;
  7195. }
  7196. else if (TargetComponents == 1) {
  7197. Second = ICK_HLSLVector_Truncation;
  7198. }
  7199. else if (TargetInfo.uRows > SourceInfo.uRows || TargetInfo.uCols > SourceInfo.uCols) {
  7200. return false;
  7201. }
  7202. else if (TargetInfo.uRows < SourceInfo.uRows || TargetInfo.uCols < SourceInfo.uCols) {
  7203. Second = ICK_HLSLVector_Truncation;
  7204. }
  7205. else {
  7206. Second = ICK_Identity;
  7207. }
  7208. break;
  7209. }
  7210. default:
  7211. return false;
  7212. }
  7213. break;
  7214. }
  7215. case AR_TOBJ_STRING:
  7216. if (SourceInfo.ShapeKind == AR_TOBJ_STRING) {
  7217. Second = ICK_Identity;
  7218. break;
  7219. }
  7220. else {
  7221. return false;
  7222. }
  7223. default:
  7224. return false;
  7225. }
  7226. if (TargetInfo.uTotalElts < SourceInfo.uTotalElts)
  7227. {
  7228. Remarks |= TYPE_CONVERSION_ELT_TRUNCATION;
  7229. }
  7230. return true;
  7231. }
  7232. static bool ConvertComponent(ArTypeInfo TargetInfo, ArTypeInfo SourceInfo,
  7233. ImplicitConversionKind &ComponentConversion,
  7234. TYPE_CONVERSION_REMARKS &Remarks) {
  7235. // Conversion to/from unknown types not supported.
  7236. if (TargetInfo.EltKind == AR_BASIC_UNKNOWN ||
  7237. SourceInfo.EltKind == AR_BASIC_UNKNOWN) {
  7238. return false;
  7239. }
  7240. bool precisionLoss = false;
  7241. if (GET_BASIC_BITS(TargetInfo.EltKind) != 0 &&
  7242. GET_BASIC_BITS(TargetInfo.EltKind) <
  7243. GET_BASIC_BITS(SourceInfo.EltKind))
  7244. {
  7245. precisionLoss = true;
  7246. Remarks |= TYPE_CONVERSION_PRECISION_LOSS;
  7247. }
  7248. // enum -> enum not allowed
  7249. if ((SourceInfo.EltKind == AR_BASIC_ENUM &&
  7250. TargetInfo.EltKind == AR_BASIC_ENUM) ||
  7251. SourceInfo.EltKind == AR_BASIC_ENUM_CLASS ||
  7252. TargetInfo.EltKind == AR_BASIC_ENUM_CLASS) {
  7253. return false;
  7254. }
  7255. if (SourceInfo.EltKind != TargetInfo.EltKind)
  7256. {
  7257. if (IS_BASIC_BOOL(TargetInfo.EltKind))
  7258. {
  7259. ComponentConversion = ICK_Boolean_Conversion;
  7260. }
  7261. else if (IS_BASIC_ENUM(TargetInfo.EltKind))
  7262. {
  7263. // conversion to enum type not allowed
  7264. return false;
  7265. }
  7266. else if (IS_BASIC_ENUM(SourceInfo.EltKind))
  7267. {
  7268. // enum -> int/float
  7269. ComponentConversion = ICK_Integral_Conversion;
  7270. }
  7271. else if (TargetInfo.EltKind == AR_OBJECT_STRING)
  7272. {
  7273. if (SourceInfo.EltKind == AR_OBJECT_STRING_LITERAL) {
  7274. ComponentConversion = ICK_Array_To_Pointer;
  7275. }
  7276. else
  7277. {
  7278. return false;
  7279. }
  7280. }
  7281. else
  7282. {
  7283. bool targetIsInt = IS_BASIC_AINT(TargetInfo.EltKind);
  7284. if (IS_BASIC_AINT(SourceInfo.EltKind))
  7285. {
  7286. if (targetIsInt)
  7287. {
  7288. ComponentConversion = precisionLoss ? ICK_Integral_Conversion : ICK_Integral_Promotion;
  7289. }
  7290. else
  7291. {
  7292. ComponentConversion = ICK_Floating_Integral;
  7293. }
  7294. }
  7295. else if (IS_BASIC_FLOAT(SourceInfo.EltKind))
  7296. {
  7297. if (targetIsInt)
  7298. {
  7299. ComponentConversion = ICK_Floating_Integral;
  7300. }
  7301. else
  7302. {
  7303. ComponentConversion = precisionLoss ? ICK_Floating_Conversion : ICK_Floating_Promotion;
  7304. }
  7305. }
  7306. else if (IS_BASIC_BOOL(SourceInfo.EltKind)) {
  7307. if (targetIsInt)
  7308. ComponentConversion = ICK_Integral_Conversion;
  7309. else
  7310. ComponentConversion = ICK_Floating_Integral;
  7311. }
  7312. }
  7313. }
  7314. return true;
  7315. }
  7316. _Use_decl_annotations_
  7317. bool HLSLExternalSource::CanConvert(
  7318. SourceLocation loc,
  7319. Expr* sourceExpr,
  7320. QualType target,
  7321. bool explicitConversion,
  7322. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  7323. _Inout_opt_ StandardConversionSequence* standard)
  7324. {
  7325. UINT uTSize, uSSize;
  7326. bool SourceIsAggregate, TargetIsAggregate; // Early declarations due to gotos below
  7327. DXASSERT_NOMSG(sourceExpr != nullptr);
  7328. DXASSERT_NOMSG(!target.isNull());
  7329. // Implements the semantics of ArType::CanConvertTo.
  7330. TYPE_CONVERSION_FLAGS Flags = explicitConversion ? TYPE_CONVERSION_EXPLICIT : TYPE_CONVERSION_DEFAULT;
  7331. TYPE_CONVERSION_REMARKS Remarks = TYPE_CONVERSION_NONE;
  7332. QualType source = sourceExpr->getType();
  7333. // Cannot cast function type.
  7334. if (source->isFunctionType())
  7335. return false;
  7336. // Convert to an r-value to begin with, with an exception for strings
  7337. // since they are not first-class values and we want to preserve them as literals.
  7338. bool needsLValueToRValue = sourceExpr->isLValue() && !target->isLValueReferenceType()
  7339. && sourceExpr->getStmtClass() != Expr::StringLiteralClass;
  7340. bool targetRef = target->isReferenceType();
  7341. // Initialize the output standard sequence if available.
  7342. if (standard != nullptr) {
  7343. // Set up a no-op conversion, other than lvalue to rvalue - HLSL does not support references.
  7344. standard->setAsIdentityConversion();
  7345. if (needsLValueToRValue) {
  7346. standard->First = ICK_Lvalue_To_Rvalue;
  7347. }
  7348. standard->setFromType(source);
  7349. standard->setAllToTypes(target);
  7350. }
  7351. source = GetStructuralForm(source);
  7352. target = GetStructuralForm(target);
  7353. // Temporary conversion kind tracking which will be used/fixed up at the end
  7354. ImplicitConversionKind Second = ICK_Identity;
  7355. ImplicitConversionKind ComponentConversion = ICK_Identity;
  7356. // Identical types require no conversion.
  7357. if (source == target) {
  7358. Remarks = TYPE_CONVERSION_IDENTICAL;
  7359. goto lSuccess;
  7360. }
  7361. // Trivial cases for void.
  7362. bool allowed;
  7363. if (HandleVoidConversion(source, target, explicitConversion, &allowed)) {
  7364. if (allowed) {
  7365. Remarks = target->isVoidType() ? TYPE_CONVERSION_TO_VOID : Remarks;
  7366. goto lSuccess;
  7367. }
  7368. else {
  7369. return false;
  7370. }
  7371. }
  7372. ArTypeInfo TargetInfo, SourceInfo;
  7373. CollectInfo(target, &TargetInfo);
  7374. CollectInfo(source, &SourceInfo);
  7375. uTSize = TargetInfo.uTotalElts;
  7376. uSSize = SourceInfo.uTotalElts;
  7377. // TODO: TYPE_CONVERSION_BY_REFERENCE does not seem possible here
  7378. // are we missing cases?
  7379. if ((Flags & TYPE_CONVERSION_BY_REFERENCE) != 0 && uTSize != uSSize) {
  7380. return false;
  7381. }
  7382. // Structure cast.
  7383. SourceIsAggregate = SourceInfo.ShapeKind == AR_TOBJ_COMPOUND || SourceInfo.ShapeKind == AR_TOBJ_ARRAY;
  7384. TargetIsAggregate = TargetInfo.ShapeKind == AR_TOBJ_COMPOUND || TargetInfo.ShapeKind == AR_TOBJ_ARRAY;
  7385. if (SourceIsAggregate || TargetIsAggregate) {
  7386. // For implicit conversions, FXC treats arrays the same as structures
  7387. // and rejects conversions between them and numeric types
  7388. if (!explicitConversion && SourceIsAggregate != TargetIsAggregate)
  7389. {
  7390. return false;
  7391. }
  7392. // Structure to structure cases
  7393. const RecordType *targetRT = dyn_cast<RecordType>(target);
  7394. const RecordType *sourceRT = dyn_cast<RecordType>(source);
  7395. if (targetRT && sourceRT) {
  7396. RecordDecl *targetRD = targetRT->getDecl();
  7397. RecordDecl *sourceRD = sourceRT->getDecl();
  7398. if (sourceRT && targetRT) {
  7399. if (targetRD == sourceRD) {
  7400. Second = ICK_Flat_Conversion;
  7401. goto lSuccess;
  7402. }
  7403. const CXXRecordDecl* targetCXXRD = dyn_cast<CXXRecordDecl>(targetRD);
  7404. const CXXRecordDecl* sourceCXXRD = dyn_cast<CXXRecordDecl>(sourceRD);
  7405. if (targetCXXRD && sourceCXXRD && sourceCXXRD->isDerivedFrom(targetCXXRD)) {
  7406. Second = ICK_HLSL_Derived_To_Base;
  7407. goto lSuccess;
  7408. }
  7409. }
  7410. }
  7411. // Handle explicit splats from single element numerical types (scalars, vector1s and matrix1x1s) to aggregate types.
  7412. if (explicitConversion) {
  7413. const BuiltinType *sourceSingleElementBuiltinType = source->getAs<BuiltinType>();
  7414. if (sourceSingleElementBuiltinType == nullptr
  7415. && hlsl::IsHLSLVecMatType(source)
  7416. && hlsl::GetElementCount(source) == 1) {
  7417. sourceSingleElementBuiltinType = hlsl::GetElementTypeOrType(source)->getAs<BuiltinType>();
  7418. }
  7419. // We can only splat to target types that do not contain object/resource types
  7420. if (sourceSingleElementBuiltinType != nullptr && hlsl::IsHLSLNumericOrAggregateOfNumericType(target)) {
  7421. BuiltinType::Kind kind = sourceSingleElementBuiltinType->getKind();
  7422. switch (kind) {
  7423. case BuiltinType::Kind::UInt:
  7424. case BuiltinType::Kind::Int:
  7425. case BuiltinType::Kind::Float:
  7426. case BuiltinType::Kind::LitFloat:
  7427. case BuiltinType::Kind::LitInt:
  7428. Second = ICK_Flat_Conversion;
  7429. goto lSuccess;
  7430. default:
  7431. // Only flat conversion kinds are relevant.
  7432. break;
  7433. }
  7434. }
  7435. }
  7436. FlattenedTypeIterator::ComparisonResult result =
  7437. FlattenedTypeIterator::CompareTypes(*this, loc, loc, target, source);
  7438. if (!result.CanConvertElements) {
  7439. return false;
  7440. }
  7441. // Only allow scalar to compound or array with explicit cast
  7442. if (result.IsConvertibleAndLeftLonger()) {
  7443. if (!explicitConversion || SourceInfo.ShapeKind != AR_TOBJ_SCALAR) {
  7444. return false;
  7445. }
  7446. }
  7447. // Assignment is valid if elements are exactly the same in type and size; if
  7448. // an explicit conversion is being done, we accept converted elements and a
  7449. // longer right-hand sequence.
  7450. if (!explicitConversion &&
  7451. (!result.AreElementsEqual || result.IsRightLonger()))
  7452. {
  7453. return false;
  7454. }
  7455. Second = ICK_Flat_Conversion;
  7456. goto lSuccess;
  7457. }
  7458. // Cast from Resource to Object types.
  7459. if (SourceInfo.EltKind == AR_OBJECT_RESOURCE) {
  7460. if (TargetInfo.ShapeKind == AR_TOBJ_OBJECT) {
  7461. Second = ICK_Flat_Conversion;
  7462. goto lSuccess;
  7463. }
  7464. }
  7465. // Convert scalar/vector/matrix dimensions
  7466. if (!ConvertDimensions(TargetInfo, SourceInfo, Second, Remarks))
  7467. return false;
  7468. // Convert component type
  7469. if (!ConvertComponent(TargetInfo, SourceInfo, ComponentConversion, Remarks))
  7470. return false;
  7471. lSuccess:
  7472. if (standard)
  7473. {
  7474. if (sourceExpr->isLValue())
  7475. {
  7476. if (needsLValueToRValue) {
  7477. // We don't need LValueToRValue cast before casting a derived object
  7478. // to its base.
  7479. if (Second == ICK_HLSL_Derived_To_Base) {
  7480. standard->First = ICK_Identity;
  7481. } else {
  7482. standard->First = ICK_Lvalue_To_Rvalue;
  7483. }
  7484. } else {
  7485. switch (Second)
  7486. {
  7487. case ICK_NoReturn_Adjustment:
  7488. case ICK_Vector_Conversion:
  7489. case ICK_Vector_Splat:
  7490. DXASSERT(false, "We shouldn't be producing these implicit conversion kinds");
  7491. case ICK_Flat_Conversion:
  7492. case ICK_HLSLVector_Splat:
  7493. standard->First = ICK_Lvalue_To_Rvalue;
  7494. break;
  7495. default:
  7496. // Only flat and splat conversions handled.
  7497. break;
  7498. }
  7499. switch (ComponentConversion)
  7500. {
  7501. case ICK_Integral_Promotion:
  7502. case ICK_Integral_Conversion:
  7503. case ICK_Floating_Promotion:
  7504. case ICK_Floating_Conversion:
  7505. case ICK_Floating_Integral:
  7506. case ICK_Boolean_Conversion:
  7507. standard->First = ICK_Lvalue_To_Rvalue;
  7508. break;
  7509. case ICK_Array_To_Pointer:
  7510. standard->First = ICK_Array_To_Pointer;
  7511. break;
  7512. default:
  7513. // Only potential assignments above covered.
  7514. break;
  7515. }
  7516. }
  7517. }
  7518. // Finally fix up the cases for scalar->scalar component conversion, and
  7519. // identity vector/matrix component conversion
  7520. if (ICK_Identity != ComponentConversion) {
  7521. if (Second == ICK_Identity) {
  7522. if (TargetInfo.ShapeKind == AR_TOBJ_BASIC) {
  7523. // Scalar to scalar type conversion, use normal mechanism (Second)
  7524. Second = ComponentConversion;
  7525. ComponentConversion = ICK_Identity;
  7526. }
  7527. else if (TargetInfo.ShapeKind != AR_TOBJ_STRING) {
  7528. // vector or matrix dimensions are not being changed, but component type
  7529. // is being converted, so change Second to signal the conversion
  7530. Second = ICK_HLSLVector_Conversion;
  7531. }
  7532. }
  7533. }
  7534. standard->Second = Second;
  7535. standard->ComponentConversion = ComponentConversion;
  7536. // For conversion which change to RValue but targeting reference type
  7537. // Hold the conversion to codeGen
  7538. if (targetRef && standard->First == ICK_Lvalue_To_Rvalue) {
  7539. standard->First = ICK_Identity;
  7540. standard->Second = ICK_Identity;
  7541. }
  7542. }
  7543. AssignOpt(Remarks, remarks);
  7544. return true;
  7545. }
  7546. bool HLSLExternalSource::ValidateTypeRequirements(
  7547. SourceLocation loc,
  7548. ArBasicKind elementKind,
  7549. ArTypeObjectKind objectKind,
  7550. bool requiresIntegrals,
  7551. bool requiresNumerics)
  7552. {
  7553. if (elementKind == AR_BASIC_DEPENDENT)
  7554. return true;
  7555. if (requiresIntegrals || requiresNumerics)
  7556. {
  7557. if (!IsObjectKindPrimitiveAggregate(objectKind))
  7558. {
  7559. m_sema->Diag(loc, diag::err_hlsl_requires_non_aggregate);
  7560. return false;
  7561. }
  7562. }
  7563. if (requiresIntegrals)
  7564. {
  7565. if (!IsBasicKindIntegral(elementKind))
  7566. {
  7567. m_sema->Diag(loc, diag::err_hlsl_requires_int_or_uint);
  7568. return false;
  7569. }
  7570. }
  7571. else if (requiresNumerics)
  7572. {
  7573. if (!IsBasicKindNumeric(elementKind))
  7574. {
  7575. m_sema->Diag(loc, diag::err_hlsl_requires_numeric);
  7576. return false;
  7577. }
  7578. }
  7579. return true;
  7580. }
  7581. bool HLSLExternalSource::ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind)
  7582. {
  7583. bool isValid = true;
  7584. if (IsBuiltInObjectType(type)) {
  7585. m_sema->Diag(loc, diag::err_hlsl_unsupported_builtin_op) << type;
  7586. isValid = false;
  7587. }
  7588. if (kind == AR_TOBJ_COMPOUND) {
  7589. m_sema->Diag(loc, diag::err_hlsl_unsupported_struct_op) << type;
  7590. isValid = false;
  7591. }
  7592. return isValid;
  7593. }
  7594. HRESULT HLSLExternalSource::CombineDimensions(
  7595. QualType leftType, QualType rightType, QualType *resultType,
  7596. ImplicitConversionKind &convKind, TYPE_CONVERSION_REMARKS &Remarks)
  7597. {
  7598. ArTypeInfo leftInfo, rightInfo;
  7599. CollectInfo(leftType, &leftInfo);
  7600. CollectInfo(rightType, &rightInfo);
  7601. // Prefer larger, or left if same.
  7602. if (leftInfo.uTotalElts >= rightInfo.uTotalElts) {
  7603. if (ConvertDimensions(leftInfo, rightInfo, convKind, Remarks))
  7604. *resultType = leftType;
  7605. else if (ConvertDimensions(rightInfo, leftInfo, convKind, Remarks))
  7606. *resultType = rightType;
  7607. else
  7608. return E_FAIL;
  7609. } else {
  7610. if (ConvertDimensions(rightInfo, leftInfo, convKind, Remarks))
  7611. *resultType = rightType;
  7612. else if (ConvertDimensions(leftInfo, rightInfo, convKind, Remarks))
  7613. *resultType = leftType;
  7614. else
  7615. return E_FAIL;
  7616. }
  7617. return S_OK;
  7618. }
  7619. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  7620. /// <param name="OpLoc">Source location for operator.</param>
  7621. /// <param name="Opc">Kind of binary operator.</param>
  7622. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  7623. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  7624. /// <param name="ResultTy">Result type for operator expression.</param>
  7625. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  7626. /// <param name="CompResultTy">Type of computation result.</param>
  7627. void HLSLExternalSource::CheckBinOpForHLSL(
  7628. SourceLocation OpLoc,
  7629. BinaryOperatorKind Opc,
  7630. ExprResult& LHS,
  7631. ExprResult& RHS,
  7632. QualType& ResultTy,
  7633. QualType& CompLHSTy,
  7634. QualType& CompResultTy)
  7635. {
  7636. // At the start, none of the output types should be valid.
  7637. DXASSERT_NOMSG(ResultTy.isNull());
  7638. DXASSERT_NOMSG(CompLHSTy.isNull());
  7639. DXASSERT_NOMSG(CompResultTy.isNull());
  7640. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  7641. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  7642. // If either expression is invalid to begin with, propagate that.
  7643. if (LHS.isInvalid() || RHS.isInvalid()) {
  7644. return;
  7645. }
  7646. // TODO: re-review the Check** in Clang and add equivalent diagnostics if/as needed, possibly after conversions
  7647. // Handle Assign and Comma operators and return
  7648. switch (Opc)
  7649. {
  7650. case BO_AddAssign:
  7651. case BO_AndAssign:
  7652. case BO_DivAssign:
  7653. case BO_MulAssign:
  7654. case BO_RemAssign:
  7655. case BO_ShlAssign:
  7656. case BO_ShrAssign:
  7657. case BO_SubAssign:
  7658. case BO_OrAssign:
  7659. case BO_XorAssign: {
  7660. extern bool CheckForModifiableLvalue(Expr * E, SourceLocation Loc,
  7661. Sema & S);
  7662. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  7663. return;
  7664. }
  7665. } break;
  7666. case BO_Assign: {
  7667. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  7668. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  7669. return;
  7670. }
  7671. bool complained = false;
  7672. ResultTy = LHS.get()->getType();
  7673. if (m_sema->DiagnoseAssignmentResult(Sema::AssignConvertType::Compatible,
  7674. OpLoc, ResultTy, RHS.get()->getType(), RHS.get(),
  7675. Sema::AssignmentAction::AA_Assigning, &complained)) {
  7676. return;
  7677. }
  7678. StandardConversionSequence standard;
  7679. if (!ValidateCast(OpLoc, RHS.get(), ResultTy,
  7680. ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  7681. return;
  7682. }
  7683. if (RHS.get()->isLValue()) {
  7684. standard.First = ICK_Lvalue_To_Rvalue;
  7685. }
  7686. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy,
  7687. standard, Sema::AA_Converting, Sema::CCK_ImplicitConversion);
  7688. return;
  7689. }
  7690. break;
  7691. case BO_Comma:
  7692. // C performs conversions, C++ doesn't but still checks for type completeness.
  7693. // There are also diagnostics for improper comma use.
  7694. // In the HLSL case these cases don't apply or simply aren't surfaced.
  7695. ResultTy = RHS.get()->getType();
  7696. return;
  7697. default:
  7698. // Only assign and comma operations handled.
  7699. break;
  7700. }
  7701. // Leave this diagnostic for last to emulate fxc behavior.
  7702. bool isCompoundAssignment = BinaryOperatorKindIsCompoundAssignment(Opc);
  7703. bool unsupportedBoolLvalue = isCompoundAssignment &&
  7704. !BinaryOperatorKindIsCompoundAssignmentForBool(Opc) &&
  7705. GetTypeElementKind(LHS.get()->getType()) == AR_BASIC_BOOL;
  7706. // Turn operand inputs into r-values.
  7707. QualType LHSTypeAsPossibleLValue = LHS.get()->getType();
  7708. if (!isCompoundAssignment) {
  7709. LHS = m_sema->DefaultLvalueConversion(LHS.get());
  7710. }
  7711. RHS = m_sema->DefaultLvalueConversion(RHS.get());
  7712. if (LHS.isInvalid() || RHS.isInvalid()) {
  7713. return;
  7714. }
  7715. // Gather type info
  7716. QualType leftType = GetStructuralForm(LHS.get()->getType());
  7717. QualType rightType = GetStructuralForm(RHS.get()->getType());
  7718. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  7719. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  7720. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  7721. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  7722. // Validate type requirements
  7723. {
  7724. bool requiresNumerics = BinaryOperatorKindRequiresNumeric(Opc);
  7725. bool requiresIntegrals = BinaryOperatorKindRequiresIntegrals(Opc);
  7726. if (!ValidateTypeRequirements(OpLoc, leftElementKind, leftObjectKind, requiresIntegrals, requiresNumerics)) {
  7727. return;
  7728. }
  7729. if (!ValidateTypeRequirements(OpLoc, rightElementKind, rightObjectKind, requiresIntegrals, requiresNumerics)) {
  7730. return;
  7731. }
  7732. }
  7733. if (unsupportedBoolLvalue) {
  7734. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  7735. return;
  7736. }
  7737. // We don't support binary operators on built-in object types other than assignment or commas.
  7738. {
  7739. DXASSERT(Opc != BO_Assign, "otherwise this wasn't handled as an early exit");
  7740. DXASSERT(Opc != BO_Comma, "otherwise this wasn't handled as an early exit");
  7741. bool isValid;
  7742. isValid = ValidatePrimitiveTypeForOperand(OpLoc, leftType, leftObjectKind);
  7743. if (leftType != rightType && !ValidatePrimitiveTypeForOperand(OpLoc, rightType, rightObjectKind)) {
  7744. isValid = false;
  7745. }
  7746. if (!isValid) {
  7747. return;
  7748. }
  7749. }
  7750. // We don't support equality comparisons on arrays.
  7751. if ((Opc == BO_EQ || Opc == BO_NE) && (leftObjectKind == AR_TOBJ_ARRAY || rightObjectKind == AR_TOBJ_ARRAY)) {
  7752. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_array_equality_op);
  7753. return;
  7754. }
  7755. // Combine element types for computation.
  7756. ArBasicKind resultElementKind = leftElementKind;
  7757. {
  7758. if (BinaryOperatorKindIsLogical(Opc)) {
  7759. resultElementKind = AR_BASIC_BOOL;
  7760. } else if (!BinaryOperatorKindIsBitwiseShift(Opc) && leftElementKind != rightElementKind) {
  7761. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind)) {
  7762. m_sema->Diag(OpLoc, diag::err_hlsl_type_mismatch);
  7763. return;
  7764. }
  7765. } else if (BinaryOperatorKindIsBitwiseShift(Opc) &&
  7766. (resultElementKind == AR_BASIC_LITERAL_INT ||
  7767. resultElementKind == AR_BASIC_LITERAL_FLOAT) &&
  7768. rightElementKind != AR_BASIC_LITERAL_INT &&
  7769. rightElementKind != AR_BASIC_LITERAL_FLOAT) {
  7770. // For case like 1<<x.
  7771. resultElementKind = AR_BASIC_UINT32;
  7772. } else if (resultElementKind == AR_BASIC_BOOL &&
  7773. BinaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  7774. resultElementKind = AR_BASIC_INT32;
  7775. }
  7776. // The following combines the selected/combined element kind above with
  7777. // the dimensions that are legal to implicitly cast. This means that
  7778. // element kind may be taken from one side and the dimensions from the
  7779. // other.
  7780. if (!isCompoundAssignment) {
  7781. // Legal dimension combinations are identical, splat, and truncation.
  7782. // ResultTy will be set to whichever type can be converted to, if legal,
  7783. // with preference for leftType if both are possible.
  7784. if (FAILED(CombineDimensions(LHS.get()->getType(), RHS.get()->getType(), &ResultTy))) {
  7785. // Just choose leftType, and allow ValidateCast to catch this later
  7786. ResultTy = LHS.get()->getType();
  7787. }
  7788. } else {
  7789. ResultTy = LHS.get()->getType();
  7790. }
  7791. // Here, element kind is combined with dimensions for computation type, if different.
  7792. if (resultElementKind != GetTypeElementKind(ResultTy)) {
  7793. UINT rowCount, colCount;
  7794. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7795. ResultTy = NewSimpleAggregateType(GetTypeObjectKind(ResultTy), resultElementKind, 0, rowCount, colCount);
  7796. }
  7797. }
  7798. bool bFailedFirstRHSCast = false;
  7799. // Perform necessary conversion sequences for LHS and RHS
  7800. if (RHS.get()->getType() != ResultTy) {
  7801. StandardConversionSequence standard;
  7802. // Suppress type narrowing or truncation warnings for RHS on bitwise shift, since we only care about the LHS type.
  7803. bool bSuppressWarnings = BinaryOperatorKindIsBitwiseShift(Opc);
  7804. // Suppress errors on compound assignment, since we will vaildate the cast to the final type later.
  7805. bool bSuppressErrors = isCompoundAssignment;
  7806. // If compound assignment, suppress errors until later, but report warning (vector truncation/type narrowing) here.
  7807. if (ValidateCast(SourceLocation(), RHS.get(), ResultTy, ExplicitConversionFalse, bSuppressWarnings, bSuppressErrors, &standard)) {
  7808. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  7809. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  7810. } else if (!isCompoundAssignment) {
  7811. // If compound assignment, validate cast from RHS directly to LHS later, otherwise, fail here.
  7812. ResultTy = QualType();
  7813. return;
  7814. } else {
  7815. bFailedFirstRHSCast = true;
  7816. }
  7817. }
  7818. if (isCompoundAssignment) {
  7819. CompResultTy = ResultTy;
  7820. CompLHSTy = CompResultTy;
  7821. // For a compound operation, C/C++ promotes both types, performs the arithmetic,
  7822. // then converts to the result type and then assigns.
  7823. //
  7824. // So int + float promotes the int to float, does a floating-point addition,
  7825. // then the result becomes and int and is assigned.
  7826. ResultTy = LHSTypeAsPossibleLValue;
  7827. // Validate remainder of cast from computation type to final result type
  7828. StandardConversionSequence standard;
  7829. if (!ValidateCast(SourceLocation(), RHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  7830. ResultTy = QualType();
  7831. return;
  7832. }
  7833. DXASSERT_LOCALVAR(bFailedFirstRHSCast, !bFailedFirstRHSCast,
  7834. "otherwise, hit compound assign case that failed RHS -> CompResultTy cast, but succeeded RHS -> LHS cast.");
  7835. } else if (LHS.get()->getType() != ResultTy) {
  7836. StandardConversionSequence standard;
  7837. if (ValidateCast(SourceLocation(), LHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  7838. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  7839. LHS = m_sema->PerformImplicitConversion(LHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  7840. } else {
  7841. ResultTy = QualType();
  7842. return;
  7843. }
  7844. }
  7845. if (BinaryOperatorKindIsComparison(Opc) || BinaryOperatorKindIsLogical(Opc))
  7846. {
  7847. DXASSERT(!isCompoundAssignment, "otherwise binary lookup tables are inconsistent");
  7848. // Return bool vector for vector types.
  7849. if (IsVectorType(m_sema, ResultTy)) {
  7850. UINT rowCount, colCount;
  7851. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7852. ResultTy = LookupVectorType(HLSLScalarType::HLSLScalarType_bool, colCount);
  7853. } else if (IsMatrixType(m_sema, ResultTy)) {
  7854. UINT rowCount, colCount;
  7855. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7856. ResultTy = LookupMatrixType(HLSLScalarType::HLSLScalarType_bool, rowCount, colCount);
  7857. } else
  7858. ResultTy = m_context->BoolTy.withConst();
  7859. }
  7860. // Run diagnostics. Some are emulating checks that occur in IR emission in fxc.
  7861. if (Opc == BO_Div || Opc == BO_DivAssign || Opc == BO_Rem || Opc == BO_RemAssign) {
  7862. if (IsBasicKindIntMinPrecision(resultElementKind)) {
  7863. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_div_minint);
  7864. return;
  7865. }
  7866. }
  7867. if (Opc == BO_Rem || Opc == BO_RemAssign) {
  7868. if (resultElementKind == AR_BASIC_FLOAT64) {
  7869. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_mod_double);
  7870. return;
  7871. }
  7872. }
  7873. }
  7874. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  7875. /// <param name="OpLoc">Source location for operator.</param>
  7876. /// <param name="Opc">Kind of operator.</param>
  7877. /// <param name="InputExpr">Input expression to the operator.</param>
  7878. /// <param name="VK">Value kind for resulting expression.</param>
  7879. /// <param name="OK">Object kind for resulting expression.</param>
  7880. /// <returns>The result type for the expression.</returns>
  7881. QualType HLSLExternalSource::CheckUnaryOpForHLSL(
  7882. SourceLocation OpLoc,
  7883. UnaryOperatorKind Opc,
  7884. ExprResult& InputExpr,
  7885. ExprValueKind& VK,
  7886. ExprObjectKind& OK)
  7887. {
  7888. InputExpr = m_sema->CorrectDelayedTyposInExpr(InputExpr);
  7889. if (InputExpr.isInvalid())
  7890. return QualType();
  7891. // Reject unsupported operators * and &
  7892. switch (Opc) {
  7893. case UO_AddrOf:
  7894. case UO_Deref:
  7895. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_operator);
  7896. return QualType();
  7897. default:
  7898. // Only * and & covered.
  7899. break;
  7900. }
  7901. Expr* expr = InputExpr.get();
  7902. if (expr->isTypeDependent())
  7903. return m_context->DependentTy;
  7904. ArBasicKind elementKind = GetTypeElementKind(expr->getType());
  7905. if (UnaryOperatorKindRequiresModifiableValue(Opc)) {
  7906. if (elementKind == AR_BASIC_ENUM) {
  7907. bool isInc = IsIncrementOp(Opc);
  7908. m_sema->Diag(OpLoc, diag::err_increment_decrement_enum) << isInc << expr->getType();
  7909. return QualType();
  7910. }
  7911. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  7912. if (CheckForModifiableLvalue(expr, OpLoc, *m_sema))
  7913. return QualType();
  7914. } else {
  7915. InputExpr = m_sema->DefaultLvalueConversion(InputExpr.get()).get();
  7916. if (InputExpr.isInvalid()) return QualType();
  7917. }
  7918. if (UnaryOperatorKindDisallowsBool(Opc) && IS_BASIC_BOOL(elementKind)) {
  7919. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  7920. return QualType();
  7921. }
  7922. if (UnaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  7923. InputExpr = PromoteToIntIfBool(InputExpr);
  7924. expr = InputExpr.get();
  7925. elementKind = GetTypeElementKind(expr->getType());
  7926. }
  7927. ArTypeObjectKind objectKind = GetTypeObjectKind(expr->getType());
  7928. bool requiresIntegrals = UnaryOperatorKindRequiresIntegrals(Opc);
  7929. bool requiresNumerics = UnaryOperatorKindRequiresNumerics(Opc);
  7930. if (!ValidateTypeRequirements(OpLoc, elementKind, objectKind, requiresIntegrals, requiresNumerics)) {
  7931. return QualType();
  7932. }
  7933. if (Opc == UnaryOperatorKind::UO_Minus) {
  7934. if (IS_BASIC_UINT(Opc)) {
  7935. m_sema->Diag(OpLoc, diag::warn_hlsl_unary_negate_unsigned);
  7936. }
  7937. }
  7938. // By default, the result type is the operand type.
  7939. // Logical not however should cast to a bool.
  7940. QualType resultType = expr->getType();
  7941. if (Opc == UnaryOperatorKind::UO_LNot) {
  7942. UINT rowCount, colCount;
  7943. GetRowsAndColsForAny(expr->getType(), rowCount, colCount);
  7944. resultType = NewSimpleAggregateType(objectKind, AR_BASIC_BOOL, AR_QUAL_CONST, rowCount, colCount);
  7945. StandardConversionSequence standard;
  7946. if (!CanConvert(OpLoc, expr, resultType, false, nullptr, &standard)) {
  7947. m_sema->Diag(OpLoc, diag::err_hlsl_requires_bool_for_not);
  7948. return QualType();
  7949. }
  7950. // Cast argument.
  7951. ExprResult result = m_sema->PerformImplicitConversion(InputExpr.get(), resultType, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  7952. if (result.isUsable()) {
  7953. InputExpr = result.get();
  7954. }
  7955. }
  7956. bool isPrefix = Opc == UO_PreInc || Opc == UO_PreDec;
  7957. if (isPrefix) {
  7958. VK = VK_LValue;
  7959. return resultType;
  7960. }
  7961. else {
  7962. VK = VK_RValue;
  7963. return resultType.getUnqualifiedType();
  7964. }
  7965. }
  7966. clang::QualType HLSLExternalSource::CheckVectorConditional(
  7967. _In_ ExprResult &Cond,
  7968. _In_ ExprResult &LHS,
  7969. _In_ ExprResult &RHS,
  7970. _In_ SourceLocation QuestionLoc)
  7971. {
  7972. Cond = m_sema->CorrectDelayedTyposInExpr(Cond);
  7973. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  7974. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  7975. // If either expression is invalid to begin with, propagate that.
  7976. if (Cond.isInvalid() || LHS.isInvalid() || RHS.isInvalid()) {
  7977. return QualType();
  7978. }
  7979. // Gather type info
  7980. QualType condType = GetStructuralForm(Cond.get()->getType());
  7981. QualType leftType = GetStructuralForm(LHS.get()->getType());
  7982. QualType rightType = GetStructuralForm(RHS.get()->getType());
  7983. ArBasicKind condElementKind = GetTypeElementKind(condType);
  7984. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  7985. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  7986. ArTypeObjectKind condObjectKind = GetTypeObjectKind(condType);
  7987. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  7988. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  7989. QualType ResultTy = leftType;
  7990. bool condIsSimple = condObjectKind == AR_TOBJ_BASIC || condObjectKind == AR_TOBJ_VECTOR || condObjectKind == AR_TOBJ_MATRIX;
  7991. if (!condIsSimple) {
  7992. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_cond_typecheck);
  7993. return QualType();
  7994. }
  7995. UINT rowCountCond, colCountCond;
  7996. GetRowsAndColsForAny(condType, rowCountCond, colCountCond);
  7997. bool leftIsSimple =
  7998. leftObjectKind == AR_TOBJ_BASIC || leftObjectKind == AR_TOBJ_VECTOR ||
  7999. leftObjectKind == AR_TOBJ_MATRIX;
  8000. bool rightIsSimple =
  8001. rightObjectKind == AR_TOBJ_BASIC || rightObjectKind == AR_TOBJ_VECTOR ||
  8002. rightObjectKind == AR_TOBJ_MATRIX;
  8003. if (!leftIsSimple || !rightIsSimple) {
  8004. if (leftObjectKind == AR_TOBJ_OBJECT && leftObjectKind == AR_TOBJ_OBJECT) {
  8005. if (leftType == rightType) {
  8006. return leftType;
  8007. }
  8008. }
  8009. // NOTE: Limiting this operator to working only on basic numeric types.
  8010. // This is due to extremely limited (and even broken) support for any other case.
  8011. // In the future we may decide to support more cases.
  8012. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_typecheck);
  8013. return QualType();
  8014. }
  8015. // Types should be only scalar, vector, or matrix after this point.
  8016. ArBasicKind resultElementKind = leftElementKind;
  8017. // Combine LHS and RHS element types for computation.
  8018. if (leftElementKind != rightElementKind) {
  8019. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind)) {
  8020. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_comptype_mismatch);
  8021. return QualType();
  8022. }
  8023. }
  8024. // Restore left/right type to original to avoid stripping attributed type or typedef type
  8025. leftType = LHS.get()->getType();
  8026. rightType = RHS.get()->getType();
  8027. // Combine LHS and RHS dimensions
  8028. if (FAILED(CombineDimensions(leftType, rightType, &ResultTy))) {
  8029. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_dimensions);
  8030. return QualType();
  8031. }
  8032. UINT rowCount, colCount;
  8033. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  8034. // If result is scalar, use condition dimensions.
  8035. // Otherwise, condition must either match or is scalar, then use result dimensions
  8036. if (rowCount * colCount == 1) {
  8037. rowCount = rowCountCond;
  8038. colCount = colCountCond;
  8039. }
  8040. else if (rowCountCond * colCountCond != 1 && (rowCountCond != rowCount || colCountCond != colCount)) {
  8041. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_dimensions);
  8042. return QualType();
  8043. }
  8044. // Here, element kind is combined with dimensions for result type.
  8045. ResultTy = NewSimpleAggregateType(AR_TOBJ_INVALID, resultElementKind, 0, rowCount, colCount)->getCanonicalTypeInternal();
  8046. // Cast condition to RValue
  8047. if (Cond.get()->isLValue())
  8048. Cond.set(CreateLValueToRValueCast(Cond.get()));
  8049. // Convert condition component type to bool, using result component dimensions
  8050. if (condElementKind != AR_BASIC_BOOL) {
  8051. QualType boolType = NewSimpleAggregateType(AR_TOBJ_INVALID, AR_BASIC_BOOL, 0, rowCount, colCount)->getCanonicalTypeInternal();
  8052. StandardConversionSequence standard;
  8053. if (ValidateCast(SourceLocation(), Cond.get(), boolType, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  8054. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  8055. Cond = m_sema->PerformImplicitConversion(Cond.get(), boolType, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8056. }
  8057. else {
  8058. return QualType();
  8059. }
  8060. }
  8061. // TODO: Is this correct? Does fxc support lvalue return here?
  8062. // Cast LHS/RHS to RValue
  8063. if (LHS.get()->isLValue())
  8064. LHS.set(CreateLValueToRValueCast(LHS.get()));
  8065. if (RHS.get()->isLValue())
  8066. RHS.set(CreateLValueToRValueCast(RHS.get()));
  8067. if (leftType != ResultTy) {
  8068. StandardConversionSequence standard;
  8069. if (ValidateCast(SourceLocation(), LHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  8070. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  8071. LHS = m_sema->PerformImplicitConversion(LHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8072. }
  8073. else {
  8074. return QualType();
  8075. }
  8076. }
  8077. if (rightType != ResultTy) {
  8078. StandardConversionSequence standard;
  8079. if (ValidateCast(SourceLocation(), RHS.get(), ResultTy, ExplicitConversionFalse, SuppressWarningsFalse, SuppressErrorsFalse, &standard)) {
  8080. if (standard.First != ICK_Identity || !standard.isIdentityConversion())
  8081. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  8082. }
  8083. else {
  8084. return QualType();
  8085. }
  8086. }
  8087. return ResultTy;
  8088. }
  8089. // Apply type specifier sign to the given QualType.
  8090. // Other than privmitive int type, only allow shorthand vectors and matrices to be unsigned.
  8091. clang::QualType HLSLExternalSource::ApplyTypeSpecSignToParsedType(
  8092. _In_ clang::QualType &type, _In_ clang::TypeSpecifierSign TSS,
  8093. _In_ clang::SourceLocation Loc) {
  8094. if (TSS == TypeSpecifierSign::TSS_unspecified) {
  8095. return type;
  8096. }
  8097. DXASSERT(TSS != TypeSpecifierSign::TSS_signed, "else signed keyword is supported in HLSL");
  8098. ArTypeObjectKind objKind = GetTypeObjectKind(type);
  8099. if (objKind != AR_TOBJ_VECTOR && objKind != AR_TOBJ_MATRIX &&
  8100. objKind != AR_TOBJ_BASIC && objKind != AR_TOBJ_ARRAY) {
  8101. return type;
  8102. }
  8103. // check if element type is unsigned and check if such vector exists
  8104. // If not create a new one, Make a QualType of the new kind
  8105. ArBasicKind elementKind = GetTypeElementKind(type);
  8106. // Only ints can have signed/unsigend ty
  8107. if (!IS_BASIC_UNSIGNABLE(elementKind)) {
  8108. return type;
  8109. }
  8110. else {
  8111. // Check given TypeSpecifierSign. If unsigned, change int to uint.
  8112. HLSLScalarType scalarType = ScalarTypeForBasic(elementKind);
  8113. HLSLScalarType newScalarType = MakeUnsigned(scalarType);
  8114. // Get new vector types for a given TypeSpecifierSign.
  8115. if (objKind == AR_TOBJ_VECTOR) {
  8116. UINT colCount = GetHLSLVecSize(type);
  8117. TypedefDecl *qts = LookupVectorShorthandType(newScalarType, colCount);
  8118. return m_context->getTypeDeclType(qts);
  8119. } else if (objKind == AR_TOBJ_MATRIX) {
  8120. UINT rowCount, colCount;
  8121. GetRowsAndCols(type, rowCount, colCount);
  8122. TypedefDecl *qts = LookupMatrixShorthandType(newScalarType, rowCount, colCount);
  8123. return m_context->getTypeDeclType(qts);
  8124. } else {
  8125. DXASSERT_NOMSG(objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY);
  8126. return m_scalarTypes[newScalarType];
  8127. }
  8128. }
  8129. }
  8130. Sema::TemplateDeductionResult HLSLExternalSource::DeduceTemplateArgumentsForHLSL(
  8131. FunctionTemplateDecl *FunctionTemplate,
  8132. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  8133. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  8134. {
  8135. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  8136. // Get information about the function we have.
  8137. CXXMethodDecl* functionMethod = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl());
  8138. if (!functionMethod) {
  8139. // standalone function.
  8140. return Sema::TemplateDeductionResult::TDK_Invalid;
  8141. }
  8142. CXXRecordDecl* functionParentRecord = functionMethod->getParent();
  8143. DXASSERT(functionParentRecord != nullptr, "otherwise function is orphaned");
  8144. QualType objectElement = GetFirstElementTypeFromDecl(functionParentRecord);
  8145. QualType functionTemplateTypeArg {};
  8146. if (ExplicitTemplateArgs != nullptr && ExplicitTemplateArgs->size() == 1) {
  8147. const TemplateArgument &firstTemplateArg = (*ExplicitTemplateArgs)[0].getArgument();
  8148. if (firstTemplateArg.getKind() == TemplateArgument::ArgKind::Type)
  8149. functionTemplateTypeArg = firstTemplateArg.getAsType();
  8150. }
  8151. // Handle subscript overloads.
  8152. if (FunctionTemplate->getDeclName() == m_context->DeclarationNames.getCXXOperatorName(OO_Subscript))
  8153. {
  8154. DeclContext* functionTemplateContext = FunctionTemplate->getDeclContext();
  8155. FindStructBasicTypeResult findResult = FindStructBasicType(functionTemplateContext);
  8156. if (!findResult.Found())
  8157. {
  8158. // This might be a nested type. Do a lookup on the parent.
  8159. CXXRecordDecl* parentRecordType = dyn_cast_or_null<CXXRecordDecl>(functionTemplateContext);
  8160. if (parentRecordType == nullptr || parentRecordType->getDeclContext() == nullptr)
  8161. {
  8162. return Sema::TemplateDeductionResult::TDK_Invalid;
  8163. }
  8164. findResult = FindStructBasicType(parentRecordType->getDeclContext());
  8165. if (!findResult.Found())
  8166. {
  8167. return Sema::TemplateDeductionResult::TDK_Invalid;
  8168. }
  8169. DXASSERT(
  8170. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::CXXRecord ||
  8171. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::ClassTemplateSpecialization,
  8172. "otherwise FindStructBasicType should have failed - no other types are allowed");
  8173. objectElement = GetFirstElementTypeFromDecl(
  8174. cast<CXXRecordDecl>(parentRecordType->getDeclContext()));
  8175. }
  8176. Specialization = AddSubscriptSpecialization(FunctionTemplate, objectElement, findResult);
  8177. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  8178. FunctionTemplate->getCanonicalDecl());
  8179. return Sema::TemplateDeductionResult::TDK_Success;
  8180. }
  8181. // Reject overload lookups that aren't identifier-based.
  8182. if (!FunctionTemplate->getDeclName().isIdentifier())
  8183. {
  8184. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  8185. }
  8186. // Find the table of intrinsics based on the object type.
  8187. const HLSL_INTRINSIC* intrinsics = nullptr;
  8188. size_t intrinsicCount = 0;
  8189. const char* objectName = nullptr;
  8190. FindIntrinsicTable(FunctionTemplate->getDeclContext(), &objectName, &intrinsics, &intrinsicCount);
  8191. // user-defined template object.
  8192. if (objectName == nullptr && intrinsics == nullptr) {
  8193. return Sema::TemplateDeductionResult::TDK_Invalid;
  8194. }
  8195. DXASSERT(objectName != nullptr &&
  8196. (intrinsics != nullptr || m_intrinsicTables.size() > 0),
  8197. "otherwise FindIntrinsicTable failed to lookup a valid object, "
  8198. "or the parser let a user-defined template object through");
  8199. // Look for an intrinsic for which we can match arguments.
  8200. std::vector<QualType> argTypes;
  8201. StringRef nameIdentifier = FunctionTemplate->getName();
  8202. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(intrinsics, intrinsicCount, objectName, nameIdentifier, Args.size());
  8203. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(intrinsics, intrinsicCount, IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  8204. while (cursor != end)
  8205. {
  8206. if (!MatchArguments(*cursor, objectElement, functionTemplateTypeArg, Args, &argTypes))
  8207. {
  8208. ++cursor;
  8209. continue;
  8210. }
  8211. // Currently only intrinsic we allow for explicit template arguments are
  8212. // for Load/Store for ByteAddressBuffer/RWByteAddressBuffer
  8213. // TODO: handle template arguments for future intrinsics in a more natural way
  8214. // Check Explicit template arguments
  8215. UINT intrinsicOp = (*cursor)->Op;
  8216. LPCSTR intrinsicName = (*cursor)->pArgs[0].pName;
  8217. bool Is2018 = getSema()->getLangOpts().HLSLVersion >= 2018;
  8218. bool IsBAB =
  8219. objectName == g_ArBasicTypeNames[AR_OBJECT_BYTEADDRESS_BUFFER] ||
  8220. objectName == g_ArBasicTypeNames[AR_OBJECT_RWBYTEADDRESS_BUFFER];
  8221. bool IsBABLoad = IsBAB && intrinsicOp == (UINT)IntrinsicOp::MOP_Load;
  8222. bool IsBABStore = IsBAB && intrinsicOp == (UINT)IntrinsicOp::MOP_Store;
  8223. if (ExplicitTemplateArgs && ExplicitTemplateArgs->size() > 0) {
  8224. bool isLegalTemplate = false;
  8225. SourceLocation Loc = ExplicitTemplateArgs->getLAngleLoc();
  8226. auto TemplateDiag = diag::err_hlsl_intrinsic_template_arg_unsupported;
  8227. if (ExplicitTemplateArgs->size() >= 1 && (IsBABLoad || IsBABStore)) {
  8228. TemplateDiag = diag::err_hlsl_intrinsic_template_arg_requires_2018;
  8229. Loc = (*ExplicitTemplateArgs)[0].getLocation();
  8230. if (Is2018) {
  8231. TemplateDiag = diag::err_hlsl_intrinsic_template_arg_numeric;
  8232. if (ExplicitTemplateArgs->size() == 1
  8233. && !functionTemplateTypeArg.isNull()
  8234. && hlsl::IsHLSLNumericOrAggregateOfNumericType(functionTemplateTypeArg)) {
  8235. isLegalTemplate = true;
  8236. argTypes[0] = functionTemplateTypeArg;
  8237. }
  8238. }
  8239. }
  8240. if (!isLegalTemplate) {
  8241. getSema()->Diag(Loc, TemplateDiag) << intrinsicName;
  8242. return Sema::TemplateDeductionResult::TDK_Invalid;
  8243. }
  8244. } else if (IsBABStore) {
  8245. // Prior to HLSL 2018, Store operation only stored scalar uint.
  8246. if (!Is2018) {
  8247. if (GetNumElements(argTypes[2]) != 1) {
  8248. getSema()->Diag(Args[1]->getLocStart(),
  8249. diag::err_ovl_no_viable_member_function_in_call)
  8250. << intrinsicName;
  8251. return Sema::TemplateDeductionResult::TDK_Invalid;
  8252. }
  8253. argTypes[2] = getSema()->getASTContext().getIntTypeForBitwidth(
  8254. 32, /*signed*/ false);
  8255. }
  8256. }
  8257. Specialization = AddHLSLIntrinsicMethod(cursor.GetTableName(), cursor.GetLoweringStrategy(), *cursor, FunctionTemplate, Args, argTypes.data(), argTypes.size());
  8258. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  8259. FunctionTemplate->getCanonicalDecl());
  8260. if (!IsValidateObjectElement(*cursor, objectElement)) {
  8261. m_sema->Diag(Args[0]->getExprLoc(), diag::err_hlsl_invalid_resource_type_on_intrinsic) <<
  8262. nameIdentifier << g_ArBasicTypeNames[GetTypeElementKind(objectElement)];
  8263. }
  8264. return Sema::TemplateDeductionResult::TDK_Success;
  8265. }
  8266. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  8267. }
  8268. void HLSLExternalSource::ReportUnsupportedTypeNesting(SourceLocation loc, QualType type)
  8269. {
  8270. m_sema->Diag(loc, diag::err_hlsl_unsupported_type_nesting) << type;
  8271. }
  8272. bool HLSLExternalSource::TryStaticCastForHLSL(ExprResult &SrcExpr,
  8273. QualType DestType,
  8274. Sema::CheckedConversionKind CCK,
  8275. const SourceRange &OpRange, unsigned &msg,
  8276. CastKind &Kind, CXXCastPath &BasePath,
  8277. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  8278. _Inout_opt_ StandardConversionSequence* standard)
  8279. {
  8280. DXASSERT(!SrcExpr.isInvalid(), "caller should check for invalid expressions and placeholder types");
  8281. bool explicitConversion
  8282. = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
  8283. bool suppressWarnings = explicitConversion || SuppressWarnings;
  8284. SourceLocation loc = OpRange.getBegin();
  8285. if (ValidateCast(loc, SrcExpr.get(), DestType, explicitConversion, suppressWarnings, SuppressErrors, standard)) {
  8286. // TODO: LValue to RValue cast was all that CanConvert (ValidateCast) did anyway,
  8287. // so do this here until we figure out why this is needed.
  8288. if (standard && standard->First == ICK_Lvalue_To_Rvalue) {
  8289. SrcExpr.set(CreateLValueToRValueCast(SrcExpr.get()));
  8290. }
  8291. return true;
  8292. }
  8293. // ValidateCast includes its own error messages.
  8294. msg = 0;
  8295. return false;
  8296. }
  8297. /// <summary>
  8298. /// Checks if a subscript index argument can be initialized from the given expression.
  8299. /// </summary>
  8300. /// <param name="SrcExpr">Source expression used as argument.</param>
  8301. /// <param name="DestType">Parameter type to initialize.</param>
  8302. /// <remarks>
  8303. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  8304. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  8305. /// </remarks>
  8306. ImplicitConversionSequence
  8307. HLSLExternalSource::TrySubscriptIndexInitialization(_In_ clang::Expr *SrcExpr,
  8308. clang::QualType DestType) {
  8309. DXASSERT_NOMSG(SrcExpr != nullptr);
  8310. DXASSERT_NOMSG(!DestType.isNull());
  8311. unsigned int msg = 0;
  8312. CastKind kind;
  8313. CXXCastPath path;
  8314. ImplicitConversionSequence sequence;
  8315. sequence.setStandard();
  8316. ExprResult sourceExpr(SrcExpr);
  8317. if (GetElementCount(SrcExpr->getType()) != GetElementCount(DestType)) {
  8318. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  8319. SrcExpr->getType(), DestType);
  8320. } else if (!TryStaticCastForHLSL(
  8321. sourceExpr, DestType, Sema::CCK_ImplicitConversion, NoRange,
  8322. msg, kind, path, ListInitializationFalse,
  8323. SuppressWarningsFalse, SuppressErrorsTrue, &sequence.Standard)) {
  8324. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  8325. SrcExpr->getType(), DestType);
  8326. }
  8327. return sequence;
  8328. }
  8329. template <typename T>
  8330. static
  8331. bool IsValueInRange(T value, T minValue, T maxValue) {
  8332. return minValue <= value && value <= maxValue;
  8333. }
  8334. #define D3DX_16F_MAX 6.550400e+004 // max value
  8335. #define D3DX_16F_MIN 6.1035156e-5f // min positive value
  8336. static
  8337. void GetFloatLimits(ArBasicKind basicKind, double* minValue, double* maxValue)
  8338. {
  8339. DXASSERT_NOMSG(minValue != nullptr);
  8340. DXASSERT_NOMSG(maxValue != nullptr);
  8341. switch (basicKind) {
  8342. case AR_BASIC_MIN10FLOAT:
  8343. case AR_BASIC_MIN16FLOAT:
  8344. case AR_BASIC_FLOAT16: *minValue = -(D3DX_16F_MIN); *maxValue = D3DX_16F_MAX; return;
  8345. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  8346. case AR_BASIC_FLOAT32: *minValue = -(FLT_MIN); *maxValue = FLT_MAX; return;
  8347. case AR_BASIC_FLOAT64: *minValue = -(DBL_MIN); *maxValue = DBL_MAX; return;
  8348. default:
  8349. // No other float types.
  8350. break;
  8351. }
  8352. DXASSERT(false, "unreachable");
  8353. *minValue = 0; *maxValue = 0;
  8354. return;
  8355. }
  8356. static
  8357. void GetUnsignedLimit(ArBasicKind basicKind, uint64_t* maxValue)
  8358. {
  8359. DXASSERT_NOMSG(maxValue != nullptr);
  8360. switch (basicKind) {
  8361. case AR_BASIC_BOOL: *maxValue = 1; return;
  8362. case AR_BASIC_UINT8: *maxValue = UINT8_MAX; return;
  8363. case AR_BASIC_MIN16UINT:
  8364. case AR_BASIC_UINT16: *maxValue = UINT16_MAX; return;
  8365. case AR_BASIC_UINT32: *maxValue = UINT32_MAX; return;
  8366. case AR_BASIC_UINT64: *maxValue = UINT64_MAX; return;
  8367. default:
  8368. // No other unsigned int types.
  8369. break;
  8370. }
  8371. DXASSERT(false, "unreachable");
  8372. *maxValue = 0;
  8373. return;
  8374. }
  8375. static
  8376. void GetSignedLimits(ArBasicKind basicKind, int64_t* minValue, int64_t* maxValue)
  8377. {
  8378. DXASSERT_NOMSG(minValue != nullptr);
  8379. DXASSERT_NOMSG(maxValue != nullptr);
  8380. switch (basicKind) {
  8381. case AR_BASIC_INT8: *minValue = INT8_MIN; *maxValue = INT8_MAX; return;
  8382. case AR_BASIC_MIN12INT:
  8383. case AR_BASIC_MIN16INT:
  8384. case AR_BASIC_INT16: *minValue = INT16_MIN; *maxValue = INT16_MAX; return;
  8385. case AR_BASIC_INT32: *minValue = INT32_MIN; *maxValue = INT32_MAX; return;
  8386. case AR_BASIC_INT64: *minValue = INT64_MIN; *maxValue = INT64_MAX; return;
  8387. default:
  8388. // No other signed int types.
  8389. break;
  8390. }
  8391. DXASSERT(false, "unreachable");
  8392. *minValue = 0; *maxValue = 0;
  8393. return;
  8394. }
  8395. static
  8396. bool IsValueInBasicRange(ArBasicKind basicKind, const APValue& value)
  8397. {
  8398. if (IS_BASIC_FLOAT(basicKind)) {
  8399. double val;
  8400. if (value.isInt()) {
  8401. val = value.getInt().getLimitedValue();
  8402. } else if (value.isFloat()) {
  8403. llvm::APFloat floatValue = value.getFloat();
  8404. if (!floatValue.isFinite()) {
  8405. return false;
  8406. }
  8407. llvm::APFloat valueFloat = value.getFloat();
  8408. if (&valueFloat.getSemantics() == &llvm::APFloat::IEEEsingle) {
  8409. val = value.getFloat().convertToFloat();
  8410. }
  8411. else {
  8412. val = value.getFloat().convertToDouble();
  8413. }
  8414. } else {
  8415. return false;
  8416. }
  8417. double minValue, maxValue;
  8418. GetFloatLimits(basicKind, &minValue, &maxValue);
  8419. return IsValueInRange(val, minValue, maxValue);
  8420. }
  8421. else if (IS_BASIC_SINT(basicKind)) {
  8422. if (!value.isInt()) {
  8423. return false;
  8424. }
  8425. int64_t val = value.getInt().getSExtValue();
  8426. int64_t minValue, maxValue;
  8427. GetSignedLimits(basicKind, &minValue, &maxValue);
  8428. return IsValueInRange(val, minValue, maxValue);
  8429. }
  8430. else if (IS_BASIC_UINT(basicKind) || IS_BASIC_BOOL(basicKind)) {
  8431. if (!value.isInt()) {
  8432. return false;
  8433. }
  8434. uint64_t val = value.getInt().getLimitedValue();
  8435. uint64_t maxValue;
  8436. GetUnsignedLimit(basicKind, &maxValue);
  8437. return IsValueInRange(val, (uint64_t)0, maxValue);
  8438. }
  8439. else {
  8440. return false;
  8441. }
  8442. }
  8443. static
  8444. bool IsPrecisionLossIrrelevant(ASTContext& Ctx, _In_ const Expr* sourceExpr, QualType targetType, ArBasicKind targetKind)
  8445. {
  8446. DXASSERT_NOMSG(!targetType.isNull());
  8447. DXASSERT_NOMSG(sourceExpr != nullptr);
  8448. Expr::EvalResult evalResult;
  8449. if (sourceExpr->EvaluateAsRValue(evalResult, Ctx)) {
  8450. if (evalResult.Diag == nullptr || evalResult.Diag->empty()) {
  8451. return IsValueInBasicRange(targetKind, evalResult.Val);
  8452. }
  8453. }
  8454. return false;
  8455. }
  8456. bool HLSLExternalSource::ValidateCast(
  8457. SourceLocation OpLoc,
  8458. _In_ Expr* sourceExpr,
  8459. QualType target,
  8460. bool explicitConversion,
  8461. bool suppressWarnings,
  8462. bool suppressErrors,
  8463. _Inout_opt_ StandardConversionSequence* standard)
  8464. {
  8465. DXASSERT_NOMSG(sourceExpr != nullptr);
  8466. if (OpLoc.isInvalid())
  8467. OpLoc = sourceExpr->getExprLoc();
  8468. QualType source = sourceExpr->getType();
  8469. TYPE_CONVERSION_REMARKS remarks;
  8470. if (!CanConvert(OpLoc, sourceExpr, target, explicitConversion, &remarks, standard))
  8471. {
  8472. const bool IsOutputParameter = false;
  8473. //
  8474. // Check whether the lack of explicit-ness matters.
  8475. //
  8476. // Setting explicitForDiagnostics to true in that case will avoid the message
  8477. // saying anything about the implicit nature of the cast, when adding the
  8478. // explicit cast won't make a difference.
  8479. //
  8480. bool explicitForDiagnostics = explicitConversion;
  8481. if (explicitConversion == false)
  8482. {
  8483. if (!CanConvert(OpLoc, sourceExpr, target, true, &remarks, nullptr))
  8484. {
  8485. // Can't convert either way - implicit/explicit doesn't matter.
  8486. explicitForDiagnostics = true;
  8487. }
  8488. }
  8489. if (!suppressErrors)
  8490. {
  8491. m_sema->Diag(OpLoc, diag::err_hlsl_cannot_convert)
  8492. << explicitForDiagnostics << IsOutputParameter << source << target;
  8493. }
  8494. return false;
  8495. }
  8496. if (!suppressWarnings)
  8497. {
  8498. if (!explicitConversion)
  8499. {
  8500. if ((remarks & TYPE_CONVERSION_PRECISION_LOSS) != 0)
  8501. {
  8502. // This is a much more restricted version of the analysis does
  8503. // StandardConversionSequence::getNarrowingKind
  8504. if (!IsPrecisionLossIrrelevant(*m_context, sourceExpr, target, GetTypeElementKind(target)))
  8505. {
  8506. m_sema->Diag(OpLoc, diag::warn_hlsl_narrowing) << source << target;
  8507. }
  8508. }
  8509. if ((remarks & TYPE_CONVERSION_ELT_TRUNCATION) != 0)
  8510. {
  8511. m_sema->Diag(OpLoc, diag::warn_hlsl_implicit_vector_truncation);
  8512. }
  8513. }
  8514. }
  8515. return true;
  8516. }
  8517. ////////////////////////////////////////////////////////////////////////////////
  8518. // Functions exported from this translation unit. //
  8519. /// <summary>Performs HLSL-specific processing for unary operators.</summary>
  8520. QualType hlsl::CheckUnaryOpForHLSL(Sema& self,
  8521. SourceLocation OpLoc,
  8522. UnaryOperatorKind Opc,
  8523. ExprResult& InputExpr,
  8524. ExprValueKind& VK,
  8525. ExprObjectKind& OK)
  8526. {
  8527. ExternalSemaSource* externalSource = self.getExternalSource();
  8528. if (externalSource == nullptr) {
  8529. return QualType();
  8530. }
  8531. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8532. return hlsl->CheckUnaryOpForHLSL(OpLoc, Opc, InputExpr, VK, OK);
  8533. }
  8534. /// <summary>Performs HLSL-specific processing for binary operators.</summary>
  8535. void hlsl::CheckBinOpForHLSL(Sema& self,
  8536. SourceLocation OpLoc,
  8537. BinaryOperatorKind Opc,
  8538. ExprResult& LHS,
  8539. ExprResult& RHS,
  8540. QualType& ResultTy,
  8541. QualType& CompLHSTy,
  8542. QualType& CompResultTy)
  8543. {
  8544. ExternalSemaSource* externalSource = self.getExternalSource();
  8545. if (externalSource == nullptr) {
  8546. return;
  8547. }
  8548. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8549. return hlsl->CheckBinOpForHLSL(OpLoc, Opc, LHS, RHS, ResultTy, CompLHSTy, CompResultTy);
  8550. }
  8551. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  8552. bool hlsl::CheckTemplateArgumentListForHLSL(Sema& self, TemplateDecl* Template, SourceLocation TemplateLoc, TemplateArgumentListInfo& TemplateArgList)
  8553. {
  8554. DXASSERT_NOMSG(Template != nullptr);
  8555. ExternalSemaSource* externalSource = self.getExternalSource();
  8556. if (externalSource == nullptr) {
  8557. return false;
  8558. }
  8559. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  8560. return hlsl->CheckTemplateArgumentListForHLSL(Template, TemplateLoc, TemplateArgList);
  8561. }
  8562. /// <summary>Deduces template arguments on a function call in an HLSL program.</summary>
  8563. Sema::TemplateDeductionResult hlsl::DeduceTemplateArgumentsForHLSL(Sema* self,
  8564. FunctionTemplateDecl *FunctionTemplate,
  8565. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  8566. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  8567. {
  8568. return HLSLExternalSource::FromSema(self)
  8569. ->DeduceTemplateArgumentsForHLSL(FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info);
  8570. }
  8571. void hlsl::DiagnoseControlFlowConditionForHLSL(Sema *self, Expr *condExpr, StringRef StmtName) {
  8572. while (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(condExpr)) {
  8573. if (IC->getCastKind() == CastKind::CK_HLSLMatrixTruncationCast ||
  8574. IC->getCastKind() == CastKind::CK_HLSLVectorTruncationCast) {
  8575. self->Diag(condExpr->getLocStart(),
  8576. diag::err_hlsl_control_flow_cond_not_scalar)
  8577. << StmtName;
  8578. return;
  8579. }
  8580. condExpr = IC->getSubExpr();
  8581. }
  8582. }
  8583. static bool ShaderModelsMatch(const StringRef& left, const StringRef& right)
  8584. {
  8585. // TODO: handle shorthand cases.
  8586. return left.size() == 0 || right.size() == 0 || left.equals(right);
  8587. }
  8588. void hlsl::DiagnosePackingOffset(
  8589. clang::Sema* self,
  8590. SourceLocation loc,
  8591. clang::QualType type,
  8592. int componentOffset)
  8593. {
  8594. DXASSERT_NOMSG(0 <= componentOffset && componentOffset <= 3);
  8595. if (componentOffset > 0) {
  8596. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  8597. ArBasicKind element = source->GetTypeElementKind(type);
  8598. ArTypeObjectKind shape = source->GetTypeObjectKind(type);
  8599. // Only perform some simple validation for now.
  8600. if (IsObjectKindPrimitiveAggregate(shape) && IsBasicKindNumeric(element)) {
  8601. int count = GetElementCount(type);
  8602. if (count > (4 - componentOffset)) {
  8603. self->Diag(loc, diag::err_hlsl_register_or_offset_bind_not_valid);
  8604. }
  8605. }
  8606. }
  8607. }
  8608. void hlsl::DiagnoseRegisterType(
  8609. clang::Sema* self,
  8610. clang::SourceLocation loc,
  8611. clang::QualType type,
  8612. char registerType)
  8613. {
  8614. // Register type can be zero if only a register space was provided.
  8615. if (registerType == 0)
  8616. return;
  8617. if (registerType >= 'A' && registerType <= 'Z')
  8618. registerType = registerType + ('a' - 'A');
  8619. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  8620. ArBasicKind element = source->GetTypeElementKind(type);
  8621. StringRef expected("none");
  8622. bool isValid = true;
  8623. bool isWarning = false;
  8624. switch (element)
  8625. {
  8626. case AR_BASIC_BOOL:
  8627. case AR_BASIC_LITERAL_FLOAT:
  8628. case AR_BASIC_FLOAT16:
  8629. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  8630. case AR_BASIC_FLOAT32:
  8631. case AR_BASIC_FLOAT64:
  8632. case AR_BASIC_LITERAL_INT:
  8633. case AR_BASIC_INT8:
  8634. case AR_BASIC_UINT8:
  8635. case AR_BASIC_INT16:
  8636. case AR_BASIC_UINT16:
  8637. case AR_BASIC_INT32:
  8638. case AR_BASIC_UINT32:
  8639. case AR_BASIC_INT64:
  8640. case AR_BASIC_UINT64:
  8641. case AR_BASIC_MIN10FLOAT:
  8642. case AR_BASIC_MIN16FLOAT:
  8643. case AR_BASIC_MIN12INT:
  8644. case AR_BASIC_MIN16INT:
  8645. case AR_BASIC_MIN16UINT:
  8646. expected = "'b', 'c', or 'i'";
  8647. isValid = registerType == 'b' || registerType == 'c' || registerType == 'i';
  8648. break;
  8649. case AR_OBJECT_TEXTURE1D:
  8650. case AR_OBJECT_TEXTURE1D_ARRAY:
  8651. case AR_OBJECT_TEXTURE2D:
  8652. case AR_OBJECT_TEXTURE2D_ARRAY:
  8653. case AR_OBJECT_TEXTURE3D:
  8654. case AR_OBJECT_TEXTURECUBE:
  8655. case AR_OBJECT_TEXTURECUBE_ARRAY:
  8656. case AR_OBJECT_TEXTURE2DMS:
  8657. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  8658. expected = "'t' or 's'";
  8659. isValid = registerType == 't' || registerType == 's';
  8660. break;
  8661. case AR_OBJECT_SAMPLER:
  8662. case AR_OBJECT_SAMPLER1D:
  8663. case AR_OBJECT_SAMPLER2D:
  8664. case AR_OBJECT_SAMPLER3D:
  8665. case AR_OBJECT_SAMPLERCUBE:
  8666. case AR_OBJECT_SAMPLERCOMPARISON:
  8667. expected = "'s' or 't'";
  8668. isValid = registerType == 's' || registerType == 't';
  8669. break;
  8670. case AR_OBJECT_BUFFER:
  8671. expected = "'t'";
  8672. isValid = registerType == 't';
  8673. break;
  8674. case AR_OBJECT_POINTSTREAM:
  8675. case AR_OBJECT_LINESTREAM:
  8676. case AR_OBJECT_TRIANGLESTREAM:
  8677. isValid = false;
  8678. isWarning = true;
  8679. break;
  8680. case AR_OBJECT_INPUTPATCH:
  8681. case AR_OBJECT_OUTPUTPATCH:
  8682. isValid = false;
  8683. isWarning = true;
  8684. break;
  8685. case AR_OBJECT_RWTEXTURE1D:
  8686. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  8687. case AR_OBJECT_RWTEXTURE2D:
  8688. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  8689. case AR_OBJECT_RWTEXTURE3D:
  8690. case AR_OBJECT_RWBUFFER:
  8691. expected = "'u'";
  8692. isValid = registerType == 'u';
  8693. break;
  8694. case AR_OBJECT_BYTEADDRESS_BUFFER:
  8695. case AR_OBJECT_STRUCTURED_BUFFER:
  8696. expected = "'t'";
  8697. isValid = registerType == 't';
  8698. break;
  8699. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  8700. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  8701. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  8702. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  8703. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  8704. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  8705. expected = "'u'";
  8706. isValid = registerType == 'u';
  8707. break;
  8708. case AR_OBJECT_CONSTANT_BUFFER:
  8709. expected = "'b'";
  8710. isValid = registerType == 'b';
  8711. break;
  8712. case AR_OBJECT_TEXTURE_BUFFER:
  8713. expected = "'t'";
  8714. isValid = registerType == 't';
  8715. break;
  8716. case AR_OBJECT_ROVBUFFER:
  8717. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  8718. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  8719. case AR_OBJECT_ROVTEXTURE1D:
  8720. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  8721. case AR_OBJECT_ROVTEXTURE2D:
  8722. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  8723. case AR_OBJECT_ROVTEXTURE3D:
  8724. case AR_OBJECT_FEEDBACKTEXTURE2D:
  8725. case AR_OBJECT_FEEDBACKTEXTURE2D_ARRAY:
  8726. expected = "'u'";
  8727. isValid = registerType == 'u';
  8728. break;
  8729. case AR_OBJECT_LEGACY_EFFECT: // Used for all unsupported but ignored legacy effect types
  8730. isWarning = true;
  8731. break; // So we don't care what you tried to bind it to
  8732. default: // Other types have no associated registers.
  8733. break;
  8734. }
  8735. // fxc is inconsistent as to when it reports an error and when it ignores invalid bind semantics, so emit
  8736. // a warning instead.
  8737. if (!isValid) {
  8738. unsigned DiagID = isWarning ? diag::warn_hlsl_incorrect_bind_semantic : diag::err_hlsl_incorrect_bind_semantic;
  8739. self->Diag(loc, DiagID) << expected;
  8740. }
  8741. }
  8742. struct NameLookup {
  8743. FunctionDecl *Found;
  8744. FunctionDecl *Other;
  8745. };
  8746. static NameLookup GetSingleFunctionDeclByName(clang::Sema *self, StringRef Name, bool checkPatch) {
  8747. auto DN = DeclarationName(&self->getASTContext().Idents.get(Name));
  8748. FunctionDecl *pFoundDecl = nullptr;
  8749. for (auto idIter = self->IdResolver.begin(DN), idEnd = self->IdResolver.end(); idIter != idEnd; ++idIter) {
  8750. FunctionDecl *pFnDecl = dyn_cast<FunctionDecl>(*idIter);
  8751. if (!pFnDecl) continue;
  8752. if (checkPatch && !self->getASTContext().IsPatchConstantFunctionDecl(pFnDecl)) continue;
  8753. if (pFoundDecl) {
  8754. return NameLookup{ pFoundDecl, pFnDecl };
  8755. }
  8756. pFoundDecl = pFnDecl;
  8757. }
  8758. return NameLookup{ pFoundDecl, nullptr };
  8759. }
  8760. void hlsl::DiagnoseTranslationUnit(clang::Sema *self) {
  8761. DXASSERT_NOMSG(self != nullptr);
  8762. // Don't bother with global validation if compilation has already failed.
  8763. if (self->getDiagnostics().hasErrorOccurred()) {
  8764. return;
  8765. }
  8766. // Don't check entry function for library.
  8767. if (self->getLangOpts().IsHLSLLibrary) {
  8768. // TODO: validate no recursion start from every function.
  8769. return;
  8770. }
  8771. // TODO: make these error 'real' errors rather than on-the-fly things
  8772. // Validate that the entry point is available.
  8773. DiagnosticsEngine &Diags = self->getDiagnostics();
  8774. FunctionDecl *pEntryPointDecl = nullptr;
  8775. FunctionDecl *pPatchFnDecl = nullptr;
  8776. const std::string &EntryPointName = self->getLangOpts().HLSLEntryFunction;
  8777. if (!EntryPointName.empty()) {
  8778. NameLookup NL = GetSingleFunctionDeclByName(self, EntryPointName, /*checkPatch*/ false);
  8779. if (NL.Found && NL.Other) {
  8780. // NOTE: currently we cannot hit this codepath when CodeGen is enabled, because
  8781. // CodeGenModule::getMangledName will mangle the entry point name into the bare
  8782. // string, and so ambiguous points will produce an error earlier on.
  8783. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8784. "ambiguous entry point function");
  8785. Diags.Report(NL.Found->getSourceRange().getBegin(), id);
  8786. Diags.Report(NL.Other->getLocation(), diag::note_previous_definition);
  8787. return;
  8788. }
  8789. pEntryPointDecl = NL.Found;
  8790. if (!pEntryPointDecl || !pEntryPointDecl->hasBody()) {
  8791. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8792. "missing entry point definition");
  8793. Diags.Report(id);
  8794. return;
  8795. }
  8796. }
  8797. // Validate that there is no recursion; start with the entry function.
  8798. // NOTE: the information gathered here could be used to bypass code generation
  8799. // on functions that are unreachable (as an early form of dead code elimination).
  8800. if (pEntryPointDecl) {
  8801. const auto *shaderModel =
  8802. hlsl::ShaderModel::GetByName(self->getLangOpts().HLSLProfile.c_str());
  8803. if (shaderModel->IsGS()) {
  8804. // Validate that GS has the maxvertexcount attribute
  8805. if (!pEntryPointDecl->hasAttr<HLSLMaxVertexCountAttr>()) {
  8806. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  8807. << "GS"
  8808. << "maxvertexcount";
  8809. return;
  8810. }
  8811. } else if (shaderModel->IsHS()) {
  8812. if (const HLSLPatchConstantFuncAttr *Attr =
  8813. pEntryPointDecl->getAttr<HLSLPatchConstantFuncAttr>()) {
  8814. NameLookup NL = GetSingleFunctionDeclByName(
  8815. self, Attr->getFunctionName(), /*checkPatch*/ true);
  8816. if (!NL.Found || !NL.Found->hasBody()) {
  8817. unsigned id =
  8818. Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8819. "missing patch function definition");
  8820. Diags.Report(id);
  8821. return;
  8822. }
  8823. pPatchFnDecl = NL.Found;
  8824. } else {
  8825. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  8826. << "HS"
  8827. << "patchconstantfunc";
  8828. return;
  8829. }
  8830. } else if (shaderModel->IsMS()) {
  8831. // Validate that MS has the numthreads attribute
  8832. if (!pEntryPointDecl->hasAttr<HLSLNumThreadsAttr>()) {
  8833. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  8834. << "MS"
  8835. << "numthreads";
  8836. return;
  8837. }
  8838. // Validate that MS has the outputtopology attribute
  8839. if (!pEntryPointDecl->hasAttr<HLSLOutputTopologyAttr>()) {
  8840. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  8841. << "MS"
  8842. << "outputtopology";
  8843. return;
  8844. }
  8845. } else if (shaderModel->IsAS()) {
  8846. // Validate that AS has the numthreads attribute
  8847. if (!pEntryPointDecl->hasAttr<HLSLNumThreadsAttr>()) {
  8848. self->Diag(pEntryPointDecl->getLocation(), diag::err_hlsl_missing_attr)
  8849. << "AS"
  8850. << "numthreads";
  8851. return;
  8852. }
  8853. }
  8854. hlsl::CallGraphWithRecurseGuard CG;
  8855. CG.BuildForEntry(pEntryPointDecl);
  8856. Decl *pResult = CG.CheckRecursion(pEntryPointDecl);
  8857. if (pResult) {
  8858. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8859. "recursive functions not allowed");
  8860. Diags.Report(pResult->getSourceRange().getBegin(), id);
  8861. }
  8862. if (pPatchFnDecl) {
  8863. CG.BuildForEntry(pPatchFnDecl);
  8864. Decl *pPatchFnDecl = CG.CheckRecursion(pEntryPointDecl);
  8865. if (pPatchFnDecl) {
  8866. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8867. "recursive functions not allowed (via patch function)");
  8868. Diags.Report(pPatchFnDecl->getSourceRange().getBegin(), id);
  8869. }
  8870. }
  8871. }
  8872. }
  8873. void hlsl::DiagnoseUnusualAnnotationsForHLSL(
  8874. Sema& S,
  8875. std::vector<hlsl::UnusualAnnotation *>& annotations)
  8876. {
  8877. bool packoffsetOverriddenReported = false;
  8878. auto && iter = annotations.begin();
  8879. auto && end = annotations.end();
  8880. for (; iter != end; ++iter) {
  8881. switch ((*iter)->getKind()) {
  8882. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  8883. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*iter);
  8884. // Check whether this will conflict with other packoffsets. If so, only issue a warning; last one wins.
  8885. if (!packoffsetOverriddenReported) {
  8886. auto newIter = iter;
  8887. ++newIter;
  8888. while (newIter != end) {
  8889. hlsl::ConstantPacking* other = dyn_cast_or_null<hlsl::ConstantPacking>(*newIter);
  8890. if (other != nullptr &&
  8891. (other->Subcomponent != constantPacking->Subcomponent || other->ComponentOffset != constantPacking->ComponentOffset)) {
  8892. S.Diag(constantPacking->Loc, diag::warn_hlsl_packoffset_overridden);
  8893. packoffsetOverriddenReported = true;
  8894. break;
  8895. }
  8896. ++newIter;
  8897. }
  8898. }
  8899. break;
  8900. }
  8901. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  8902. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*iter);
  8903. // Check whether this will conflict with other register assignments of the same type.
  8904. auto newIter = iter;
  8905. ++newIter;
  8906. while (newIter != end) {
  8907. hlsl::RegisterAssignment* other = dyn_cast_or_null<hlsl::RegisterAssignment>(*newIter);
  8908. // Same register bank and profile, but different number.
  8909. if (other != nullptr &&
  8910. ShaderModelsMatch(other->ShaderProfile, registerAssignment->ShaderProfile) &&
  8911. other->RegisterType == registerAssignment->RegisterType &&
  8912. (other->RegisterNumber != registerAssignment->RegisterNumber ||
  8913. other->RegisterOffset != registerAssignment->RegisterOffset)) {
  8914. // Obvious conflict - report it up front.
  8915. S.Diag(registerAssignment->Loc, diag::err_hlsl_register_semantics_conflicting);
  8916. }
  8917. ++newIter;
  8918. }
  8919. break;
  8920. }
  8921. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  8922. // hlsl::SemanticDecl* semanticDecl = cast<hlsl::SemanticDecl>(*iter);
  8923. // No common validation to be performed.
  8924. break;
  8925. }
  8926. }
  8927. }
  8928. }
  8929. clang::OverloadingResult
  8930. hlsl::GetBestViableFunction(clang::Sema &S, clang::SourceLocation Loc,
  8931. clang::OverloadCandidateSet &set,
  8932. clang::OverloadCandidateSet::iterator &Best) {
  8933. return HLSLExternalSource::FromSema(&S)
  8934. ->GetBestViableFunction(Loc, set, Best);
  8935. }
  8936. void hlsl::InitializeInitSequenceForHLSL(Sema *self,
  8937. const InitializedEntity &Entity,
  8938. const InitializationKind &Kind,
  8939. MultiExprArg Args,
  8940. bool TopLevelOfInitList,
  8941. InitializationSequence *initSequence) {
  8942. return HLSLExternalSource::FromSema(self)
  8943. ->InitializeInitSequenceForHLSL(Entity, Kind, Args, TopLevelOfInitList, initSequence);
  8944. }
  8945. static unsigned CaculateInitListSize(HLSLExternalSource *hlslSource,
  8946. const clang::InitListExpr *InitList) {
  8947. unsigned totalSize = 0;
  8948. for (unsigned i = 0; i < InitList->getNumInits(); i++) {
  8949. const clang::Expr *EltInit = InitList->getInit(i);
  8950. QualType EltInitTy = EltInit->getType();
  8951. if (const InitListExpr *EltInitList = dyn_cast<InitListExpr>(EltInit)) {
  8952. totalSize += CaculateInitListSize(hlslSource, EltInitList);
  8953. } else {
  8954. totalSize += hlslSource->GetNumBasicElements(EltInitTy);
  8955. }
  8956. }
  8957. return totalSize;
  8958. }
  8959. unsigned hlsl::CaculateInitListArraySizeForHLSL(
  8960. _In_ clang::Sema* sema,
  8961. _In_ const clang::InitListExpr *InitList,
  8962. _In_ const clang::QualType EltTy) {
  8963. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(sema);
  8964. unsigned totalSize = CaculateInitListSize(hlslSource, InitList);
  8965. unsigned eltSize = hlslSource->GetNumBasicElements(EltTy);
  8966. if (totalSize > 0 && (totalSize % eltSize)==0) {
  8967. return totalSize / eltSize;
  8968. } else {
  8969. return 0;
  8970. }
  8971. }
  8972. bool hlsl::IsConversionToLessOrEqualElements(
  8973. _In_ clang::Sema* self,
  8974. const clang::ExprResult& sourceExpr,
  8975. const clang::QualType& targetType,
  8976. bool explicitConversion)
  8977. {
  8978. return HLSLExternalSource::FromSema(self)
  8979. ->IsConversionToLessOrEqualElements(sourceExpr, targetType, explicitConversion);
  8980. }
  8981. ExprResult hlsl::LookupMatrixMemberExprForHLSL(
  8982. Sema* self,
  8983. Expr& BaseExpr,
  8984. DeclarationName MemberName,
  8985. bool IsArrow,
  8986. SourceLocation OpLoc,
  8987. SourceLocation MemberLoc)
  8988. {
  8989. return HLSLExternalSource::FromSema(self)
  8990. ->LookupMatrixMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  8991. }
  8992. ExprResult hlsl::LookupVectorMemberExprForHLSL(
  8993. Sema* self,
  8994. Expr& BaseExpr,
  8995. DeclarationName MemberName,
  8996. bool IsArrow,
  8997. SourceLocation OpLoc,
  8998. SourceLocation MemberLoc)
  8999. {
  9000. return HLSLExternalSource::FromSema(self)
  9001. ->LookupVectorMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9002. }
  9003. ExprResult hlsl::LookupArrayMemberExprForHLSL(
  9004. Sema* self,
  9005. Expr& BaseExpr,
  9006. DeclarationName MemberName,
  9007. bool IsArrow,
  9008. SourceLocation OpLoc,
  9009. SourceLocation MemberLoc)
  9010. {
  9011. return HLSLExternalSource::FromSema(self)
  9012. ->LookupArrayMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9013. }
  9014. bool hlsl::LookupRecordMemberExprForHLSL(
  9015. Sema* self,
  9016. Expr& BaseExpr,
  9017. DeclarationName MemberName,
  9018. bool IsArrow,
  9019. SourceLocation OpLoc,
  9020. SourceLocation MemberLoc,
  9021. ExprResult &result)
  9022. {
  9023. HLSLExternalSource *source = HLSLExternalSource::FromSema(self);
  9024. switch (source->GetTypeObjectKind(BaseExpr.getType())) {
  9025. case AR_TOBJ_MATRIX:
  9026. result = source->LookupMatrixMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9027. return true;
  9028. case AR_TOBJ_VECTOR:
  9029. result = source->LookupVectorMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9030. return true;
  9031. case AR_TOBJ_ARRAY:
  9032. result = source->LookupArrayMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc);
  9033. return true;
  9034. default:
  9035. return false;
  9036. }
  9037. return false;
  9038. }
  9039. clang::ExprResult hlsl::MaybeConvertScalarToVector(
  9040. _In_ clang::Sema* self,
  9041. _In_ clang::Expr* E)
  9042. {
  9043. return HLSLExternalSource::FromSema(self)->MaybeConvertScalarToVector(E);
  9044. }
  9045. bool hlsl::TryStaticCastForHLSL(_In_ Sema* self, ExprResult &SrcExpr,
  9046. QualType DestType,
  9047. Sema::CheckedConversionKind CCK,
  9048. const SourceRange &OpRange, unsigned &msg,
  9049. CastKind &Kind, CXXCastPath &BasePath,
  9050. bool ListInitialization,
  9051. bool SuppressDiagnostics,
  9052. _Inout_opt_ StandardConversionSequence* standard)
  9053. {
  9054. return HLSLExternalSource::FromSema(self)->TryStaticCastForHLSL(
  9055. SrcExpr, DestType, CCK, OpRange, msg, Kind, BasePath, ListInitialization,
  9056. SuppressDiagnostics, SuppressDiagnostics, standard);
  9057. }
  9058. clang::ExprResult hlsl::PerformHLSLConversion(
  9059. _In_ clang::Sema* self,
  9060. _In_ clang::Expr* From,
  9061. _In_ clang::QualType targetType,
  9062. _In_ const clang::StandardConversionSequence &SCS,
  9063. _In_ clang::Sema::CheckedConversionKind CCK)
  9064. {
  9065. return HLSLExternalSource::FromSema(self)->PerformHLSLConversion(From, targetType, SCS, CCK);
  9066. }
  9067. clang::ImplicitConversionSequence hlsl::TrySubscriptIndexInitialization(
  9068. _In_ clang::Sema* self,
  9069. _In_ clang::Expr* SrcExpr,
  9070. clang::QualType DestType)
  9071. {
  9072. return HLSLExternalSource::FromSema(self)
  9073. ->TrySubscriptIndexInitialization(SrcExpr, DestType);
  9074. }
  9075. /// <summary>Performs HLSL-specific initialization on the specified context.</summary>
  9076. void hlsl::InitializeASTContextForHLSL(ASTContext& context)
  9077. {
  9078. HLSLExternalSource* hlslSource = new HLSLExternalSource();
  9079. IntrusiveRefCntPtr<ExternalASTSource> externalSource(hlslSource);
  9080. if (hlslSource->Initialize(context)) {
  9081. context.setExternalSource(externalSource);
  9082. }
  9083. }
  9084. ////////////////////////////////////////////////////////////////////////////////
  9085. // FlattenedTypeIterator implementation //
  9086. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  9087. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source) :
  9088. m_source(source), m_draining(false), m_springLoaded(false), m_incompleteCount(0), m_typeDepth(0), m_loc(loc)
  9089. {
  9090. if (pushTrackerForType(type, nullptr)) {
  9091. while (!m_typeTrackers.empty() && !considerLeaf())
  9092. consumeLeaf();
  9093. }
  9094. }
  9095. /// <summary>Constructs a FlattenedTypeIterator for the specified expressions.</summary>
  9096. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source) :
  9097. m_source(source), m_draining(false), m_springLoaded(false), m_incompleteCount(0), m_typeDepth(0), m_loc(loc)
  9098. {
  9099. if (!args.empty()) {
  9100. MultiExprArg::iterator ii = args.begin();
  9101. MultiExprArg::iterator ie = args.end();
  9102. DXASSERT(ii != ie, "otherwise empty() returned an incorrect value");
  9103. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  9104. if (!considerLeaf()) {
  9105. m_typeTrackers.clear();
  9106. }
  9107. }
  9108. }
  9109. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  9110. QualType FlattenedTypeIterator::getCurrentElement() const
  9111. {
  9112. return m_typeTrackers.back().Type;
  9113. }
  9114. /// <summary>Get the number of repeated current elements.</summary>
  9115. unsigned int FlattenedTypeIterator::getCurrentElementSize() const
  9116. {
  9117. const FlattenedTypeTracker& back = m_typeTrackers.back();
  9118. return (back.IterKind == FK_IncompleteArray) ? 1 : back.Count;
  9119. }
  9120. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  9121. bool FlattenedTypeIterator::hasCurrentElement() const
  9122. {
  9123. return m_typeTrackers.size() > 0;
  9124. }
  9125. /// <summary>Consumes count elements on this iterator.</summary>
  9126. void FlattenedTypeIterator::advanceCurrentElement(unsigned int count)
  9127. {
  9128. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  9129. DXASSERT(m_typeTrackers.back().IterKind == FK_IncompleteArray || count <= m_typeTrackers.back().Count, "caller should never exceed currently pending element count");
  9130. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  9131. if (tracker.IterKind == FK_IncompleteArray)
  9132. {
  9133. tracker.Count += count;
  9134. m_springLoaded = true;
  9135. }
  9136. else
  9137. {
  9138. tracker.Count -= count;
  9139. m_springLoaded = false;
  9140. if (m_typeTrackers.back().Count == 0)
  9141. {
  9142. advanceLeafTracker();
  9143. }
  9144. }
  9145. }
  9146. unsigned int FlattenedTypeIterator::countRemaining()
  9147. {
  9148. m_draining = true; // when draining the iterator, incomplete arrays stop functioning as an infinite array
  9149. size_t result = 0;
  9150. while (hasCurrentElement() && !m_springLoaded)
  9151. {
  9152. size_t pending = getCurrentElementSize();
  9153. result += pending;
  9154. advanceCurrentElement(pending);
  9155. }
  9156. return result;
  9157. }
  9158. void FlattenedTypeIterator::advanceLeafTracker()
  9159. {
  9160. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  9161. for (;;)
  9162. {
  9163. consumeLeaf();
  9164. if (m_typeTrackers.empty()) {
  9165. return;
  9166. }
  9167. if (considerLeaf()) {
  9168. return;
  9169. }
  9170. }
  9171. }
  9172. bool FlattenedTypeIterator::considerLeaf()
  9173. {
  9174. if (m_typeTrackers.empty()) {
  9175. return false;
  9176. }
  9177. m_typeDepth++;
  9178. if (m_typeDepth > MaxTypeDepth) {
  9179. m_source.ReportUnsupportedTypeNesting(m_loc, m_firstType);
  9180. m_typeTrackers.clear();
  9181. m_typeDepth--;
  9182. return false;
  9183. }
  9184. bool result = false;
  9185. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  9186. tracker.IsConsidered = true;
  9187. switch (tracker.IterKind) {
  9188. case FlattenedIterKind::FK_Expressions:
  9189. if (pushTrackerForExpression(tracker.CurrentExpr)) {
  9190. result = considerLeaf();
  9191. }
  9192. break;
  9193. case FlattenedIterKind::FK_Fields:
  9194. if (pushTrackerForType(tracker.CurrentField->getType(), nullptr)) {
  9195. result = considerLeaf();
  9196. }
  9197. break;
  9198. case FlattenedIterKind::FK_Bases:
  9199. if (pushTrackerForType(tracker.CurrentBase->getType(), nullptr)) {
  9200. result = considerLeaf();
  9201. }
  9202. break;
  9203. case FlattenedIterKind::FK_IncompleteArray:
  9204. m_springLoaded = true; // fall through.
  9205. default:
  9206. case FlattenedIterKind::FK_Simple: {
  9207. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(tracker.Type);
  9208. if (objectKind != ArTypeObjectKind::AR_TOBJ_BASIC &&
  9209. objectKind != ArTypeObjectKind::AR_TOBJ_OBJECT &&
  9210. objectKind != ArTypeObjectKind::AR_TOBJ_STRING) {
  9211. if (pushTrackerForType(tracker.Type, tracker.CurrentExpr)) {
  9212. result = considerLeaf();
  9213. }
  9214. } else {
  9215. result = true;
  9216. }
  9217. }
  9218. }
  9219. m_typeDepth--;
  9220. return result;
  9221. }
  9222. void FlattenedTypeIterator::consumeLeaf()
  9223. {
  9224. bool topConsumed = true; // Tracks whether we're processing the topmost item which we should consume.
  9225. for (;;) {
  9226. if (m_typeTrackers.empty()) {
  9227. return;
  9228. }
  9229. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  9230. // Reach a leaf which is not considered before.
  9231. // Stop here.
  9232. if (!tracker.IsConsidered) {
  9233. break;
  9234. }
  9235. switch (tracker.IterKind) {
  9236. case FlattenedIterKind::FK_Expressions:
  9237. ++tracker.CurrentExpr;
  9238. if (tracker.CurrentExpr == tracker.EndExpr) {
  9239. m_typeTrackers.pop_back();
  9240. topConsumed = false;
  9241. } else {
  9242. return;
  9243. }
  9244. break;
  9245. case FlattenedIterKind::FK_Fields:
  9246. ++tracker.CurrentField;
  9247. if (tracker.CurrentField == tracker.EndField) {
  9248. m_typeTrackers.pop_back();
  9249. topConsumed = false;
  9250. } else {
  9251. return;
  9252. }
  9253. break;
  9254. case FlattenedIterKind::FK_Bases:
  9255. ++tracker.CurrentBase;
  9256. if (tracker.CurrentBase == tracker.EndBase) {
  9257. m_typeTrackers.pop_back();
  9258. topConsumed = false;
  9259. } else {
  9260. return;
  9261. }
  9262. break;
  9263. case FlattenedIterKind::FK_IncompleteArray:
  9264. if (m_draining) {
  9265. DXASSERT(m_typeTrackers.size() == 1, "m_typeTrackers.size() == 1, otherwise incomplete array isn't topmost");
  9266. m_incompleteCount = tracker.Count;
  9267. m_typeTrackers.pop_back();
  9268. }
  9269. return;
  9270. default:
  9271. case FlattenedIterKind::FK_Simple: {
  9272. m_springLoaded = false;
  9273. if (!topConsumed) {
  9274. DXASSERT(tracker.Count > 0, "tracker.Count > 0 - otherwise we shouldn't be on stack");
  9275. --tracker.Count;
  9276. }
  9277. else {
  9278. topConsumed = false;
  9279. }
  9280. if (tracker.Count == 0) {
  9281. m_typeTrackers.pop_back();
  9282. } else {
  9283. return;
  9284. }
  9285. }
  9286. }
  9287. }
  9288. }
  9289. bool FlattenedTypeIterator::pushTrackerForExpression(MultiExprArg::iterator expression)
  9290. {
  9291. Expr* e = *expression;
  9292. Stmt::StmtClass expressionClass = e->getStmtClass();
  9293. if (expressionClass == Stmt::StmtClass::InitListExprClass) {
  9294. InitListExpr* initExpr = dyn_cast<InitListExpr>(e);
  9295. if (initExpr->getNumInits() == 0) {
  9296. return false;
  9297. }
  9298. MultiExprArg inits(initExpr->getInits(), initExpr->getNumInits());
  9299. MultiExprArg::iterator ii = inits.begin();
  9300. MultiExprArg::iterator ie = inits.end();
  9301. DXASSERT(ii != ie, "otherwise getNumInits() returned an incorrect value");
  9302. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  9303. return true;
  9304. }
  9305. return pushTrackerForType(e->getType(), expression);
  9306. }
  9307. // TODO: improve this to provide a 'peek' at intermediate types,
  9308. // which should help compare struct foo[1000] to avoid 1000 steps + per-field steps
  9309. bool FlattenedTypeIterator::pushTrackerForType(QualType type, MultiExprArg::iterator expression)
  9310. {
  9311. if (type->isVoidType()) {
  9312. return false;
  9313. }
  9314. if (type->isFunctionType()) {
  9315. return false;
  9316. }
  9317. if (m_firstType.isNull()) {
  9318. m_firstType = type;
  9319. }
  9320. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(type);
  9321. QualType elementType;
  9322. unsigned int elementCount;
  9323. const RecordType* recordType;
  9324. RecordDecl::field_iterator fi, fe;
  9325. switch (objectKind)
  9326. {
  9327. case ArTypeObjectKind::AR_TOBJ_ARRAY:
  9328. // TODO: handle multi-dimensional arrays
  9329. elementType = type->getAsArrayTypeUnsafe()->getElementType(); // handle arrays of arrays
  9330. elementCount = GetArraySize(type);
  9331. if (elementCount == 0) {
  9332. if (type->isIncompleteArrayType()) {
  9333. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(elementType));
  9334. return true;
  9335. }
  9336. return false;
  9337. }
  9338. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9339. elementType, elementCount, nullptr));
  9340. return true;
  9341. case ArTypeObjectKind::AR_TOBJ_BASIC:
  9342. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(type, 1, expression));
  9343. return true;
  9344. case ArTypeObjectKind::AR_TOBJ_COMPOUND: {
  9345. recordType = type->getAsStructureType();
  9346. if (recordType == nullptr)
  9347. recordType = dyn_cast<RecordType>(type.getTypePtr());
  9348. fi = recordType->getDecl()->field_begin();
  9349. fe = recordType->getDecl()->field_end();
  9350. bool bAddTracker = false;
  9351. // Skip empty struct.
  9352. if (fi != fe) {
  9353. m_typeTrackers.push_back(
  9354. FlattenedTypeIterator::FlattenedTypeTracker(type, fi, fe));
  9355. type = (*fi)->getType();
  9356. bAddTracker = true;
  9357. }
  9358. if (CXXRecordDecl *cxxRecordDecl =
  9359. dyn_cast<CXXRecordDecl>(recordType->getDecl())) {
  9360. // We'll error elsewhere if the record has no definition,
  9361. // just don't attempt to use it.
  9362. if (cxxRecordDecl->hasDefinition()) {
  9363. CXXRecordDecl::base_class_iterator bi, be;
  9364. bi = cxxRecordDecl->bases_begin();
  9365. be = cxxRecordDecl->bases_end();
  9366. if (bi != be) {
  9367. // Add type tracker for base.
  9368. // Add base after child to make sure base considered first.
  9369. m_typeTrackers.push_back(
  9370. FlattenedTypeIterator::FlattenedTypeTracker(type, bi, be));
  9371. bAddTracker = true;
  9372. }
  9373. }
  9374. }
  9375. return bAddTracker;
  9376. }
  9377. case ArTypeObjectKind::AR_TOBJ_MATRIX:
  9378. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9379. m_source.GetMatrixOrVectorElementType(type),
  9380. GetElementCount(type), nullptr));
  9381. return true;
  9382. case ArTypeObjectKind::AR_TOBJ_VECTOR:
  9383. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9384. m_source.GetMatrixOrVectorElementType(type),
  9385. GetHLSLVecSize(type), nullptr));
  9386. return true;
  9387. case ArTypeObjectKind::AR_TOBJ_OBJECT: {
  9388. if (m_source.IsSubobjectType(type)) {
  9389. // subobjects are initialized with initialization lists
  9390. recordType = type->getAsStructureType();
  9391. fi = recordType->getDecl()->field_begin();
  9392. fe = recordType->getDecl()->field_end();
  9393. m_typeTrackers.push_back(
  9394. FlattenedTypeIterator::FlattenedTypeTracker(type, fi, fe));
  9395. return true;
  9396. }
  9397. else {
  9398. // Object have no sub-types.
  9399. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9400. type.getCanonicalType(), 1, expression));
  9401. return true;
  9402. }
  9403. }
  9404. case ArTypeObjectKind::AR_TOBJ_STRING: {
  9405. // Strings have no sub-types.
  9406. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  9407. type.getCanonicalType(), 1, expression));
  9408. return true;
  9409. }
  9410. default:
  9411. DXASSERT(false, "unreachable");
  9412. return false;
  9413. }
  9414. }
  9415. FlattenedTypeIterator::ComparisonResult
  9416. FlattenedTypeIterator::CompareIterators(
  9417. HLSLExternalSource& source,
  9418. SourceLocation loc,
  9419. FlattenedTypeIterator& leftIter,
  9420. FlattenedTypeIterator& rightIter)
  9421. {
  9422. FlattenedTypeIterator::ComparisonResult result;
  9423. result.LeftCount = 0;
  9424. result.RightCount = 0;
  9425. result.AreElementsEqual = true; // Until proven otherwise.
  9426. result.CanConvertElements = true; // Until proven otherwise.
  9427. while (leftIter.hasCurrentElement() && rightIter.hasCurrentElement())
  9428. {
  9429. Expr* actualExpr = rightIter.getExprOrNull();
  9430. bool hasExpr = actualExpr != nullptr;
  9431. StmtExpr scratchExpr(nullptr, rightIter.getCurrentElement(), NoLoc, NoLoc);
  9432. StandardConversionSequence standard;
  9433. ExprResult convertedExpr;
  9434. if (!source.CanConvert(loc,
  9435. hasExpr ? actualExpr : &scratchExpr,
  9436. leftIter.getCurrentElement(),
  9437. ExplicitConversionFalse,
  9438. nullptr,
  9439. &standard)) {
  9440. result.AreElementsEqual = false;
  9441. result.CanConvertElements = false;
  9442. break;
  9443. }
  9444. else if (hasExpr && (standard.First != ICK_Identity || !standard.isIdentityConversion()))
  9445. {
  9446. convertedExpr = source.getSema()->PerformImplicitConversion(actualExpr,
  9447. leftIter.getCurrentElement(),
  9448. standard,
  9449. Sema::AA_Casting,
  9450. Sema::CCK_ImplicitConversion);
  9451. }
  9452. if (rightIter.getCurrentElement()->getCanonicalTypeUnqualified() !=
  9453. leftIter.getCurrentElement()->getCanonicalTypeUnqualified())
  9454. {
  9455. result.AreElementsEqual = false;
  9456. }
  9457. unsigned int advance = std::min(leftIter.getCurrentElementSize(), rightIter.getCurrentElementSize());
  9458. DXASSERT(advance > 0, "otherwise one iterator should report empty");
  9459. // If we need to apply conversions to the expressions, then advance a single element.
  9460. if (hasExpr && convertedExpr.isUsable()) {
  9461. rightIter.replaceExpr(convertedExpr.get());
  9462. advance = 1;
  9463. }
  9464. leftIter.advanceCurrentElement(advance);
  9465. rightIter.advanceCurrentElement(advance);
  9466. result.LeftCount += advance;
  9467. result.RightCount += advance;
  9468. }
  9469. result.LeftCount += leftIter.countRemaining();
  9470. result.RightCount += rightIter.countRemaining();
  9471. return result;
  9472. }
  9473. FlattenedTypeIterator::ComparisonResult
  9474. FlattenedTypeIterator::CompareTypes(
  9475. HLSLExternalSource& source,
  9476. SourceLocation leftLoc, SourceLocation rightLoc,
  9477. QualType left, QualType right)
  9478. {
  9479. FlattenedTypeIterator leftIter(leftLoc, left, source);
  9480. FlattenedTypeIterator rightIter(rightLoc, right, source);
  9481. return CompareIterators(source, leftLoc, leftIter, rightIter);
  9482. }
  9483. FlattenedTypeIterator::ComparisonResult
  9484. FlattenedTypeIterator::CompareTypesForInit(
  9485. HLSLExternalSource& source, QualType left, MultiExprArg args,
  9486. SourceLocation leftLoc, SourceLocation rightLoc)
  9487. {
  9488. FlattenedTypeIterator leftIter(leftLoc, left, source);
  9489. FlattenedTypeIterator rightIter(rightLoc, args, source);
  9490. return CompareIterators(source, leftLoc, leftIter, rightIter);
  9491. }
  9492. ////////////////////////////////////////////////////////////////////////////////
  9493. // Attribute processing support. //
  9494. static int ValidateAttributeIntArg(Sema& S, const AttributeList &Attr, unsigned index = 0)
  9495. {
  9496. int64_t value = 0;
  9497. if (Attr.getNumArgs() > index)
  9498. {
  9499. Expr *E = nullptr;
  9500. if (!Attr.isArgExpr(index)) {
  9501. // For case arg is constant variable.
  9502. IdentifierLoc *loc = Attr.getArgAsIdent(index);
  9503. VarDecl *decl = dyn_cast_or_null<VarDecl>(
  9504. S.LookupSingleName(S.getCurScope(), loc->Ident, loc->Loc,
  9505. Sema::LookupNameKind::LookupOrdinaryName));
  9506. if (!decl) {
  9507. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  9508. return value;
  9509. }
  9510. Expr *init = decl->getInit();
  9511. if (!init) {
  9512. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  9513. return value;
  9514. }
  9515. E = init;
  9516. } else
  9517. E = Attr.getArgAsExpr(index);
  9518. clang::APValue ArgNum;
  9519. bool displayError = false;
  9520. if (E->isTypeDependent() || E->isValueDependent() || !E->isCXX11ConstantExpr(S.Context, &ArgNum))
  9521. {
  9522. displayError = true;
  9523. }
  9524. else
  9525. {
  9526. if (ArgNum.isInt())
  9527. {
  9528. value = ArgNum.getInt().getSExtValue();
  9529. }
  9530. else if (ArgNum.isFloat())
  9531. {
  9532. llvm::APSInt floatInt;
  9533. bool isPrecise;
  9534. if (ArgNum.getFloat().convertToInteger(floatInt, llvm::APFloat::rmTowardZero, &isPrecise) == llvm::APFloat::opStatus::opOK)
  9535. {
  9536. value = floatInt.getSExtValue();
  9537. }
  9538. else
  9539. {
  9540. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  9541. }
  9542. }
  9543. else
  9544. {
  9545. displayError = true;
  9546. }
  9547. if (value < 0)
  9548. {
  9549. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  9550. }
  9551. }
  9552. if (displayError)
  9553. {
  9554. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
  9555. << Attr.getName() << AANT_ArgumentIntegerConstant
  9556. << E->getSourceRange();
  9557. }
  9558. }
  9559. return (int)value;
  9560. }
  9561. // TODO: support float arg directly.
  9562. static int ValidateAttributeFloatArg(Sema &S, const AttributeList &Attr,
  9563. unsigned index = 0) {
  9564. int value = 0;
  9565. if (Attr.getNumArgs() > index) {
  9566. Expr *E = Attr.getArgAsExpr(index);
  9567. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E)) {
  9568. llvm::APFloat flV = FL->getValue();
  9569. if (flV.getSizeInBits(flV.getSemantics()) == 64) {
  9570. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToDouble());
  9571. value = intV.getLimitedValue();
  9572. } else {
  9573. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToFloat());
  9574. value = intV.getLimitedValue();
  9575. }
  9576. } else if (IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  9577. llvm::APInt intV =
  9578. llvm::APInt::floatToBits((float)IL->getValue().getLimitedValue());
  9579. value = intV.getLimitedValue();
  9580. } else {
  9581. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_float_literal)
  9582. << Attr.getName();
  9583. }
  9584. }
  9585. return value;
  9586. }
  9587. static Stmt* IgnoreParensAndDecay(Stmt* S)
  9588. {
  9589. for (;;)
  9590. {
  9591. switch (S->getStmtClass())
  9592. {
  9593. case Stmt::ParenExprClass:
  9594. S = cast<ParenExpr>(S)->getSubExpr();
  9595. break;
  9596. case Stmt::ImplicitCastExprClass:
  9597. {
  9598. ImplicitCastExpr* castExpr = cast<ImplicitCastExpr>(S);
  9599. if (castExpr->getCastKind() != CK_ArrayToPointerDecay &&
  9600. castExpr->getCastKind() != CK_NoOp &&
  9601. castExpr->getCastKind() != CK_LValueToRValue)
  9602. {
  9603. return S;
  9604. }
  9605. S = castExpr->getSubExpr();
  9606. }
  9607. break;
  9608. default:
  9609. return S;
  9610. }
  9611. }
  9612. }
  9613. static Expr* ValidateClipPlaneArraySubscriptExpr(Sema& S, ArraySubscriptExpr* E)
  9614. {
  9615. DXASSERT_NOMSG(E != nullptr);
  9616. Expr* subscriptExpr = E->getIdx();
  9617. subscriptExpr = dyn_cast<Expr>(subscriptExpr->IgnoreParens());
  9618. if (subscriptExpr == nullptr ||
  9619. subscriptExpr->isTypeDependent() || subscriptExpr->isValueDependent() ||
  9620. !subscriptExpr->isCXX11ConstantExpr(S.Context))
  9621. {
  9622. S.Diag(
  9623. (subscriptExpr == nullptr) ? E->getLocStart() : subscriptExpr->getLocStart(),
  9624. diag::err_hlsl_unsupported_clipplane_argument_subscript_expression);
  9625. return nullptr;
  9626. }
  9627. return E->getBase();
  9628. }
  9629. static bool IsValidClipPlaneDecl(Decl* D)
  9630. {
  9631. Decl::Kind kind = D->getKind();
  9632. if (kind == Decl::Var)
  9633. {
  9634. VarDecl* varDecl = cast<VarDecl>(D);
  9635. if (varDecl->getStorageClass() == StorageClass::SC_Static &&
  9636. varDecl->getType().isConstQualified())
  9637. {
  9638. return false;
  9639. }
  9640. return true;
  9641. }
  9642. else if (kind == Decl::Field)
  9643. {
  9644. return true;
  9645. }
  9646. return false;
  9647. }
  9648. static Expr* ValidateClipPlaneExpr(Sema& S, Expr* E)
  9649. {
  9650. Stmt* cursor = E;
  9651. // clip plane expressions are a linear path, so no need to traverse the tree here.
  9652. while (cursor != nullptr)
  9653. {
  9654. bool supported = true;
  9655. cursor = IgnoreParensAndDecay(cursor);
  9656. switch (cursor->getStmtClass())
  9657. {
  9658. case Stmt::ArraySubscriptExprClass:
  9659. cursor = ValidateClipPlaneArraySubscriptExpr(S, cast<ArraySubscriptExpr>(cursor));
  9660. if (cursor == nullptr)
  9661. {
  9662. // nullptr indicates failure, and the error message has already been printed out
  9663. return nullptr;
  9664. }
  9665. break;
  9666. case Stmt::DeclRefExprClass:
  9667. {
  9668. DeclRefExpr* declRef = cast<DeclRefExpr>(cursor);
  9669. Decl* decl = declRef->getDecl();
  9670. supported = IsValidClipPlaneDecl(decl);
  9671. cursor = supported ? nullptr : cursor;
  9672. }
  9673. break;
  9674. case Stmt::MemberExprClass:
  9675. {
  9676. MemberExpr* member = cast<MemberExpr>(cursor);
  9677. supported = IsValidClipPlaneDecl(member->getMemberDecl());
  9678. cursor = supported ? member->getBase() : cursor;
  9679. }
  9680. break;
  9681. default:
  9682. supported = false;
  9683. break;
  9684. }
  9685. if (!supported)
  9686. {
  9687. DXASSERT(cursor != nullptr, "otherwise it was cleared when the supported flag was set to false");
  9688. S.Diag(cursor->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_expression);
  9689. return nullptr;
  9690. }
  9691. }
  9692. // Validate that the type is a float4.
  9693. QualType expressionType = E->getType();
  9694. HLSLExternalSource* hlslSource = HLSLExternalSource::FromSema(&S);
  9695. if (hlslSource->GetTypeElementKind(expressionType) != ArBasicKind::AR_BASIC_FLOAT32 ||
  9696. hlslSource->GetTypeObjectKind(expressionType) != ArTypeObjectKind::AR_TOBJ_VECTOR)
  9697. {
  9698. S.Diag(E->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_type) << expressionType;
  9699. return nullptr;
  9700. }
  9701. return E;
  9702. }
  9703. static Attr* HandleClipPlanes(Sema& S, const AttributeList &A)
  9704. {
  9705. Expr* clipExprs[6];
  9706. for (unsigned int index = 0; index < _countof(clipExprs); index++)
  9707. {
  9708. if (A.getNumArgs() <= index)
  9709. {
  9710. clipExprs[index] = nullptr;
  9711. continue;
  9712. }
  9713. Expr *E = A.getArgAsExpr(index);
  9714. clipExprs[index] = ValidateClipPlaneExpr(S, E);
  9715. }
  9716. return ::new (S.Context) HLSLClipPlanesAttr(A.getRange(), S.Context,
  9717. clipExprs[0], clipExprs[1], clipExprs[2], clipExprs[3], clipExprs[4], clipExprs[5],
  9718. A.getAttributeSpellingListIndex());
  9719. }
  9720. static Attr* HandleUnrollAttribute(Sema& S, const AttributeList &Attr)
  9721. {
  9722. int argValue = ValidateAttributeIntArg(S, Attr);
  9723. // Default value is 0 (full unroll).
  9724. if (Attr.getNumArgs() == 0) argValue = 0;
  9725. return ::new (S.Context) HLSLUnrollAttr(Attr.getRange(), S.Context,
  9726. argValue, Attr.getAttributeSpellingListIndex());
  9727. }
  9728. static void ValidateAttributeOnLoop(Sema& S, Stmt* St, const AttributeList &Attr)
  9729. {
  9730. Stmt::StmtClass stClass = St->getStmtClass();
  9731. if (stClass != Stmt::ForStmtClass && stClass != Stmt::WhileStmtClass && stClass != Stmt::DoStmtClass)
  9732. {
  9733. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  9734. << Attr.getName();
  9735. }
  9736. }
  9737. static void ValidateAttributeOnSwitch(Sema& S, Stmt* St, const AttributeList &Attr)
  9738. {
  9739. Stmt::StmtClass stClass = St->getStmtClass();
  9740. if (stClass != Stmt::SwitchStmtClass)
  9741. {
  9742. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  9743. << Attr.getName();
  9744. }
  9745. }
  9746. static void ValidateAttributeOnSwitchOrIf(Sema& S, Stmt* St, const AttributeList &Attr)
  9747. {
  9748. Stmt::StmtClass stClass = St->getStmtClass();
  9749. if (stClass != Stmt::SwitchStmtClass && stClass != Stmt::IfStmtClass)
  9750. {
  9751. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  9752. << Attr.getName();
  9753. }
  9754. }
  9755. static StringRef ValidateAttributeStringArg(Sema& S, const AttributeList &A, _In_opt_z_ const char* values, unsigned index = 0)
  9756. {
  9757. // values is an optional comma-separated list of potential values.
  9758. if (A.getNumArgs() <= index)
  9759. return StringRef();
  9760. Expr* E = A.getArgAsExpr(index);
  9761. if (E->isTypeDependent() || E->isValueDependent() || E->getStmtClass() != Stmt::StringLiteralClass)
  9762. {
  9763. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal)
  9764. << A.getName();
  9765. return StringRef();
  9766. }
  9767. StringLiteral* sl = cast<StringLiteral>(E);
  9768. StringRef result = sl->getString();
  9769. // Return result with no additional validation.
  9770. if (values == nullptr)
  9771. {
  9772. return result;
  9773. }
  9774. const char* value = values;
  9775. while (*value != '\0')
  9776. {
  9777. DXASSERT_NOMSG(*value != ','); // no leading commas in values
  9778. // Look for a match.
  9779. const char* argData = result.data();
  9780. size_t argDataLen = result.size();
  9781. while (argDataLen != 0 && *argData == *value && *value)
  9782. {
  9783. ++argData;
  9784. ++value;
  9785. --argDataLen;
  9786. }
  9787. // Match found if every input character matched.
  9788. if (argDataLen == 0 && (*value == '\0' || *value == ','))
  9789. {
  9790. return result;
  9791. }
  9792. // Move to next separator.
  9793. while (*value != '\0' && *value != ',')
  9794. {
  9795. ++value;
  9796. }
  9797. // Move to the start of the next item if any.
  9798. if (*value == ',') value++;
  9799. }
  9800. DXASSERT_NOMSG(*value == '\0'); // no other terminating conditions
  9801. // No match found.
  9802. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal_from_list)
  9803. << A.getName() << values;
  9804. return StringRef();
  9805. }
  9806. static
  9807. bool ValidateAttributeTargetIsFunction(Sema& S, Decl* D, const AttributeList &A)
  9808. {
  9809. if (D->isFunctionOrFunctionTemplate())
  9810. {
  9811. return true;
  9812. }
  9813. S.Diag(A.getLoc(), diag::err_hlsl_attribute_valid_on_function_only);
  9814. return false;
  9815. }
  9816. void hlsl::HandleDeclAttributeForHLSL(Sema &S, Decl *D, const AttributeList &A, bool& Handled)
  9817. {
  9818. DXASSERT_NOMSG(D != nullptr);
  9819. DXASSERT_NOMSG(!A.isInvalid());
  9820. Attr* declAttr = nullptr;
  9821. Handled = true;
  9822. switch (A.getKind())
  9823. {
  9824. case AttributeList::AT_HLSLIn:
  9825. declAttr = ::new (S.Context) HLSLInAttr(A.getRange(), S.Context,
  9826. A.getAttributeSpellingListIndex());
  9827. break;
  9828. case AttributeList::AT_HLSLOut:
  9829. declAttr = ::new (S.Context) HLSLOutAttr(A.getRange(), S.Context,
  9830. A.getAttributeSpellingListIndex());
  9831. break;
  9832. case AttributeList::AT_HLSLInOut:
  9833. declAttr = ::new (S.Context) HLSLInOutAttr(A.getRange(), S.Context,
  9834. A.getAttributeSpellingListIndex());
  9835. break;
  9836. case AttributeList::AT_HLSLNoInterpolation:
  9837. declAttr = ::new (S.Context) HLSLNoInterpolationAttr(A.getRange(), S.Context,
  9838. A.getAttributeSpellingListIndex());
  9839. break;
  9840. case AttributeList::AT_HLSLLinear:
  9841. case AttributeList::AT_HLSLCenter:
  9842. declAttr = ::new (S.Context) HLSLLinearAttr(A.getRange(), S.Context,
  9843. A.getAttributeSpellingListIndex());
  9844. break;
  9845. case AttributeList::AT_HLSLNoPerspective:
  9846. declAttr = ::new (S.Context) HLSLNoPerspectiveAttr(A.getRange(), S.Context,
  9847. A.getAttributeSpellingListIndex());
  9848. break;
  9849. case AttributeList::AT_HLSLSample:
  9850. declAttr = ::new (S.Context) HLSLSampleAttr(A.getRange(), S.Context,
  9851. A.getAttributeSpellingListIndex());
  9852. break;
  9853. case AttributeList::AT_HLSLCentroid:
  9854. declAttr = ::new (S.Context) HLSLCentroidAttr(A.getRange(), S.Context,
  9855. A.getAttributeSpellingListIndex());
  9856. break;
  9857. case AttributeList::AT_HLSLPrecise:
  9858. declAttr = ::new (S.Context) HLSLPreciseAttr(A.getRange(), S.Context,
  9859. A.getAttributeSpellingListIndex());
  9860. break;
  9861. case AttributeList::AT_HLSLShared:
  9862. declAttr = ::new (S.Context) HLSLSharedAttr(A.getRange(), S.Context,
  9863. A.getAttributeSpellingListIndex());
  9864. break;
  9865. case AttributeList::AT_HLSLGroupShared:
  9866. declAttr = ::new (S.Context) HLSLGroupSharedAttr(A.getRange(), S.Context,
  9867. A.getAttributeSpellingListIndex());
  9868. if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
  9869. VD->setType(S.Context.getAddrSpaceQualType(VD->getType(), DXIL::kTGSMAddrSpace));
  9870. }
  9871. break;
  9872. case AttributeList::AT_HLSLUniform:
  9873. declAttr = ::new (S.Context) HLSLUniformAttr(A.getRange(), S.Context,
  9874. A.getAttributeSpellingListIndex());
  9875. break;
  9876. case AttributeList::AT_HLSLColumnMajor:
  9877. declAttr = ::new (S.Context) HLSLColumnMajorAttr(A.getRange(), S.Context,
  9878. A.getAttributeSpellingListIndex());
  9879. break;
  9880. case AttributeList::AT_HLSLRowMajor:
  9881. declAttr = ::new (S.Context) HLSLRowMajorAttr(A.getRange(), S.Context,
  9882. A.getAttributeSpellingListIndex());
  9883. break;
  9884. case AttributeList::AT_HLSLUnorm:
  9885. declAttr = ::new (S.Context) HLSLUnormAttr(A.getRange(), S.Context,
  9886. A.getAttributeSpellingListIndex());
  9887. break;
  9888. case AttributeList::AT_HLSLSnorm:
  9889. declAttr = ::new (S.Context) HLSLSnormAttr(A.getRange(), S.Context,
  9890. A.getAttributeSpellingListIndex());
  9891. break;
  9892. case AttributeList::AT_HLSLPoint:
  9893. declAttr = ::new (S.Context) HLSLPointAttr(A.getRange(), S.Context,
  9894. A.getAttributeSpellingListIndex());
  9895. break;
  9896. case AttributeList::AT_HLSLLine:
  9897. declAttr = ::new (S.Context) HLSLLineAttr(A.getRange(), S.Context,
  9898. A.getAttributeSpellingListIndex());
  9899. break;
  9900. case AttributeList::AT_HLSLLineAdj:
  9901. declAttr = ::new (S.Context) HLSLLineAdjAttr(A.getRange(), S.Context,
  9902. A.getAttributeSpellingListIndex());
  9903. break;
  9904. case AttributeList::AT_HLSLTriangle:
  9905. declAttr = ::new (S.Context) HLSLTriangleAttr(A.getRange(), S.Context,
  9906. A.getAttributeSpellingListIndex());
  9907. break;
  9908. case AttributeList::AT_HLSLTriangleAdj:
  9909. declAttr = ::new (S.Context) HLSLTriangleAdjAttr(A.getRange(), S.Context,
  9910. A.getAttributeSpellingListIndex());
  9911. break;
  9912. case AttributeList::AT_HLSLGloballyCoherent:
  9913. declAttr = ::new (S.Context) HLSLGloballyCoherentAttr(
  9914. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9915. break;
  9916. case AttributeList::AT_HLSLIndices:
  9917. declAttr = ::new (S.Context) HLSLIndicesAttr(
  9918. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9919. break;
  9920. case AttributeList::AT_HLSLVertices:
  9921. declAttr = ::new (S.Context) HLSLVerticesAttr(
  9922. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9923. break;
  9924. case AttributeList::AT_HLSLPrimitives:
  9925. declAttr = ::new (S.Context) HLSLPrimitivesAttr(
  9926. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9927. break;
  9928. case AttributeList::AT_HLSLPayload:
  9929. declAttr = ::new (S.Context) HLSLPayloadAttr(
  9930. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9931. break;
  9932. default:
  9933. Handled = false;
  9934. break;
  9935. }
  9936. if (declAttr != nullptr)
  9937. {
  9938. DXASSERT_NOMSG(Handled);
  9939. D->addAttr(declAttr);
  9940. return;
  9941. }
  9942. Handled = true;
  9943. switch (A.getKind())
  9944. {
  9945. // These apply to statements, not declarations. The warning messages clarify this properly.
  9946. case AttributeList::AT_HLSLUnroll:
  9947. case AttributeList::AT_HLSLAllowUAVCondition:
  9948. case AttributeList::AT_HLSLLoop:
  9949. case AttributeList::AT_HLSLFastOpt:
  9950. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  9951. << A.getName();
  9952. return;
  9953. case AttributeList::AT_HLSLBranch:
  9954. case AttributeList::AT_HLSLFlatten:
  9955. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  9956. << A.getName();
  9957. return;
  9958. case AttributeList::AT_HLSLForceCase:
  9959. case AttributeList::AT_HLSLCall:
  9960. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  9961. << A.getName();
  9962. return;
  9963. // These are the cases that actually apply to declarations.
  9964. case AttributeList::AT_HLSLClipPlanes:
  9965. declAttr = HandleClipPlanes(S, A);
  9966. break;
  9967. case AttributeList::AT_HLSLDomain:
  9968. declAttr = ::new (S.Context) HLSLDomainAttr(A.getRange(), S.Context,
  9969. ValidateAttributeStringArg(S, A, "tri,quad,isoline"), A.getAttributeSpellingListIndex());
  9970. break;
  9971. case AttributeList::AT_HLSLEarlyDepthStencil:
  9972. declAttr = ::new (S.Context) HLSLEarlyDepthStencilAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9973. break;
  9974. case AttributeList::AT_HLSLInstance:
  9975. declAttr = ::new (S.Context) HLSLInstanceAttr(A.getRange(), S.Context,
  9976. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9977. break;
  9978. case AttributeList::AT_HLSLMaxTessFactor:
  9979. declAttr = ::new (S.Context) HLSLMaxTessFactorAttr(A.getRange(), S.Context,
  9980. ValidateAttributeFloatArg(S, A), A.getAttributeSpellingListIndex());
  9981. break;
  9982. case AttributeList::AT_HLSLNumThreads:
  9983. declAttr = ::new (S.Context) HLSLNumThreadsAttr(A.getRange(), S.Context,
  9984. ValidateAttributeIntArg(S, A), ValidateAttributeIntArg(S, A, 1), ValidateAttributeIntArg(S, A, 2),
  9985. A.getAttributeSpellingListIndex());
  9986. break;
  9987. case AttributeList::AT_HLSLRootSignature:
  9988. declAttr = ::new (S.Context) HLSLRootSignatureAttr(A.getRange(), S.Context,
  9989. ValidateAttributeStringArg(S, A, /*validate strings*/nullptr),
  9990. A.getAttributeSpellingListIndex());
  9991. break;
  9992. case AttributeList::AT_HLSLOutputControlPoints:
  9993. declAttr = ::new (S.Context) HLSLOutputControlPointsAttr(A.getRange(), S.Context,
  9994. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9995. break;
  9996. case AttributeList::AT_HLSLOutputTopology:
  9997. declAttr = ::new (S.Context) HLSLOutputTopologyAttr(A.getRange(), S.Context,
  9998. ValidateAttributeStringArg(S, A, "point,line,triangle,triangle_cw,triangle_ccw"), A.getAttributeSpellingListIndex());
  9999. break;
  10000. case AttributeList::AT_HLSLPartitioning:
  10001. declAttr = ::new (S.Context) HLSLPartitioningAttr(A.getRange(), S.Context,
  10002. ValidateAttributeStringArg(S, A, "integer,fractional_even,fractional_odd,pow2"), A.getAttributeSpellingListIndex());
  10003. break;
  10004. case AttributeList::AT_HLSLPatchConstantFunc:
  10005. declAttr = ::new (S.Context) HLSLPatchConstantFuncAttr(A.getRange(), S.Context,
  10006. ValidateAttributeStringArg(S, A, nullptr), A.getAttributeSpellingListIndex());
  10007. break;
  10008. case AttributeList::AT_HLSLShader:
  10009. declAttr = ::new (S.Context) HLSLShaderAttr(
  10010. A.getRange(), S.Context,
  10011. ValidateAttributeStringArg(
  10012. S, A,
  10013. "compute,vertex,pixel,hull,domain,geometry,raygeneration,"
  10014. "intersection,anyhit,closesthit,miss,callable,mesh,amplification"),
  10015. A.getAttributeSpellingListIndex());
  10016. break;
  10017. case AttributeList::AT_HLSLMaxVertexCount:
  10018. declAttr = ::new (S.Context) HLSLMaxVertexCountAttr(A.getRange(), S.Context,
  10019. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10020. break;
  10021. case AttributeList::AT_HLSLExperimental:
  10022. declAttr = ::new (S.Context) HLSLExperimentalAttr(A.getRange(), S.Context,
  10023. ValidateAttributeStringArg(S, A, nullptr, 0), ValidateAttributeStringArg(S, A, nullptr, 1),
  10024. A.getAttributeSpellingListIndex());
  10025. break;
  10026. case AttributeList::AT_NoInline:
  10027. declAttr = ::new (S.Context) NoInlineAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10028. break;
  10029. case AttributeList::AT_HLSLExport:
  10030. declAttr = ::new (S.Context) HLSLExportAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10031. break;
  10032. case AttributeList::AT_HLSLWaveSensitive:
  10033. declAttr = ::new (S.Context) HLSLWaveSensitiveAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10034. break;
  10035. default:
  10036. Handled = false;
  10037. break; // SPIRV Change: was return;
  10038. }
  10039. if (declAttr != nullptr)
  10040. {
  10041. DXASSERT_NOMSG(Handled);
  10042. D->addAttr(declAttr);
  10043. // The attribute has been set but will have no effect. Validation will emit a diagnostic
  10044. // and prevent code generation.
  10045. ValidateAttributeTargetIsFunction(S, D, A);
  10046. return; // SPIRV Change
  10047. }
  10048. // SPIRV Change Starts
  10049. Handled = true;
  10050. switch (A.getKind())
  10051. {
  10052. case AttributeList::AT_VKBuiltIn:
  10053. declAttr = ::new (S.Context) VKBuiltInAttr(A.getRange(), S.Context,
  10054. ValidateAttributeStringArg(S, A, "PointSize,HelperInvocation,BaseVertex,BaseInstance,DrawIndex,DeviceIndex,ViewportMaskNV"),
  10055. A.getAttributeSpellingListIndex());
  10056. break;
  10057. case AttributeList::AT_VKLocation:
  10058. declAttr = ::new (S.Context) VKLocationAttr(A.getRange(), S.Context,
  10059. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10060. break;
  10061. case AttributeList::AT_VKIndex:
  10062. declAttr = ::new (S.Context) VKIndexAttr(A.getRange(), S.Context,
  10063. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10064. break;
  10065. case AttributeList::AT_VKBinding:
  10066. declAttr = ::new (S.Context) VKBindingAttr(
  10067. A.getRange(), S.Context, ValidateAttributeIntArg(S, A),
  10068. A.getNumArgs() < 2 ? INT_MIN : ValidateAttributeIntArg(S, A, 1),
  10069. A.getAttributeSpellingListIndex());
  10070. break;
  10071. case AttributeList::AT_VKCounterBinding:
  10072. declAttr = ::new (S.Context) VKCounterBindingAttr(A.getRange(), S.Context,
  10073. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10074. break;
  10075. case AttributeList::AT_VKPushConstant:
  10076. declAttr = ::new (S.Context) VKPushConstantAttr(A.getRange(), S.Context,
  10077. A.getAttributeSpellingListIndex());
  10078. break;
  10079. case AttributeList::AT_VKOffset:
  10080. declAttr = ::new (S.Context) VKOffsetAttr(A.getRange(), S.Context,
  10081. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10082. break;
  10083. case AttributeList::AT_VKInputAttachmentIndex:
  10084. declAttr = ::new (S.Context) VKInputAttachmentIndexAttr(
  10085. A.getRange(), S.Context, ValidateAttributeIntArg(S, A),
  10086. A.getAttributeSpellingListIndex());
  10087. break;
  10088. case AttributeList::AT_VKConstantId:
  10089. declAttr = ::new (S.Context) VKConstantIdAttr(A.getRange(), S.Context,
  10090. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  10091. break;
  10092. case AttributeList::AT_VKPostDepthCoverage:
  10093. declAttr = ::new (S.Context) VKPostDepthCoverageAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10094. break;
  10095. case AttributeList::AT_VKShaderRecordNV:
  10096. declAttr = ::new (S.Context) VKShaderRecordNVAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10097. break;
  10098. default:
  10099. Handled = false;
  10100. return;
  10101. }
  10102. if (declAttr != nullptr)
  10103. {
  10104. DXASSERT_NOMSG(Handled);
  10105. D->addAttr(declAttr);
  10106. }
  10107. // SPIRV Change Ends
  10108. }
  10109. /// <summary>Processes an attribute for a statement.</summary>
  10110. /// <param name="S">Sema with context.</param>
  10111. /// <param name="St">Statement annotated.</param>
  10112. /// <param name="A">Single parsed attribute to process.</param>
  10113. /// <param name="Range">Range of all attribute lists (useful for FixIts to suggest inclusions).</param>
  10114. /// <param name="Handled">After execution, whether this was recognized and handled.</param>
  10115. /// <returns>An attribute instance if processed, nullptr if not recognized or an error was found.</returns>
  10116. Attr *hlsl::ProcessStmtAttributeForHLSL(Sema &S, Stmt *St, const AttributeList &A, SourceRange Range, bool& Handled)
  10117. {
  10118. // | Construct | Allowed Attributes |
  10119. // +------------------+--------------------------------------------+
  10120. // | for, while, do | loop, fastopt, unroll, allow_uav_condition |
  10121. // | if | branch, flatten |
  10122. // | switch | branch, flatten, forcecase, call |
  10123. Attr * result = nullptr;
  10124. Handled = true;
  10125. switch (A.getKind())
  10126. {
  10127. case AttributeList::AT_HLSLUnroll:
  10128. ValidateAttributeOnLoop(S, St, A);
  10129. result = HandleUnrollAttribute(S, A);
  10130. break;
  10131. case AttributeList::AT_HLSLAllowUAVCondition:
  10132. ValidateAttributeOnLoop(S, St, A);
  10133. result = ::new (S.Context) HLSLAllowUAVConditionAttr(
  10134. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10135. break;
  10136. case AttributeList::AT_HLSLLoop:
  10137. ValidateAttributeOnLoop(S, St, A);
  10138. result = ::new (S.Context) HLSLLoopAttr(
  10139. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10140. break;
  10141. case AttributeList::AT_HLSLFastOpt:
  10142. ValidateAttributeOnLoop(S, St, A);
  10143. result = ::new (S.Context) HLSLFastOptAttr(
  10144. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10145. break;
  10146. case AttributeList::AT_HLSLBranch:
  10147. ValidateAttributeOnSwitchOrIf(S, St, A);
  10148. result = ::new (S.Context) HLSLBranchAttr(
  10149. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10150. break;
  10151. case AttributeList::AT_HLSLFlatten:
  10152. ValidateAttributeOnSwitchOrIf(S, St, A);
  10153. result = ::new (S.Context) HLSLFlattenAttr(
  10154. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10155. break;
  10156. case AttributeList::AT_HLSLForceCase:
  10157. ValidateAttributeOnSwitch(S, St, A);
  10158. result = ::new (S.Context) HLSLForceCaseAttr(
  10159. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10160. break;
  10161. case AttributeList::AT_HLSLCall:
  10162. ValidateAttributeOnSwitch(S, St, A);
  10163. result = ::new (S.Context) HLSLCallAttr(
  10164. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  10165. break;
  10166. default:
  10167. Handled = false;
  10168. break;
  10169. }
  10170. return result;
  10171. }
  10172. ////////////////////////////////////////////////////////////////////////////////
  10173. // Implementation of Sema members. //
  10174. Decl* Sema::ActOnStartHLSLBuffer(
  10175. Scope* bufferScope,
  10176. bool cbuffer, SourceLocation KwLoc,
  10177. IdentifierInfo *Ident, SourceLocation IdentLoc,
  10178. std::vector<hlsl::UnusualAnnotation *>& BufferAttributes,
  10179. SourceLocation LBrace)
  10180. {
  10181. // For anonymous namespace, take the location of the left brace.
  10182. DeclContext* lexicalParent = getCurLexicalContext();
  10183. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  10184. Context, lexicalParent, cbuffer, /*isConstantBufferView*/ false, KwLoc,
  10185. Ident, IdentLoc, BufferAttributes, LBrace);
  10186. // Keep track of the currently active buffer.
  10187. HLSLBuffers.push_back(result);
  10188. // Validate unusual annotations and emit diagnostics.
  10189. DiagnoseUnusualAnnotationsForHLSL(*this, BufferAttributes);
  10190. auto && unusualIter = BufferAttributes.begin();
  10191. auto && unusualEnd = BufferAttributes.end();
  10192. char expectedRegisterType = cbuffer ? 'b' : 't';
  10193. for (; unusualIter != unusualEnd; ++unusualIter) {
  10194. switch ((*unusualIter)->getKind()) {
  10195. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  10196. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*unusualIter);
  10197. Diag(constantPacking->Loc, diag::err_hlsl_unsupported_buffer_packoffset);
  10198. break;
  10199. }
  10200. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  10201. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*unusualIter);
  10202. if (registerAssignment->isSpaceOnly())
  10203. continue;
  10204. if (registerAssignment->RegisterType != expectedRegisterType && registerAssignment->RegisterType != toupper(expectedRegisterType)) {
  10205. Diag(registerAssignment->Loc, diag::err_hlsl_incorrect_bind_semantic) << (cbuffer ? "'b'" : "'t'");
  10206. } else if (registerAssignment->ShaderProfile.size() > 0) {
  10207. Diag(registerAssignment->Loc, diag::err_hlsl_unsupported_buffer_slot_target_specific);
  10208. }
  10209. break;
  10210. }
  10211. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  10212. // Ignore semantic declarations.
  10213. break;
  10214. }
  10215. }
  10216. }
  10217. PushOnScopeChains(result, bufferScope);
  10218. PushDeclContext(bufferScope, result);
  10219. ActOnDocumentableDecl(result);
  10220. return result;
  10221. }
  10222. void Sema::ActOnFinishHLSLBuffer(Decl *Dcl, SourceLocation RBrace)
  10223. {
  10224. DXASSERT_NOMSG(Dcl != nullptr);
  10225. DXASSERT(Dcl == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  10226. dyn_cast<HLSLBufferDecl>(Dcl)->setRBraceLoc(RBrace);
  10227. HLSLBuffers.pop_back();
  10228. PopDeclContext();
  10229. }
  10230. Decl* Sema::getActiveHLSLBuffer() const
  10231. {
  10232. return HLSLBuffers.empty() ? nullptr : HLSLBuffers.back();
  10233. }
  10234. Decl *Sema::ActOnHLSLBufferView(Scope *bufferScope, SourceLocation KwLoc,
  10235. DeclGroupPtrTy &dcl, bool iscbuf) {
  10236. DXASSERT(nullptr == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  10237. HLSLBuffers.pop_back();
  10238. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  10239. Decl *decl = dcl.get().getSingleDecl();
  10240. NamedDecl *namedDecl = cast<NamedDecl>(decl);
  10241. IdentifierInfo *Ident = namedDecl->getIdentifier();
  10242. // No anonymous namespace for ConstantBuffer, take the location of the decl.
  10243. SourceLocation Loc = decl->getLocation();
  10244. // Prevent array type in template. The only way to specify an array in the template type
  10245. // is to use a typedef, so we will strip non-typedef arrays off, since these are the legal
  10246. // array dimensions for the CBV/TBV, and if any array type remains, that is illegal.
  10247. QualType declType = cast<VarDecl>(namedDecl)->getType();
  10248. while (declType->isArrayType() && declType->getTypeClass() != Type::TypeClass::Typedef) {
  10249. const ArrayType *arrayType = declType->getAsArrayTypeUnsafe();
  10250. declType = arrayType->getElementType();
  10251. }
  10252. // Check to make that sure only structs are allowed as parameter types for
  10253. // ConstantBuffer and TextureBuffer.
  10254. if (!declType->isStructureType()) {
  10255. Diag(decl->getLocStart(),
  10256. diag::err_hlsl_typeintemplateargument_requires_struct)
  10257. << declType;
  10258. return nullptr;
  10259. }
  10260. std::vector<hlsl::UnusualAnnotation *> hlslAttrs;
  10261. DeclContext *lexicalParent = getCurLexicalContext();
  10262. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  10263. Context, lexicalParent, iscbuf, /*isConstantBufferView*/ true,
  10264. KwLoc, Ident, Loc, hlslAttrs, Loc);
  10265. // set relation
  10266. namedDecl->setDeclContext(result);
  10267. result->addDecl(namedDecl);
  10268. // move attribute from constant to constant buffer
  10269. result->setUnusualAnnotations(namedDecl->getUnusualAnnotations());
  10270. namedDecl->setUnusualAnnotations(hlslAttrs);
  10271. return result;
  10272. }
  10273. bool Sema::IsOnHLSLBufferView() {
  10274. // nullptr will not pushed for cbuffer.
  10275. return !HLSLBuffers.empty() && getActiveHLSLBuffer() == nullptr;
  10276. }
  10277. void Sema::ActOnStartHLSLBufferView() {
  10278. // Push nullptr to mark HLSLBufferView.
  10279. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  10280. HLSLBuffers.emplace_back(nullptr);
  10281. }
  10282. HLSLBufferDecl::HLSLBufferDecl(
  10283. DeclContext *DC, bool cbuffer, bool cbufferView, SourceLocation KwLoc,
  10284. IdentifierInfo *Id, SourceLocation IdLoc,
  10285. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  10286. SourceLocation LBrace)
  10287. : NamedDecl(Decl::HLSLBuffer, DC, IdLoc, DeclarationName(Id)),
  10288. DeclContext(Decl::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc),
  10289. IsCBuffer(cbuffer), IsConstantBufferView(cbufferView) {
  10290. if (!BufferAttributes.empty()) {
  10291. setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  10292. getASTContext(), BufferAttributes.data(), BufferAttributes.size()));
  10293. }
  10294. }
  10295. HLSLBufferDecl *
  10296. HLSLBufferDecl::Create(ASTContext &C, DeclContext *lexicalParent, bool cbuffer,
  10297. bool constantbuffer, SourceLocation KwLoc,
  10298. IdentifierInfo *Id, SourceLocation IdLoc,
  10299. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  10300. SourceLocation LBrace) {
  10301. DeclContext *DC = C.getTranslationUnitDecl();
  10302. HLSLBufferDecl *result = ::new (C) HLSLBufferDecl(
  10303. DC, cbuffer, constantbuffer, KwLoc, Id, IdLoc, BufferAttributes, LBrace);
  10304. if (DC != lexicalParent) {
  10305. result->setLexicalDeclContext(lexicalParent);
  10306. }
  10307. return result;
  10308. }
  10309. const char *HLSLBufferDecl::getDeclKindName() const {
  10310. static const char *HLSLBufferNames[] = {"tbuffer", "cbuffer", "TextureBuffer",
  10311. "ConstantBuffer"};
  10312. unsigned index = (unsigned ) isCBuffer() | (isConstantBufferView()) << 1;
  10313. return HLSLBufferNames[index];
  10314. }
  10315. void Sema::TransferUnusualAttributes(Declarator &D, NamedDecl *NewDecl) {
  10316. assert(NewDecl != nullptr);
  10317. if (!getLangOpts().HLSL) {
  10318. return;
  10319. }
  10320. if (!D.UnusualAnnotations.empty()) {
  10321. NewDecl->setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  10322. getASTContext(), D.UnusualAnnotations.data(),
  10323. D.UnusualAnnotations.size()));
  10324. D.UnusualAnnotations.clear();
  10325. }
  10326. }
  10327. /// Checks whether a usage attribute is compatible with those seen so far and
  10328. /// maintains history.
  10329. static bool IsUsageAttributeCompatible(AttributeList::Kind kind, bool &usageIn,
  10330. bool &usageOut) {
  10331. switch (kind) {
  10332. case AttributeList::AT_HLSLIn:
  10333. if (usageIn)
  10334. return false;
  10335. usageIn = true;
  10336. break;
  10337. case AttributeList::AT_HLSLOut:
  10338. if (usageOut)
  10339. return false;
  10340. usageOut = true;
  10341. break;
  10342. default:
  10343. assert(kind == AttributeList::AT_HLSLInOut);
  10344. if (usageOut || usageIn)
  10345. return false;
  10346. usageIn = usageOut = true;
  10347. break;
  10348. }
  10349. return true;
  10350. }
  10351. // Diagnose valid/invalid modifiers for HLSL.
  10352. bool Sema::DiagnoseHLSLDecl(Declarator &D, DeclContext *DC, Expr *BitWidth,
  10353. TypeSourceInfo *TInfo, bool isParameter) {
  10354. assert(getLangOpts().HLSL &&
  10355. "otherwise this is called without checking language first");
  10356. // NOTE: some tests may declare templates.
  10357. if (DC->isNamespace() || DC->isDependentContext()) return true;
  10358. DeclSpec::SCS storage = D.getDeclSpec().getStorageClassSpec();
  10359. assert(!DC->isClosure() && "otherwise parser accepted closure syntax instead of failing with a syntax error");
  10360. assert(!DC->isDependentContext() && "otherwise parser accepted a template instead of failing with a syntax error");
  10361. assert(!DC->isNamespace() && "otherwise parser accepted a namespace instead of failing a syntax error");
  10362. bool result = true;
  10363. bool isTypedef = storage == DeclSpec::SCS_typedef;
  10364. bool isFunction = D.isFunctionDeclarator() && !DC->isRecord();
  10365. bool isLocalVar = DC->isFunctionOrMethod() && !isFunction && !isTypedef;
  10366. bool isGlobal = !isParameter && !isTypedef && !isFunction && (DC->isTranslationUnit() || DC->getDeclKind() == Decl::HLSLBuffer);
  10367. bool isMethod = DC->isRecord() && D.isFunctionDeclarator() && !isTypedef;
  10368. bool isField = DC->isRecord() && !D.isFunctionDeclarator() && !isTypedef;
  10369. bool isConst = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_const;
  10370. bool isVolatile = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_volatile;
  10371. bool isStatic = storage == DeclSpec::SCS::SCS_static;
  10372. bool isExtern = storage == DeclSpec::SCS::SCS_extern;
  10373. bool hasSignSpec = D.getDeclSpec().getTypeSpecSign() != DeclSpec::TSS::TSS_unspecified;
  10374. // Function declarations are not allowed in parameter declaration
  10375. // TODO : Remove this check once we support function declarations/pointers in HLSL
  10376. if (isParameter && isFunction) {
  10377. Diag(D.getLocStart(), diag::err_hlsl_func_in_func_decl);
  10378. D.setInvalidType();
  10379. return false;
  10380. }
  10381. assert(
  10382. (1 == (isLocalVar ? 1 : 0) + (isGlobal ? 1 : 0) + (isField ? 1 : 0) +
  10383. (isTypedef ? 1 : 0) + (isFunction ? 1 : 0) + (isMethod ? 1 : 0) +
  10384. (isParameter ? 1 : 0))
  10385. && "exactly one type of declarator is being processed");
  10386. // qt/pType captures either the type being modified, or the return type in the
  10387. // case of a function (or method).
  10388. QualType qt = TInfo->getType();
  10389. const Type* pType = qt.getTypePtrOrNull();
  10390. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(this);
  10391. // Early checks - these are not simple attribution errors, but constructs that
  10392. // are fundamentally unsupported,
  10393. // and so we avoid errors that might indicate they can be repaired.
  10394. if (DC->isRecord()) {
  10395. unsigned int nestedDiagId = 0;
  10396. if (isTypedef) {
  10397. nestedDiagId = diag::err_hlsl_unsupported_nested_typedef;
  10398. }
  10399. if (isField && pType && pType->isIncompleteArrayType()) {
  10400. nestedDiagId = diag::err_hlsl_unsupported_incomplete_array;
  10401. }
  10402. if (nestedDiagId) {
  10403. Diag(D.getLocStart(), nestedDiagId);
  10404. D.setInvalidType();
  10405. return false;
  10406. }
  10407. }
  10408. // String and subobject declarations are supported only as top level global variables.
  10409. // Const and static modifiers are implied - add them if missing.
  10410. if ((hlsl::IsStringType(qt) || hlslSource->IsSubobjectType(qt)) && !D.isInvalidType()) {
  10411. // string are supported only as top level global variables
  10412. if (!DC->isTranslationUnit()) {
  10413. Diag(D.getLocStart(), diag::err_hlsl_object_not_global) << (int)hlsl::IsStringType(qt);
  10414. result = false;
  10415. }
  10416. if (isExtern) {
  10417. Diag(D.getLocStart(), diag::err_hlsl_object_extern_not_supported) << (int)hlsl::IsStringType(qt);
  10418. result = false;
  10419. }
  10420. const char *PrevSpec = nullptr;
  10421. unsigned DiagID = 0;
  10422. if (!isStatic) {
  10423. D.getMutableDeclSpec().SetStorageClassSpec(*this, DeclSpec::SCS_static, D.getLocStart(), PrevSpec, DiagID, Context.getPrintingPolicy());
  10424. isStatic = true;
  10425. }
  10426. if (!isConst) {
  10427. D.getMutableDeclSpec().SetTypeQual(DeclSpec::TQ_const, D.getLocStart(), PrevSpec, DiagID, getLangOpts());
  10428. isConst = true;
  10429. }
  10430. }
  10431. const char* declarationType =
  10432. (isLocalVar) ? "local variable" :
  10433. (isTypedef) ? "typedef" :
  10434. (isFunction) ? "function" :
  10435. (isMethod) ? "method" :
  10436. (isGlobal) ? "global variable" :
  10437. (isParameter) ? "parameter" :
  10438. (isField) ? "field" : "<unknown>";
  10439. if (pType && D.isFunctionDeclarator()) {
  10440. const FunctionProtoType *pFP = pType->getAs<FunctionProtoType>();
  10441. if (pFP) {
  10442. qt = pFP->getReturnType();
  10443. pType = qt.getTypePtrOrNull();
  10444. // prohibit string as a return type
  10445. if (hlsl::IsStringType(qt)) {
  10446. static const unsigned selectReturnValueIdx = 2;
  10447. Diag(D.getLocStart(), diag::err_hlsl_unsupported_string_decl) << selectReturnValueIdx;
  10448. D.setInvalidType();
  10449. }
  10450. }
  10451. }
  10452. // Check for deprecated effect object type here, warn, and invalidate decl
  10453. bool bDeprecatedEffectObject = false;
  10454. bool bIsObject = false;
  10455. if (hlsl::IsObjectType(this, qt, &bDeprecatedEffectObject)) {
  10456. bIsObject = true;
  10457. if (bDeprecatedEffectObject) {
  10458. Diag(D.getLocStart(), diag::warn_hlsl_effect_object);
  10459. D.setInvalidType();
  10460. return false;
  10461. }
  10462. // Add methods if not ready.
  10463. hlslSource->AddHLSLObjectMethodsIfNotReady(qt);
  10464. } else if (qt->isArrayType()) {
  10465. QualType eltQt(qt->getArrayElementTypeNoTypeQual(), 0);
  10466. while (eltQt->isArrayType())
  10467. eltQt = QualType(eltQt->getArrayElementTypeNoTypeQual(), 0);
  10468. if (hlsl::IsObjectType(this, eltQt, &bDeprecatedEffectObject)) {
  10469. // Add methods if not ready.
  10470. hlslSource->AddHLSLObjectMethodsIfNotReady(eltQt);
  10471. bIsObject = true;
  10472. }
  10473. }
  10474. if (isExtern) {
  10475. if (!(isFunction || isGlobal)) {
  10476. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'extern'"
  10477. << declarationType;
  10478. result = false;
  10479. }
  10480. }
  10481. if (isStatic) {
  10482. if (!(isLocalVar || isGlobal || isFunction || isMethod || isField)) {
  10483. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'static'"
  10484. << declarationType;
  10485. result = false;
  10486. }
  10487. }
  10488. if (isVolatile) {
  10489. if (!(isLocalVar || isTypedef)) {
  10490. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'volatile'"
  10491. << declarationType;
  10492. result = false;
  10493. }
  10494. }
  10495. if (isConst) {
  10496. if (isField && !isStatic) {
  10497. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'const'"
  10498. << declarationType;
  10499. result = false;
  10500. }
  10501. }
  10502. ArBasicKind basicKind = hlslSource->GetTypeElementKind(qt);
  10503. if (hasSignSpec) {
  10504. ArTypeObjectKind objKind = hlslSource->GetTypeObjectKind(qt);
  10505. // vectors or matrices can only have unsigned integer types.
  10506. if (objKind == AR_TOBJ_MATRIX || objKind == AR_TOBJ_VECTOR || objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY) {
  10507. if (!IS_BASIC_UNSIGNABLE(basicKind)) {
  10508. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec)
  10509. << g_ArBasicTypeNames[basicKind];
  10510. result = false;
  10511. }
  10512. }
  10513. else {
  10514. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec) << g_ArBasicTypeNames[basicKind];
  10515. result = false;
  10516. }
  10517. }
  10518. // Validate attributes
  10519. clang::AttributeList
  10520. *pUniform = nullptr,
  10521. *pUsage = nullptr,
  10522. *pNoInterpolation = nullptr,
  10523. *pLinear = nullptr,
  10524. *pNoPerspective = nullptr,
  10525. *pSample = nullptr,
  10526. *pCentroid = nullptr,
  10527. *pCenter = nullptr,
  10528. *pAnyLinear = nullptr, // first linear attribute found
  10529. *pTopology = nullptr,
  10530. *pMeshModifier = nullptr;
  10531. bool usageIn = false;
  10532. bool usageOut = false;
  10533. for (clang::AttributeList *pAttr = D.getDeclSpec().getAttributes().getList();
  10534. pAttr != NULL; pAttr = pAttr->getNext()) {
  10535. if (pAttr->isInvalid() || pAttr->isUsedAsTypeAttr())
  10536. continue;
  10537. switch (pAttr->getKind()) {
  10538. case AttributeList::AT_HLSLPrecise: // precise is applicable everywhere.
  10539. break;
  10540. case AttributeList::AT_HLSLShared:
  10541. if (!isGlobal) {
  10542. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10543. << pAttr->getName() << declarationType << pAttr->getRange();
  10544. result = false;
  10545. }
  10546. if (isStatic) {
  10547. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10548. << "'static'" << pAttr->getName() << declarationType
  10549. << pAttr->getRange();
  10550. result = false;
  10551. }
  10552. break;
  10553. case AttributeList::AT_HLSLGroupShared:
  10554. if (!isGlobal) {
  10555. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10556. << pAttr->getName() << declarationType << pAttr->getRange();
  10557. result = false;
  10558. }
  10559. if (isExtern) {
  10560. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10561. << "'extern'" << pAttr->getName() << declarationType
  10562. << pAttr->getRange();
  10563. result = false;
  10564. }
  10565. break;
  10566. case AttributeList::AT_HLSLGloballyCoherent:
  10567. if (!bIsObject) {
  10568. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10569. << pAttr->getName() << "non-UAV type";
  10570. result = false;
  10571. }
  10572. break;
  10573. case AttributeList::AT_HLSLUniform:
  10574. if (!(isGlobal || isParameter)) {
  10575. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10576. << pAttr->getName() << declarationType << pAttr->getRange();
  10577. result = false;
  10578. }
  10579. if (isStatic) {
  10580. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10581. << "'static'" << pAttr->getName() << declarationType
  10582. << pAttr->getRange();
  10583. result = false;
  10584. }
  10585. pUniform = pAttr;
  10586. break;
  10587. case AttributeList::AT_HLSLIn:
  10588. case AttributeList::AT_HLSLOut:
  10589. case AttributeList::AT_HLSLInOut:
  10590. if (!isParameter) {
  10591. Diag(pAttr->getLoc(), diag::err_hlsl_usage_not_on_parameter)
  10592. << pAttr->getName() << pAttr->getRange();
  10593. result = false;
  10594. }
  10595. if (!IsUsageAttributeCompatible(pAttr->getKind(), usageIn, usageOut)) {
  10596. Diag(pAttr->getLoc(), diag::err_hlsl_duplicate_parameter_usages)
  10597. << pAttr->getName() << pAttr->getRange();
  10598. result = false;
  10599. }
  10600. pUsage = pAttr;
  10601. break;
  10602. case AttributeList::AT_HLSLNoInterpolation:
  10603. if (!(isParameter || isField || isFunction)) {
  10604. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10605. << pAttr->getName() << declarationType << pAttr->getRange();
  10606. result = false;
  10607. }
  10608. if (pNoInterpolation) {
  10609. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10610. << pAttr->getName() << pAttr->getRange();
  10611. }
  10612. pNoInterpolation = pAttr;
  10613. break;
  10614. case AttributeList::AT_HLSLLinear:
  10615. case AttributeList::AT_HLSLCenter:
  10616. case AttributeList::AT_HLSLNoPerspective:
  10617. case AttributeList::AT_HLSLSample:
  10618. case AttributeList::AT_HLSLCentroid:
  10619. if (!(isParameter || isField || isFunction)) {
  10620. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10621. << pAttr->getName() << declarationType << pAttr->getRange();
  10622. result = false;
  10623. }
  10624. if (nullptr == pAnyLinear)
  10625. pAnyLinear = pAttr;
  10626. switch (pAttr->getKind()) {
  10627. case AttributeList::AT_HLSLLinear:
  10628. if (pLinear) {
  10629. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10630. << pAttr->getName() << pAttr->getRange();
  10631. }
  10632. pLinear = pAttr;
  10633. break;
  10634. case AttributeList::AT_HLSLCenter:
  10635. if (pCenter) {
  10636. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10637. << pAttr->getName() << pAttr->getRange();
  10638. }
  10639. pCenter = pAttr;
  10640. break;
  10641. case AttributeList::AT_HLSLNoPerspective:
  10642. if (pNoPerspective) {
  10643. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10644. << pAttr->getName() << pAttr->getRange();
  10645. }
  10646. pNoPerspective = pAttr;
  10647. break;
  10648. case AttributeList::AT_HLSLSample:
  10649. if (pSample) {
  10650. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10651. << pAttr->getName() << pAttr->getRange();
  10652. }
  10653. pSample = pAttr;
  10654. break;
  10655. case AttributeList::AT_HLSLCentroid:
  10656. if (pCentroid) {
  10657. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10658. << pAttr->getName() << pAttr->getRange();
  10659. }
  10660. pCentroid = pAttr;
  10661. break;
  10662. default:
  10663. // Only relevant to the four attribs included in this block.
  10664. break;
  10665. }
  10666. break;
  10667. case AttributeList::AT_HLSLPoint:
  10668. case AttributeList::AT_HLSLLine:
  10669. case AttributeList::AT_HLSLLineAdj:
  10670. case AttributeList::AT_HLSLTriangle:
  10671. case AttributeList::AT_HLSLTriangleAdj:
  10672. if (!(isParameter)) {
  10673. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10674. << pAttr->getName() << declarationType << pAttr->getRange();
  10675. result = false;
  10676. }
  10677. if (pTopology) {
  10678. if (pTopology->getKind() == pAttr->getKind()) {
  10679. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10680. << pAttr->getName() << pAttr->getRange();
  10681. } else {
  10682. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10683. << pAttr->getName() << pTopology->getName()
  10684. << declarationType << pAttr->getRange();
  10685. result = false;
  10686. }
  10687. }
  10688. pTopology = pAttr;
  10689. break;
  10690. case AttributeList::AT_HLSLExport:
  10691. if (!isFunction) {
  10692. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10693. << pAttr->getName() << declarationType << pAttr->getRange();
  10694. result = false;
  10695. }
  10696. if (isStatic) {
  10697. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10698. << "'static'" << pAttr->getName() << declarationType
  10699. << pAttr->getRange();
  10700. result = false;
  10701. }
  10702. break;
  10703. case AttributeList::AT_HLSLIndices:
  10704. case AttributeList::AT_HLSLVertices:
  10705. case AttributeList::AT_HLSLPrimitives:
  10706. case AttributeList::AT_HLSLPayload:
  10707. if (!(isParameter)) {
  10708. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  10709. << pAttr->getName() << declarationType << pAttr->getRange();
  10710. result = false;
  10711. }
  10712. if (pMeshModifier) {
  10713. if (pMeshModifier->getKind() == pAttr->getKind()) {
  10714. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  10715. << pAttr->getName() << pAttr->getRange();
  10716. } else {
  10717. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  10718. << pAttr->getName() << pMeshModifier->getName()
  10719. << declarationType << pAttr->getRange();
  10720. result = false;
  10721. }
  10722. }
  10723. pMeshModifier = pAttr;
  10724. break;
  10725. default:
  10726. break;
  10727. }
  10728. }
  10729. if (pNoInterpolation && pAnyLinear) {
  10730. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  10731. << pNoInterpolation->getName() << pAnyLinear->getName()
  10732. << declarationType << pNoInterpolation->getRange();
  10733. result = false;
  10734. }
  10735. if (pSample && pCentroid) {
  10736. Diag(pCentroid->getLoc(), diag::warn_hlsl_specifier_overridden)
  10737. << pCentroid->getName() << pSample->getName() << pCentroid->getRange();
  10738. }
  10739. if (pCenter && pCentroid) {
  10740. Diag(pCenter->getLoc(), diag::warn_hlsl_specifier_overridden)
  10741. << pCenter->getName() << pCentroid->getName() << pCenter->getRange();
  10742. }
  10743. if (pSample && pCenter) {
  10744. Diag(pCenter->getLoc(), diag::warn_hlsl_specifier_overridden)
  10745. << pCenter->getName() << pSample->getName() << pCenter->getRange();
  10746. }
  10747. clang::AttributeList *pNonUniformAttr = pAnyLinear ? pAnyLinear : (
  10748. pNoInterpolation ? pNoInterpolation : pTopology);
  10749. if (pUniform && pNonUniformAttr) {
  10750. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  10751. << pNonUniformAttr->getName()
  10752. << pUniform->getName() << declarationType << pUniform->getRange();
  10753. result = false;
  10754. }
  10755. if (pAnyLinear && pTopology) {
  10756. Diag(pAnyLinear->getLoc(), diag::err_hlsl_varmodifiersna)
  10757. << pTopology->getName()
  10758. << pAnyLinear->getName() << declarationType << pAnyLinear->getRange();
  10759. result = false;
  10760. }
  10761. if (pNoInterpolation && pTopology) {
  10762. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  10763. << pTopology->getName()
  10764. << pNoInterpolation->getName() << declarationType << pNoInterpolation->getRange();
  10765. result = false;
  10766. }
  10767. if (pUniform && pUsage) {
  10768. if (pUsage->getKind() != AttributeList::Kind::AT_HLSLIn) {
  10769. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  10770. << pUsage->getName() << pUniform->getName() << declarationType
  10771. << pUniform->getRange();
  10772. result = false;
  10773. }
  10774. }
  10775. if (pMeshModifier) {
  10776. if (pMeshModifier->getKind() == AttributeList::Kind::AT_HLSLPayload) {
  10777. if (!usageIn) {
  10778. Diag(D.getLocStart(), diag::err_hlsl_missing_in_attr)
  10779. << pMeshModifier->getName();
  10780. result = false;
  10781. }
  10782. } else {
  10783. if (!usageOut) {
  10784. Diag(D.getLocStart(), diag::err_hlsl_missing_out_attr)
  10785. << pMeshModifier->getName();
  10786. result = false;
  10787. }
  10788. }
  10789. }
  10790. // Validate that stream-ouput objects are marked as inout
  10791. if (isParameter && !(usageIn && usageOut) &&
  10792. (basicKind == ArBasicKind::AR_OBJECT_LINESTREAM ||
  10793. basicKind == ArBasicKind::AR_OBJECT_POINTSTREAM ||
  10794. basicKind == ArBasicKind::AR_OBJECT_TRIANGLESTREAM)) {
  10795. Diag(D.getLocStart(), diag::err_hlsl_missing_inout_attr);
  10796. result = false;
  10797. }
  10798. // SPIRV change starts
  10799. #ifdef ENABLE_SPIRV_CODEGEN
  10800. // Validate that Vulkan specific feature is only used when targeting SPIR-V
  10801. if (!getLangOpts().SPIRV) {
  10802. if (basicKind == ArBasicKind::AR_OBJECT_VK_SUBPASS_INPUT ||
  10803. basicKind == ArBasicKind::AR_OBJECT_VK_SUBPASS_INPUT_MS) {
  10804. Diag(D.getLocStart(), diag::err_hlsl_vulkan_specific_feature)
  10805. << g_ArBasicTypeNames[basicKind];
  10806. result = false;
  10807. }
  10808. }
  10809. #endif // ENABLE_SPIRV_CODEGEN
  10810. // SPIRV change ends
  10811. // Disallow bitfields
  10812. if (BitWidth) {
  10813. Diag(BitWidth->getExprLoc(), diag::err_hlsl_bitfields);
  10814. result = false;
  10815. }
  10816. // Validate unusual annotations.
  10817. hlsl::DiagnoseUnusualAnnotationsForHLSL(*this, D.UnusualAnnotations);
  10818. auto && unusualIter = D.UnusualAnnotations.begin();
  10819. auto && unusualEnd = D.UnusualAnnotations.end();
  10820. for (; unusualIter != unusualEnd; ++unusualIter) {
  10821. switch ((*unusualIter)->getKind()) {
  10822. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  10823. hlsl::ConstantPacking *constantPacking =
  10824. cast<hlsl::ConstantPacking>(*unusualIter);
  10825. if (!isGlobal || HLSLBuffers.size() == 0) {
  10826. Diag(constantPacking->Loc, diag::err_hlsl_packoffset_requires_cbuffer);
  10827. continue;
  10828. }
  10829. if (constantPacking->ComponentOffset > 0) {
  10830. // Validate that this will fit.
  10831. if (!qt.isNull()) {
  10832. hlsl::DiagnosePackingOffset(this, constantPacking->Loc, qt,
  10833. constantPacking->ComponentOffset);
  10834. }
  10835. }
  10836. break;
  10837. }
  10838. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  10839. hlsl::RegisterAssignment *registerAssignment =
  10840. cast<hlsl::RegisterAssignment>(*unusualIter);
  10841. if (registerAssignment->IsValid) {
  10842. if (!qt.isNull()) {
  10843. hlsl::DiagnoseRegisterType(this, registerAssignment->Loc, qt,
  10844. registerAssignment->RegisterType);
  10845. }
  10846. }
  10847. break;
  10848. }
  10849. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  10850. hlsl::SemanticDecl *semanticDecl = cast<hlsl::SemanticDecl>(*unusualIter);
  10851. if (isTypedef || isLocalVar) {
  10852. Diag(semanticDecl->Loc, diag::err_hlsl_varmodifierna)
  10853. << "semantic" << declarationType;
  10854. }
  10855. break;
  10856. }
  10857. }
  10858. }
  10859. if (!result) {
  10860. D.setInvalidType();
  10861. }
  10862. return result;
  10863. }
  10864. // Diagnose HLSL types on lookup
  10865. bool Sema::DiagnoseHLSLLookup(const LookupResult &R) {
  10866. const DeclarationNameInfo declName = R.getLookupNameInfo();
  10867. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  10868. if (idInfo) {
  10869. StringRef nameIdentifier = idInfo->getName();
  10870. HLSLScalarType parsedType;
  10871. int rowCount, colCount;
  10872. if (TryParseAny(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &rowCount, &colCount, getLangOpts())) {
  10873. HLSLExternalSource *hlslExternalSource = HLSLExternalSource::FromSema(this);
  10874. hlslExternalSource->WarnMinPrecision(parsedType, R.getNameLoc());
  10875. return hlslExternalSource->DiagnoseHLSLScalarType(parsedType, R.getNameLoc());
  10876. }
  10877. }
  10878. return true;
  10879. }
  10880. static QualType getUnderlyingType(QualType Type)
  10881. {
  10882. while (const TypedefType *TD = dyn_cast<TypedefType>(Type))
  10883. {
  10884. if (const TypedefNameDecl* pDecl = TD->getDecl())
  10885. Type = pDecl->getUnderlyingType();
  10886. else
  10887. break;
  10888. }
  10889. return Type;
  10890. }
  10891. /// <summary>Return HLSL AttributedType objects if they exist on type.</summary>
  10892. /// <param name="self">Sema with context.</param>
  10893. /// <param name="type">QualType to inspect.</param>
  10894. /// <param name="ppMatrixOrientation">Set pointer to column_major/row_major AttributedType if supplied.</param>
  10895. /// <param name="ppNorm">Set pointer to snorm/unorm AttributedType if supplied.</param>
  10896. void hlsl::GetHLSLAttributedTypes(
  10897. _In_ clang::Sema *self, clang::QualType type,
  10898. _Inout_opt_ const clang::AttributedType **ppMatrixOrientation,
  10899. _Inout_opt_ const clang::AttributedType **ppNorm,
  10900. _Inout_opt_ const clang::AttributedType **ppGLC) {
  10901. AssignOpt<const clang::AttributedType *>(nullptr, ppMatrixOrientation);
  10902. AssignOpt<const clang::AttributedType *>(nullptr, ppNorm);
  10903. AssignOpt<const clang::AttributedType *>(nullptr, ppGLC);
  10904. // Note: we clear output pointers once set so we can stop searching
  10905. QualType Desugared = getUnderlyingType(type);
  10906. const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
  10907. while (AT && (ppMatrixOrientation || ppNorm || ppGLC)) {
  10908. AttributedType::Kind Kind = AT->getAttrKind();
  10909. if (Kind == AttributedType::attr_hlsl_row_major ||
  10910. Kind == AttributedType::attr_hlsl_column_major)
  10911. {
  10912. if (ppMatrixOrientation)
  10913. {
  10914. *ppMatrixOrientation = AT;
  10915. ppMatrixOrientation = nullptr;
  10916. }
  10917. }
  10918. else if (Kind == AttributedType::attr_hlsl_unorm ||
  10919. Kind == AttributedType::attr_hlsl_snorm)
  10920. {
  10921. if (ppNorm)
  10922. {
  10923. *ppNorm = AT;
  10924. ppNorm = nullptr;
  10925. }
  10926. }
  10927. else if (Kind == AttributedType::attr_hlsl_globallycoherent) {
  10928. if (ppGLC) {
  10929. *ppGLC = AT;
  10930. ppGLC = nullptr;
  10931. }
  10932. }
  10933. Desugared = getUnderlyingType(AT->getEquivalentType());
  10934. AT = dyn_cast<AttributedType>(Desugared);
  10935. }
  10936. // Unwrap component type on vector or matrix and check snorm/unorm
  10937. Desugared = getUnderlyingType(hlsl::GetOriginalElementType(self, Desugared));
  10938. AT = dyn_cast<AttributedType>(Desugared);
  10939. while (AT && ppNorm) {
  10940. AttributedType::Kind Kind = AT->getAttrKind();
  10941. if (Kind == AttributedType::attr_hlsl_unorm ||
  10942. Kind == AttributedType::attr_hlsl_snorm)
  10943. {
  10944. *ppNorm = AT;
  10945. ppNorm = nullptr;
  10946. }
  10947. Desugared = getUnderlyingType(AT->getEquivalentType());
  10948. AT = dyn_cast<AttributedType>(Desugared);
  10949. }
  10950. }
  10951. /// <summary>Returns true if QualType is an HLSL Matrix type.</summary>
  10952. /// <param name="self">Sema with context.</param>
  10953. /// <param name="type">QualType to check.</param>
  10954. bool hlsl::IsMatrixType(
  10955. _In_ clang::Sema* self,
  10956. _In_ clang::QualType type)
  10957. {
  10958. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_MATRIX;
  10959. }
  10960. /// <summary>Returns true if QualType is an HLSL Vector type.</summary>
  10961. /// <param name="self">Sema with context.</param>
  10962. /// <param name="type">QualType to check.</param>
  10963. bool hlsl::IsVectorType(
  10964. _In_ clang::Sema* self,
  10965. _In_ clang::QualType type)
  10966. {
  10967. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_VECTOR;
  10968. }
  10969. /// <summary>Get element type for an HLSL Matrix or Vector, preserving AttributedType.</summary>
  10970. /// <param name="self">Sema with context.</param>
  10971. /// <param name="type">Matrix or Vector type.</param>
  10972. clang::QualType hlsl::GetOriginalMatrixOrVectorElementType(
  10973. _In_ clang::QualType type)
  10974. {
  10975. // TODO: Determine if this is really the best way to get the matrix/vector specialization
  10976. // without losing the AttributedType on the template parameter
  10977. if (const Type* pType = type.getTypePtrOrNull()) {
  10978. // A non-dependent template specialization type is always "sugar",
  10979. // typically for a RecordType. For example, a class template
  10980. // specialization type of @c vector<int> will refer to a tag type for
  10981. // the instantiation @c std::vector<int, std::allocator<int>>.
  10982. if (const TemplateSpecializationType* pTemplate = pType->getAs<TemplateSpecializationType>()) {
  10983. // If we have enough arguments, pull them from the template directly, rather than doing
  10984. // the extra lookups.
  10985. if (pTemplate->getNumArgs() > 0)
  10986. return pTemplate->getArg(0).getAsType();
  10987. QualType templateRecord = pTemplate->desugar();
  10988. const Type *pTemplateRecordType = templateRecord.getTypePtr();
  10989. if (pTemplateRecordType) {
  10990. const TagType *pTemplateTagType = pTemplateRecordType->getAs<TagType>();
  10991. if (pTemplateTagType) {
  10992. const ClassTemplateSpecializationDecl *specializationDecl =
  10993. dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  10994. pTemplateTagType->getDecl());
  10995. if (specializationDecl) {
  10996. return specializationDecl->getTemplateArgs()[0].getAsType();
  10997. }
  10998. }
  10999. }
  11000. }
  11001. }
  11002. return QualType();
  11003. }
  11004. /// <summary>Get element type, preserving AttributedType, if vector or matrix, otherwise return the type unmodified.</summary>
  11005. /// <param name="self">Sema with context.</param>
  11006. /// <param name="type">Input type.</param>
  11007. clang::QualType hlsl::GetOriginalElementType(
  11008. _In_ clang::Sema* self,
  11009. _In_ clang::QualType type)
  11010. {
  11011. ArTypeObjectKind Kind = HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type);
  11012. if (Kind == AR_TOBJ_MATRIX || Kind == AR_TOBJ_VECTOR) {
  11013. return GetOriginalMatrixOrVectorElementType(type);
  11014. }
  11015. return type;
  11016. }
  11017. void hlsl::CustomPrintHLSLAttr(const clang::Attr *A, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy, unsigned int Indentation) {
  11018. switch (A->getKind()) {
  11019. // Parameter modifiers
  11020. case clang::attr::HLSLIn:
  11021. Out << "in ";
  11022. break;
  11023. case clang::attr::HLSLInOut:
  11024. Out << "inout ";
  11025. break;
  11026. case clang::attr::HLSLOut:
  11027. Out << "out ";
  11028. break;
  11029. // Interpolation modifiers
  11030. case clang::attr::HLSLLinear:
  11031. Out << "linear ";
  11032. break;
  11033. case clang::attr::HLSLCenter:
  11034. Out << "center ";
  11035. break;
  11036. case clang::attr::HLSLCentroid:
  11037. Out << "centroid ";
  11038. break;
  11039. case clang::attr::HLSLNoInterpolation:
  11040. Out << "nointerpolation ";
  11041. break;
  11042. case clang::attr::HLSLNoPerspective:
  11043. Out << "noperspective ";
  11044. break;
  11045. case clang::attr::HLSLSample:
  11046. Out << "sample ";
  11047. break;
  11048. // Function attributes
  11049. case clang::attr::HLSLClipPlanes:
  11050. {
  11051. Attr * noconst = const_cast<Attr*>(A);
  11052. HLSLClipPlanesAttr *ACast = static_cast<HLSLClipPlanesAttr*>(noconst);
  11053. if (!ACast->getClipPlane1())
  11054. break;
  11055. Indent(Indentation, Out);
  11056. Out << "[clipplanes(";
  11057. ACast->getClipPlane1()->printPretty(Out, 0, Policy);
  11058. PrintClipPlaneIfPresent(ACast->getClipPlane2(), Out, Policy);
  11059. PrintClipPlaneIfPresent(ACast->getClipPlane3(), Out, Policy);
  11060. PrintClipPlaneIfPresent(ACast->getClipPlane4(), Out, Policy);
  11061. PrintClipPlaneIfPresent(ACast->getClipPlane5(), Out, Policy);
  11062. PrintClipPlaneIfPresent(ACast->getClipPlane6(), Out, Policy);
  11063. Out << ")]\n";
  11064. break;
  11065. }
  11066. case clang::attr::HLSLDomain:
  11067. {
  11068. Attr * noconst = const_cast<Attr*>(A);
  11069. HLSLDomainAttr *ACast = static_cast<HLSLDomainAttr*>(noconst);
  11070. Indent(Indentation, Out);
  11071. Out << "[domain(\"" << ACast->getDomainType() << "\")]\n";
  11072. break;
  11073. }
  11074. case clang::attr::HLSLEarlyDepthStencil:
  11075. Indent(Indentation, Out);
  11076. Out << "[earlydepthstencil]\n";
  11077. break;
  11078. case clang::attr::HLSLInstance: //TODO - test
  11079. {
  11080. Attr * noconst = const_cast<Attr*>(A);
  11081. HLSLInstanceAttr *ACast = static_cast<HLSLInstanceAttr*>(noconst);
  11082. Indent(Indentation, Out);
  11083. Out << "[instance(" << ACast->getCount() << ")]\n";
  11084. break;
  11085. }
  11086. case clang::attr::HLSLMaxTessFactor: //TODO - test
  11087. {
  11088. Attr * noconst = const_cast<Attr*>(A);
  11089. HLSLMaxTessFactorAttr *ACast = static_cast<HLSLMaxTessFactorAttr*>(noconst);
  11090. Indent(Indentation, Out);
  11091. Out << "[maxtessfactor(" << ACast->getFactor() << ")]\n";
  11092. break;
  11093. }
  11094. case clang::attr::HLSLNumThreads: //TODO - test
  11095. {
  11096. Attr * noconst = const_cast<Attr*>(A);
  11097. HLSLNumThreadsAttr *ACast = static_cast<HLSLNumThreadsAttr*>(noconst);
  11098. Indent(Indentation, Out);
  11099. Out << "[numthreads(" << ACast->getX() << ", " << ACast->getY() << ", " << ACast->getZ() << ")]\n";
  11100. break;
  11101. }
  11102. case clang::attr::HLSLRootSignature:
  11103. {
  11104. Attr * noconst = const_cast<Attr*>(A);
  11105. HLSLRootSignatureAttr *ACast = static_cast<HLSLRootSignatureAttr*>(noconst);
  11106. Indent(Indentation, Out);
  11107. Out << "[RootSignature(\"" << ACast->getSignatureName() << "\")]\n";
  11108. break;
  11109. }
  11110. case clang::attr::HLSLOutputControlPoints:
  11111. {
  11112. Attr * noconst = const_cast<Attr*>(A);
  11113. HLSLOutputControlPointsAttr *ACast = static_cast<HLSLOutputControlPointsAttr*>(noconst);
  11114. Indent(Indentation, Out);
  11115. Out << "[outputcontrolpoints(" << ACast->getCount() << ")]\n";
  11116. break;
  11117. }
  11118. case clang::attr::HLSLOutputTopology:
  11119. {
  11120. Attr * noconst = const_cast<Attr*>(A);
  11121. HLSLOutputTopologyAttr *ACast = static_cast<HLSLOutputTopologyAttr*>(noconst);
  11122. Indent(Indentation, Out);
  11123. Out << "[outputtopology(\"" << ACast->getTopology() << "\")]\n";
  11124. break;
  11125. }
  11126. case clang::attr::HLSLPartitioning:
  11127. {
  11128. Attr * noconst = const_cast<Attr*>(A);
  11129. HLSLPartitioningAttr *ACast = static_cast<HLSLPartitioningAttr*>(noconst);
  11130. Indent(Indentation, Out);
  11131. Out << "[partitioning(\"" << ACast->getScheme() << "\")]\n";
  11132. break;
  11133. }
  11134. case clang::attr::HLSLPatchConstantFunc:
  11135. {
  11136. Attr * noconst = const_cast<Attr*>(A);
  11137. HLSLPatchConstantFuncAttr *ACast = static_cast<HLSLPatchConstantFuncAttr*>(noconst);
  11138. Indent(Indentation, Out);
  11139. Out << "[patchconstantfunc(\"" << ACast->getFunctionName() << "\")]\n";
  11140. break;
  11141. }
  11142. case clang::attr::HLSLShader:
  11143. {
  11144. Attr * noconst = const_cast<Attr*>(A);
  11145. HLSLShaderAttr *ACast = static_cast<HLSLShaderAttr*>(noconst);
  11146. Indent(Indentation, Out);
  11147. Out << "[shader(\"" << ACast->getStage() << "\")]\n";
  11148. break;
  11149. }
  11150. case clang::attr::HLSLExperimental:
  11151. {
  11152. Attr * noconst = const_cast<Attr*>(A);
  11153. HLSLExperimentalAttr *ACast = static_cast<HLSLExperimentalAttr*>(noconst);
  11154. Indent(Indentation, Out);
  11155. Out << "[experimental(\"" << ACast->getName() << "\", \"" << ACast->getValue() << "\")]\n";
  11156. break;
  11157. }
  11158. case clang::attr::HLSLMaxVertexCount:
  11159. {
  11160. Attr * noconst = const_cast<Attr*>(A);
  11161. HLSLMaxVertexCountAttr *ACast = static_cast<HLSLMaxVertexCountAttr*>(noconst);
  11162. Indent(Indentation, Out);
  11163. Out << "[maxvertexcount(" << ACast->getCount() << ")]\n";
  11164. break;
  11165. }
  11166. case clang::attr::NoInline:
  11167. Indent(Indentation, Out);
  11168. Out << "[noinline]\n";
  11169. break;
  11170. case clang::attr::HLSLExport:
  11171. Indent(Indentation, Out);
  11172. Out << "export\n";
  11173. break;
  11174. // Statement attributes
  11175. case clang::attr::HLSLAllowUAVCondition:
  11176. Indent(Indentation, Out);
  11177. Out << "[allow_uav_condition]\n";
  11178. break;
  11179. case clang::attr::HLSLBranch:
  11180. Indent(Indentation, Out);
  11181. Out << "[branch]\n";
  11182. break;
  11183. case clang::attr::HLSLCall:
  11184. Indent(Indentation, Out);
  11185. Out << "[call]\n";
  11186. break;
  11187. case clang::attr::HLSLFastOpt:
  11188. Indent(Indentation, Out);
  11189. Out << "[fastopt]\n";
  11190. break;
  11191. case clang::attr::HLSLFlatten:
  11192. Indent(Indentation, Out);
  11193. Out << "[flatten]\n";
  11194. break;
  11195. case clang::attr::HLSLForceCase:
  11196. Indent(Indentation, Out);
  11197. Out << "[forcecase]\n";
  11198. break;
  11199. case clang::attr::HLSLLoop:
  11200. Indent(Indentation, Out);
  11201. Out << "[loop]\n";
  11202. break;
  11203. case clang::attr::HLSLUnroll:
  11204. {
  11205. Attr * noconst = const_cast<Attr*>(A);
  11206. HLSLUnrollAttr *ACast = static_cast<HLSLUnrollAttr*>(noconst);
  11207. Indent(Indentation, Out);
  11208. if (ACast->getCount() == 0)
  11209. Out << "[unroll]\n";
  11210. else
  11211. Out << "[unroll(" << ACast->getCount() << ")]\n";
  11212. break;
  11213. }
  11214. // Variable modifiers
  11215. case clang::attr::HLSLGroupShared:
  11216. Out << "groupshared ";
  11217. break;
  11218. case clang::attr::HLSLPrecise:
  11219. Out << "precise ";
  11220. break;
  11221. case clang::attr::HLSLSemantic: // TODO: Consider removing HLSLSemantic attribute
  11222. break;
  11223. case clang::attr::HLSLShared:
  11224. Out << "shared ";
  11225. break;
  11226. case clang::attr::HLSLUniform:
  11227. Out << "uniform ";
  11228. break;
  11229. // These four cases are printed in TypePrinter::printAttributedBefore
  11230. case clang::attr::HLSLColumnMajor:
  11231. case clang::attr::HLSLRowMajor:
  11232. case clang::attr::HLSLSnorm:
  11233. case clang::attr::HLSLUnorm:
  11234. break;
  11235. case clang::attr::HLSLPoint:
  11236. Out << "point ";
  11237. break;
  11238. case clang::attr::HLSLLine:
  11239. Out << "line ";
  11240. break;
  11241. case clang::attr::HLSLLineAdj:
  11242. Out << "lineadj ";
  11243. break;
  11244. case clang::attr::HLSLTriangle:
  11245. Out << "triangle ";
  11246. break;
  11247. case clang::attr::HLSLTriangleAdj:
  11248. Out << "triangleadj ";
  11249. break;
  11250. case clang::attr::HLSLGloballyCoherent:
  11251. Out << "globallycoherent ";
  11252. break;
  11253. case clang::attr::HLSLIndices:
  11254. Out << "indices ";
  11255. break;
  11256. case clang::attr::HLSLVertices:
  11257. Out << "vertices ";
  11258. break;
  11259. case clang::attr::HLSLPrimitives:
  11260. Out << "primitives ";
  11261. break;
  11262. case clang::attr::HLSLPayload:
  11263. Out << "payload ";
  11264. break;
  11265. default:
  11266. A->printPretty(Out, Policy);
  11267. break;
  11268. }
  11269. }
  11270. bool hlsl::IsHLSLAttr(clang::attr::Kind AttrKind) {
  11271. switch (AttrKind){
  11272. case clang::attr::HLSLAllowUAVCondition:
  11273. case clang::attr::HLSLBranch:
  11274. case clang::attr::HLSLCall:
  11275. case clang::attr::HLSLCentroid:
  11276. case clang::attr::HLSLClipPlanes:
  11277. case clang::attr::HLSLColumnMajor:
  11278. case clang::attr::HLSLDomain:
  11279. case clang::attr::HLSLEarlyDepthStencil:
  11280. case clang::attr::HLSLFastOpt:
  11281. case clang::attr::HLSLFlatten:
  11282. case clang::attr::HLSLForceCase:
  11283. case clang::attr::HLSLGroupShared:
  11284. case clang::attr::HLSLIn:
  11285. case clang::attr::HLSLInOut:
  11286. case clang::attr::HLSLInstance:
  11287. case clang::attr::HLSLLinear:
  11288. case clang::attr::HLSLCenter:
  11289. case clang::attr::HLSLLoop:
  11290. case clang::attr::HLSLMaxTessFactor:
  11291. case clang::attr::HLSLNoInterpolation:
  11292. case clang::attr::HLSLNoPerspective:
  11293. case clang::attr::HLSLNumThreads:
  11294. case clang::attr::HLSLRootSignature:
  11295. case clang::attr::HLSLOut:
  11296. case clang::attr::HLSLOutputControlPoints:
  11297. case clang::attr::HLSLOutputTopology:
  11298. case clang::attr::HLSLPartitioning:
  11299. case clang::attr::HLSLPatchConstantFunc:
  11300. case clang::attr::HLSLMaxVertexCount:
  11301. case clang::attr::HLSLPrecise:
  11302. case clang::attr::HLSLRowMajor:
  11303. case clang::attr::HLSLSample:
  11304. case clang::attr::HLSLSemantic:
  11305. case clang::attr::HLSLShared:
  11306. case clang::attr::HLSLSnorm:
  11307. case clang::attr::HLSLUniform:
  11308. case clang::attr::HLSLUnorm:
  11309. case clang::attr::HLSLUnroll:
  11310. case clang::attr::HLSLPoint:
  11311. case clang::attr::HLSLLine:
  11312. case clang::attr::HLSLLineAdj:
  11313. case clang::attr::HLSLTriangle:
  11314. case clang::attr::HLSLTriangleAdj:
  11315. case clang::attr::HLSLGloballyCoherent:
  11316. case clang::attr::HLSLIndices:
  11317. case clang::attr::HLSLVertices:
  11318. case clang::attr::HLSLPrimitives:
  11319. case clang::attr::HLSLPayload:
  11320. case clang::attr::NoInline:
  11321. case clang::attr::HLSLExport:
  11322. case clang::attr::HLSLWaveSensitive:
  11323. case clang::attr::VKBinding:
  11324. case clang::attr::VKBuiltIn:
  11325. case clang::attr::VKConstantId:
  11326. case clang::attr::VKCounterBinding:
  11327. case clang::attr::VKIndex:
  11328. case clang::attr::VKInputAttachmentIndex:
  11329. case clang::attr::VKLocation:
  11330. case clang::attr::VKOffset:
  11331. case clang::attr::VKPushConstant:
  11332. case clang::attr::VKShaderRecordNV:
  11333. return true;
  11334. default:
  11335. // Only HLSL/VK Attributes return true. Only used for printPretty(), which doesn't support them.
  11336. break;
  11337. }
  11338. return false;
  11339. }
  11340. void hlsl::PrintClipPlaneIfPresent(clang::Expr *ClipPlane, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy) {
  11341. if (ClipPlane) {
  11342. Out << ", ";
  11343. ClipPlane->printPretty(Out, 0, Policy);
  11344. }
  11345. }
  11346. bool hlsl::IsObjectType(
  11347. _In_ clang::Sema* self,
  11348. _In_ clang::QualType type,
  11349. _Inout_opt_ bool *isDeprecatedEffectObject)
  11350. {
  11351. HLSLExternalSource *pExternalSource = HLSLExternalSource::FromSema(self);
  11352. if (pExternalSource && pExternalSource->GetTypeObjectKind(type) == AR_TOBJ_OBJECT) {
  11353. if (isDeprecatedEffectObject)
  11354. *isDeprecatedEffectObject = pExternalSource->GetTypeElementKind(type) == AR_OBJECT_LEGACY_EFFECT;
  11355. return true;
  11356. }
  11357. if (isDeprecatedEffectObject)
  11358. *isDeprecatedEffectObject = false;
  11359. return false;
  11360. }
  11361. bool hlsl::CanConvert(
  11362. _In_ clang::Sema* self,
  11363. clang::SourceLocation loc,
  11364. _In_ clang::Expr* sourceExpr,
  11365. clang::QualType target,
  11366. bool explicitConversion,
  11367. _Inout_opt_ clang::StandardConversionSequence* standard)
  11368. {
  11369. return HLSLExternalSource::FromSema(self)->CanConvert(loc, sourceExpr, target, explicitConversion, nullptr, standard);
  11370. }
  11371. void hlsl::Indent(unsigned int Indentation, llvm::raw_ostream &Out)
  11372. {
  11373. for (unsigned i = 0; i != Indentation; ++i)
  11374. Out << " ";
  11375. }
  11376. void hlsl::RegisterIntrinsicTable(_In_ clang::ExternalSemaSource* self, _In_ IDxcIntrinsicTable* table)
  11377. {
  11378. DXASSERT_NOMSG(self != nullptr);
  11379. DXASSERT_NOMSG(table != nullptr);
  11380. HLSLExternalSource* source = (HLSLExternalSource*)self;
  11381. source->RegisterIntrinsicTable(table);
  11382. }
  11383. clang::QualType hlsl::CheckVectorConditional(
  11384. _In_ clang::Sema* self,
  11385. _In_ clang::ExprResult &Cond,
  11386. _In_ clang::ExprResult &LHS,
  11387. _In_ clang::ExprResult &RHS,
  11388. _In_ clang::SourceLocation QuestionLoc)
  11389. {
  11390. return HLSLExternalSource::FromSema(self)->CheckVectorConditional(Cond, LHS, RHS, QuestionLoc);
  11391. }
  11392. bool IsTypeNumeric(_In_ clang::Sema* self, _In_ clang::QualType &type) {
  11393. UINT count;
  11394. return HLSLExternalSource::FromSema(self)->IsTypeNumeric(type, &count);
  11395. }
  11396. void Sema::CheckHLSLArrayAccess(const Expr *expr) {
  11397. DXASSERT_NOMSG(isa<CXXOperatorCallExpr>(expr));
  11398. const CXXOperatorCallExpr *OperatorCallExpr = cast<CXXOperatorCallExpr>(expr);
  11399. DXASSERT_NOMSG(OperatorCallExpr->getOperator() == OverloadedOperatorKind::OO_Subscript);
  11400. const Expr *RHS = OperatorCallExpr->getArg(1); // first subscript expression
  11401. llvm::APSInt index;
  11402. if (RHS->EvaluateAsInt(index, Context)) {
  11403. int64_t intIndex = index.getLimitedValue();
  11404. const QualType LHSQualType = OperatorCallExpr->getArg(0)->getType();
  11405. if (IsVectorType(this, LHSQualType)) {
  11406. uint32_t vectorSize = GetHLSLVecSize(LHSQualType);
  11407. // If expression is a double two subscript operator for matrix (e.g x[0][1])
  11408. // we also have to check the first subscript oprator by recursively calling
  11409. // this funciton for the first CXXOperatorCallExpr
  11410. if (isa<CXXOperatorCallExpr>(OperatorCallExpr->getArg(0))) {
  11411. CheckHLSLArrayAccess(cast<CXXOperatorCallExpr>(OperatorCallExpr->getArg(0)));
  11412. }
  11413. if (intIndex < 0 || (uint32_t)intIndex >= vectorSize) {
  11414. Diag(RHS->getExprLoc(),
  11415. diag::err_hlsl_vector_element_index_out_of_bounds)
  11416. << (int)intIndex;
  11417. }
  11418. }
  11419. else if (IsMatrixType(this, LHSQualType)) {
  11420. uint32_t rowCount, colCount;
  11421. GetHLSLMatRowColCount(LHSQualType, rowCount, colCount);
  11422. if (intIndex < 0 || (uint32_t)intIndex >= rowCount) {
  11423. Diag(RHS->getExprLoc(), diag::err_hlsl_matrix_row_index_out_of_bounds)
  11424. << (int)intIndex;
  11425. }
  11426. }
  11427. }
  11428. }
  11429. clang::QualType ApplyTypeSpecSignToParsedType(
  11430. _In_ clang::Sema* self,
  11431. _In_ clang::QualType &type,
  11432. _In_ clang::TypeSpecifierSign TSS,
  11433. _In_ clang::SourceLocation Loc
  11434. )
  11435. {
  11436. return HLSLExternalSource::FromSema(self)->ApplyTypeSpecSignToParsedType(type, TSS, Loc);
  11437. }