SemaHLSL.cpp 404 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810
  1. //===--- SemaHLSL.cpp - HLSL support for AST nodes and operations ---===//
  2. ///////////////////////////////////////////////////////////////////////////////
  3. // //
  4. // SemaHLSL.cpp //
  5. // Copyright (C) Microsoft Corporation. All rights reserved. //
  6. // This file is distributed under the University of Illinois Open Source //
  7. // License. See LICENSE.TXT for details. //
  8. // //
  9. // This file implements the semantic support for HLSL. //
  10. // //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. #include "llvm/ADT/SmallPtrSet.h"
  13. #include "llvm/ADT/DenseMap.h"
  14. #include "clang/AST/ASTContext.h"
  15. #include "clang/AST/Attr.h"
  16. #include "clang/AST/DeclCXX.h"
  17. #include "clang/AST/DeclTemplate.h"
  18. #include "clang/AST/Expr.h"
  19. #include "clang/AST/ExprCXX.h"
  20. #include "clang/AST/ExternalASTSource.h"
  21. #include "clang/AST/RecursiveASTVisitor.h"
  22. #include "clang/AST/TypeLoc.h"
  23. #include "clang/AST/HlslTypes.h"
  24. #include "clang/Sema/Overload.h"
  25. #include "clang/Sema/SemaDiagnostic.h"
  26. #include "clang/Sema/Initialization.h"
  27. #include "clang/Sema/ExternalSemaSource.h"
  28. #include "clang/Sema/Lookup.h"
  29. #include "clang/Sema/Template.h"
  30. #include "clang/Sema/TemplateDeduction.h"
  31. #include "clang/Sema/SemaHLSL.h"
  32. #include "dxc/Support/Global.h"
  33. #include "dxc/Support/WinIncludes.h"
  34. #include "dxc/dxcapi.internal.h"
  35. #include "dxc/HlslIntrinsicOp.h"
  36. #include "gen_intrin_main_tables_15.h"
  37. #include "dxc/HLSL/HLOperations.h"
  38. #include "dxc/HLSL/DxilShaderModel.h"
  39. #include <array>
  40. enum ArBasicKind {
  41. AR_BASIC_BOOL,
  42. AR_BASIC_LITERAL_FLOAT,
  43. AR_BASIC_FLOAT16,
  44. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  45. AR_BASIC_FLOAT32,
  46. AR_BASIC_FLOAT64,
  47. AR_BASIC_LITERAL_INT,
  48. AR_BASIC_INT8,
  49. AR_BASIC_UINT8,
  50. AR_BASIC_INT16,
  51. AR_BASIC_UINT16,
  52. AR_BASIC_INT32,
  53. AR_BASIC_UINT32,
  54. AR_BASIC_INT64,
  55. AR_BASIC_UINT64,
  56. AR_BASIC_MIN10FLOAT,
  57. AR_BASIC_MIN16FLOAT,
  58. AR_BASIC_MIN12INT,
  59. AR_BASIC_MIN16INT,
  60. AR_BASIC_MIN16UINT,
  61. AR_BASIC_ENUM,
  62. AR_BASIC_COUNT,
  63. //
  64. // Pseudo-entries for intrinsic tables and such.
  65. //
  66. AR_BASIC_NONE,
  67. AR_BASIC_UNKNOWN,
  68. AR_BASIC_NOCAST,
  69. //
  70. // The following pseudo-entries represent higher-level
  71. // object types that are treated as units.
  72. //
  73. AR_BASIC_POINTER,
  74. AR_BASIC_ENUM_CLASS,
  75. AR_OBJECT_NULL,
  76. AR_OBJECT_STRING,
  77. // AR_OBJECT_TEXTURE,
  78. AR_OBJECT_TEXTURE1D,
  79. AR_OBJECT_TEXTURE1D_ARRAY,
  80. AR_OBJECT_TEXTURE2D,
  81. AR_OBJECT_TEXTURE2D_ARRAY,
  82. AR_OBJECT_TEXTURE3D,
  83. AR_OBJECT_TEXTURECUBE,
  84. AR_OBJECT_TEXTURECUBE_ARRAY,
  85. AR_OBJECT_TEXTURE2DMS,
  86. AR_OBJECT_TEXTURE2DMS_ARRAY,
  87. AR_OBJECT_SAMPLER,
  88. AR_OBJECT_SAMPLER1D,
  89. AR_OBJECT_SAMPLER2D,
  90. AR_OBJECT_SAMPLER3D,
  91. AR_OBJECT_SAMPLERCUBE,
  92. AR_OBJECT_SAMPLERCOMPARISON,
  93. AR_OBJECT_BUFFER,
  94. //
  95. // View objects are only used as variable/types within the Effects
  96. // framework, for example in calls to OMSetRenderTargets.
  97. //
  98. AR_OBJECT_RENDERTARGETVIEW,
  99. AR_OBJECT_DEPTHSTENCILVIEW,
  100. //
  101. // Shader objects are only used as variable/types within the Effects
  102. // framework, for example as a result of CompileShader().
  103. //
  104. AR_OBJECT_COMPUTESHADER,
  105. AR_OBJECT_DOMAINSHADER,
  106. AR_OBJECT_GEOMETRYSHADER,
  107. AR_OBJECT_HULLSHADER,
  108. AR_OBJECT_PIXELSHADER,
  109. AR_OBJECT_VERTEXSHADER,
  110. AR_OBJECT_PIXELFRAGMENT,
  111. AR_OBJECT_VERTEXFRAGMENT,
  112. AR_OBJECT_STATEBLOCK,
  113. AR_OBJECT_RASTERIZER,
  114. AR_OBJECT_DEPTHSTENCIL,
  115. AR_OBJECT_BLEND,
  116. AR_OBJECT_POINTSTREAM,
  117. AR_OBJECT_LINESTREAM,
  118. AR_OBJECT_TRIANGLESTREAM,
  119. AR_OBJECT_INPUTPATCH,
  120. AR_OBJECT_OUTPUTPATCH,
  121. AR_OBJECT_RWTEXTURE1D,
  122. AR_OBJECT_RWTEXTURE1D_ARRAY,
  123. AR_OBJECT_RWTEXTURE2D,
  124. AR_OBJECT_RWTEXTURE2D_ARRAY,
  125. AR_OBJECT_RWTEXTURE3D,
  126. AR_OBJECT_RWBUFFER,
  127. AR_OBJECT_BYTEADDRESS_BUFFER,
  128. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  129. AR_OBJECT_STRUCTURED_BUFFER,
  130. AR_OBJECT_RWSTRUCTURED_BUFFER,
  131. AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  132. AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  133. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  134. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  135. AR_OBJECT_CONSTANT_BUFFER,
  136. AR_OBJECT_TEXTURE_BUFFER,
  137. AR_OBJECT_ROVBUFFER,
  138. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  139. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  140. AR_OBJECT_ROVTEXTURE1D,
  141. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  142. AR_OBJECT_ROVTEXTURE2D,
  143. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  144. AR_OBJECT_ROVTEXTURE3D,
  145. // SPIRV change starts
  146. #ifdef ENABLE_SPIRV_CODEGEN
  147. AR_OBJECT_VK_SUBPASS_INPUT,
  148. AR_OBJECT_VK_SUBPASS_INPUT_MS,
  149. #endif // ENABLE_SPIRV_CODEGEN
  150. // SPIRV change ends
  151. AR_OBJECT_INNER, // Used for internal type object
  152. AR_OBJECT_LEGACY_EFFECT,
  153. AR_OBJECT_WAVE,
  154. AR_BASIC_MAXIMUM_COUNT
  155. };
  156. #define AR_BASIC_TEXTURE_MS_CASES \
  157. case AR_OBJECT_TEXTURE2DMS: \
  158. case AR_OBJECT_TEXTURE2DMS_ARRAY
  159. #define AR_BASIC_NON_TEXTURE_MS_CASES \
  160. case AR_OBJECT_TEXTURE1D: \
  161. case AR_OBJECT_TEXTURE1D_ARRAY: \
  162. case AR_OBJECT_TEXTURE2D: \
  163. case AR_OBJECT_TEXTURE2D_ARRAY: \
  164. case AR_OBJECT_TEXTURE3D: \
  165. case AR_OBJECT_TEXTURECUBE: \
  166. case AR_OBJECT_TEXTURECUBE_ARRAY
  167. #define AR_BASIC_TEXTURE_CASES \
  168. AR_BASIC_TEXTURE_MS_CASES: \
  169. AR_BASIC_NON_TEXTURE_MS_CASES
  170. #define AR_BASIC_NON_CMP_SAMPLER_CASES \
  171. case AR_OBJECT_SAMPLER: \
  172. case AR_OBJECT_SAMPLER1D: \
  173. case AR_OBJECT_SAMPLER2D: \
  174. case AR_OBJECT_SAMPLER3D: \
  175. case AR_OBJECT_SAMPLERCUBE
  176. #define AR_BASIC_ROBJECT_CASES \
  177. case AR_OBJECT_BLEND: \
  178. case AR_OBJECT_RASTERIZER: \
  179. case AR_OBJECT_DEPTHSTENCIL: \
  180. case AR_OBJECT_STATEBLOCK
  181. //
  182. // Properties of entries in the ArBasicKind enumeration.
  183. // These properties are intended to allow easy identification
  184. // of classes of basic kinds. More specific checks on the
  185. // actual kind values could then be done.
  186. //
  187. // The first four bits are used as a subtype indicator,
  188. // such as bit count for primitive kinds or specific
  189. // types for non-primitive-data kinds.
  190. #define BPROP_SUBTYPE_MASK 0x0000000f
  191. // Bit counts must be ordered from smaller to larger.
  192. #define BPROP_BITS0 0x00000000
  193. #define BPROP_BITS8 0x00000001
  194. #define BPROP_BITS10 0x00000002
  195. #define BPROP_BITS12 0x00000003
  196. #define BPROP_BITS16 0x00000004
  197. #define BPROP_BITS32 0x00000005
  198. #define BPROP_BITS64 0x00000006
  199. #define BPROP_BITS_NON_PRIM 0x00000007
  200. #define GET_BPROP_SUBTYPE(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  201. #define GET_BPROP_BITS(_Props) ((_Props) & BPROP_SUBTYPE_MASK)
  202. #define BPROP_BOOLEAN 0x00000010 // Whether the type is bool
  203. #define BPROP_INTEGER 0x00000020 // Whether the type is an integer
  204. #define BPROP_UNSIGNED 0x00000040 // Whether the type is an unsigned numeric (its absence implies signed)
  205. #define BPROP_NUMERIC 0x00000080 // Whether the type is numeric or boolean
  206. #define BPROP_LITERAL 0x00000100 // Whether the type is a literal float or integer
  207. #define BPROP_FLOATING 0x00000200 // Whether the type is a float
  208. #define BPROP_OBJECT 0x00000400 // Whether the type is an object (including null or stream)
  209. #define BPROP_OTHER 0x00000800 // Whether the type is a pseudo-entry in another table.
  210. #define BPROP_PARTIAL_PRECISION 0x00001000 // Whether the type has partial precision for calculations (i.e., is this 'half')
  211. #define BPROP_POINTER 0x00002000 // Whether the type is a basic pointer.
  212. #define BPROP_TEXTURE 0x00004000 // Whether the type is any kind of texture.
  213. #define BPROP_SAMPLER 0x00008000 // Whether the type is any kind of sampler object.
  214. #define BPROP_STREAM 0x00010000 // Whether the type is a point, line or triangle stream.
  215. #define BPROP_PATCH 0x00020000 // Whether the type is an input or output patch.
  216. #define BPROP_RBUFFER 0x00040000 // Whether the type acts as a read-only buffer.
  217. #define BPROP_RWBUFFER 0x00080000 // Whether the type acts as a read-write buffer.
  218. #define BPROP_PRIMITIVE 0x00100000 // Whether the type is a primitive scalar type.
  219. #define BPROP_MIN_PRECISION 0x00200000 // Whether the type is qualified with a minimum precision.
  220. #define BPROP_ROVBUFFER 0x00400000 // Whether the type is a ROV object.
  221. #define BPROP_ENUM 0x00800000 // Whether the type is a enum
  222. #define GET_BPROP_PRIM_KIND(_Props) \
  223. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING))
  224. #define GET_BPROP_PRIM_KIND_SU(_Props) \
  225. ((_Props) & (BPROP_BOOLEAN | BPROP_INTEGER | BPROP_FLOATING | BPROP_UNSIGNED))
  226. #define IS_BPROP_PRIMITIVE(_Props) \
  227. (((_Props) & BPROP_PRIMITIVE) != 0)
  228. #define IS_BPROP_BOOL(_Props) \
  229. (((_Props) & BPROP_BOOLEAN) != 0)
  230. #define IS_BPROP_FLOAT(_Props) \
  231. (((_Props) & BPROP_FLOATING) != 0)
  232. #define IS_BPROP_SINT(_Props) \
  233. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  234. BPROP_INTEGER)
  235. #define IS_BPROP_UINT(_Props) \
  236. (((_Props) & (BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BOOLEAN)) == \
  237. (BPROP_INTEGER | BPROP_UNSIGNED))
  238. #define IS_BPROP_AINT(_Props) \
  239. (((_Props) & (BPROP_INTEGER | BPROP_BOOLEAN)) == BPROP_INTEGER)
  240. #define IS_BPROP_STREAM(_Props) \
  241. (((_Props) & BPROP_STREAM) != 0)
  242. #define IS_BPROP_SAMPLER(_Props) \
  243. (((_Props) & BPROP_SAMPLER) != 0)
  244. #define IS_BPROP_TEXTURE(_Props) \
  245. (((_Props) & BPROP_TEXTURE) != 0)
  246. #define IS_BPROP_OBJECT(_Props) \
  247. (((_Props) & BPROP_OBJECT) != 0)
  248. #define IS_BPROP_MIN_PRECISION(_Props) \
  249. (((_Props) & BPROP_MIN_PRECISION) != 0)
  250. #define IS_BPROP_UNSIGNABLE(_Props) \
  251. (IS_BPROP_AINT(_Props) && GET_BPROP_BITS(_Props) != BPROP_BITS12)
  252. #define IS_BPROP_ENUM(_Props) \
  253. (((_Props) & BPROP_ENUM) != 0)
  254. const UINT g_uBasicKindProps[] =
  255. {
  256. BPROP_PRIMITIVE | BPROP_BOOLEAN | BPROP_INTEGER | BPROP_NUMERIC | BPROP_BITS0, // AR_BASIC_BOOL
  257. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_FLOAT
  258. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16, // AR_BASIC_FLOAT16
  259. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32 | BPROP_PARTIAL_PRECISION, // AR_BASIC_FLOAT32_PARTIAL_PRECISION
  260. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS32, // AR_BASIC_FLOAT32
  261. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS64, // AR_BASIC_FLOAT64
  262. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_LITERAL | BPROP_BITS0, // AR_BASIC_LITERAL_INT
  263. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS8, // AR_BASIC_INT8
  264. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS8, // AR_BASIC_UINT8
  265. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16, // AR_BASIC_INT16
  266. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16,// AR_BASIC_UINT16
  267. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS32, // AR_BASIC_INT32
  268. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS32,// AR_BASIC_UINT32
  269. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS64, // AR_BASIC_INT64
  270. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS64,// AR_BASIC_UINT64
  271. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS10 | BPROP_MIN_PRECISION, // AR_BASIC_MIN10FLOAT
  272. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_FLOATING | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16FLOAT
  273. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS12 | BPROP_MIN_PRECISION, // AR_BASIC_MIN12INT
  274. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16INT
  275. BPROP_PRIMITIVE | BPROP_NUMERIC | BPROP_INTEGER | BPROP_UNSIGNED | BPROP_BITS16 | BPROP_MIN_PRECISION, // AR_BASIC_MIN16UINT
  276. BPROP_ENUM | BPROP_NUMERIC | BPROP_INTEGER, // AR_BASIC_ENUM
  277. BPROP_OTHER, // AR_BASIC_COUNT
  278. //
  279. // Pseudo-entries for intrinsic tables and such.
  280. //
  281. 0, // AR_BASIC_NONE
  282. BPROP_OTHER, // AR_BASIC_UNKNOWN
  283. BPROP_OTHER, // AR_BASIC_NOCAST
  284. //
  285. // The following pseudo-entries represent higher-level
  286. // object types that are treated as units.
  287. //
  288. BPROP_POINTER, // AR_BASIC_POINTER
  289. BPROP_ENUM, // AR_BASIC_ENUM_CLASS
  290. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_NULL
  291. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRING
  292. // BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE
  293. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D
  294. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE1D_ARRAY
  295. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D
  296. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2D_ARRAY
  297. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE3D
  298. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE
  299. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURECUBE_ARRAY
  300. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS
  301. BPROP_OBJECT | BPROP_TEXTURE, // AR_OBJECT_TEXTURE2DMS_ARRAY
  302. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER
  303. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER1D
  304. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER2D
  305. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLER3D
  306. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCUBE
  307. BPROP_OBJECT | BPROP_SAMPLER, // AR_OBJECT_SAMPLERCOMPARISON
  308. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BUFFER
  309. BPROP_OBJECT, // AR_OBJECT_RENDERTARGETVIEW
  310. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCILVIEW
  311. BPROP_OBJECT, // AR_OBJECT_COMPUTESHADER
  312. BPROP_OBJECT, // AR_OBJECT_DOMAINSHADER
  313. BPROP_OBJECT, // AR_OBJECT_GEOMETRYSHADER
  314. BPROP_OBJECT, // AR_OBJECT_HULLSHADER
  315. BPROP_OBJECT, // AR_OBJECT_PIXELSHADER
  316. BPROP_OBJECT, // AR_OBJECT_VERTEXSHADER
  317. BPROP_OBJECT, // AR_OBJECT_PIXELFRAGMENT
  318. BPROP_OBJECT, // AR_OBJECT_VERTEXFRAGMENT
  319. BPROP_OBJECT, // AR_OBJECT_STATEBLOCK
  320. BPROP_OBJECT, // AR_OBJECT_RASTERIZER
  321. BPROP_OBJECT, // AR_OBJECT_DEPTHSTENCIL
  322. BPROP_OBJECT, // AR_OBJECT_BLEND
  323. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_POINTSTREAM
  324. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_LINESTREAM
  325. BPROP_OBJECT | BPROP_STREAM, // AR_OBJECT_TRIANGLESTREAM
  326. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_INPUTPATCH
  327. BPROP_OBJECT | BPROP_PATCH, // AR_OBJECT_OUTPUTPATCH
  328. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D
  329. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE1D_ARRAY
  330. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D
  331. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE2D_ARRAY
  332. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWTEXTURE3D
  333. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBUFFER
  334. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_BYTEADDRESS_BUFFER
  335. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  336. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_STRUCTURED_BUFFER
  337. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER
  338. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  339. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  340. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  341. BPROP_OBJECT | BPROP_RWBUFFER, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  342. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_CONSTANT_BUFFER
  343. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_TEXTURE_BUFFER
  344. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBUFFER
  345. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  346. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  347. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D
  348. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  349. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D
  350. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  351. BPROP_OBJECT | BPROP_RWBUFFER | BPROP_ROVBUFFER, // AR_OBJECT_ROVTEXTURE3D
  352. // SPIRV change starts
  353. #ifdef ENABLE_SPIRV_CODEGEN
  354. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_VK_SUBPASS_INPUT
  355. BPROP_OBJECT | BPROP_RBUFFER, // AR_OBJECT_VK_SUBPASS_INPUT_MS
  356. #endif // ENABLE_SPIRV_CODEGEN
  357. // SPIRV change ends
  358. BPROP_OBJECT, // AR_OBJECT_INNER
  359. BPROP_OBJECT, // AR_OBJECT_LEGACY_EFFECT
  360. BPROP_OBJECT, // AR_OBJECT_WAVE
  361. // AR_BASIC_MAXIMUM_COUNT
  362. };
  363. C_ASSERT(ARRAYSIZE(g_uBasicKindProps) == AR_BASIC_MAXIMUM_COUNT);
  364. #define GetBasicKindProps(_Kind) g_uBasicKindProps[(_Kind)]
  365. #define GET_BASIC_BITS(_Kind) \
  366. GET_BPROP_BITS(GetBasicKindProps(_Kind))
  367. #define GET_BASIC_PRIM_KIND(_Kind) \
  368. GET_BPROP_PRIM_KIND(GetBasicKindProps(_Kind))
  369. #define GET_BASIC_PRIM_KIND_SU(_Kind) \
  370. GET_BPROP_PRIM_KIND_SU(GetBasicKindProps(_Kind))
  371. #define IS_BASIC_PRIMITIVE(_Kind) \
  372. IS_BPROP_PRIMITIVE(GetBasicKindProps(_Kind))
  373. #define IS_BASIC_BOOL(_Kind) \
  374. IS_BPROP_BOOL(GetBasicKindProps(_Kind))
  375. #define IS_BASIC_FLOAT(_Kind) \
  376. IS_BPROP_FLOAT(GetBasicKindProps(_Kind))
  377. #define IS_BASIC_SINT(_Kind) \
  378. IS_BPROP_SINT(GetBasicKindProps(_Kind))
  379. #define IS_BASIC_UINT(_Kind) \
  380. IS_BPROP_UINT(GetBasicKindProps(_Kind))
  381. #define IS_BASIC_AINT(_Kind) \
  382. IS_BPROP_AINT(GetBasicKindProps(_Kind))
  383. #define IS_BASIC_STREAM(_Kind) \
  384. IS_BPROP_STREAM(GetBasicKindProps(_Kind))
  385. #define IS_BASIC_SAMPLER(_Kind) \
  386. IS_BPROP_SAMPLER(GetBasicKindProps(_Kind))
  387. #define IS_BASIC_TEXTURE(_Kind) \
  388. IS_BPROP_TEXTURE(GetBasicKindProps(_Kind))
  389. #define IS_BASIC_OBJECT(_Kind) \
  390. IS_BPROP_OBJECT(GetBasicKindProps(_Kind))
  391. #define IS_BASIC_MIN_PRECISION(_Kind) \
  392. IS_BPROP_MIN_PRECISION(GetBasicKindProps(_Kind))
  393. #define IS_BASIC_UNSIGNABLE(_Kind) \
  394. IS_BPROP_UNSIGNABLE(GetBasicKindProps(_Kind))
  395. #define IS_BASIC_ENUM(_Kind) \
  396. IS_BPROP_ENUM(GetBasicKindProps(_Kind))
  397. #define BITWISE_ENUM_OPS(_Type) \
  398. inline _Type operator|(_Type F1, _Type F2) \
  399. { \
  400. return (_Type)((UINT)F1 | (UINT)F2); \
  401. } \
  402. inline _Type operator&(_Type F1, _Type F2) \
  403. { \
  404. return (_Type)((UINT)F1 & (UINT)F2); \
  405. } \
  406. inline _Type& operator|=(_Type& F1, _Type F2) \
  407. { \
  408. F1 = F1 | F2; \
  409. return F1; \
  410. } \
  411. inline _Type& operator&=(_Type& F1, _Type F2) \
  412. { \
  413. F1 = F1 & F2; \
  414. return F1; \
  415. } \
  416. inline _Type& operator&=(_Type& F1, UINT F2) \
  417. { \
  418. F1 = (_Type)((UINT)F1 & F2); \
  419. return F1; \
  420. }
  421. enum ArTypeObjectKind {
  422. AR_TOBJ_INVALID, // Flag for an unassigned / unavailable object type.
  423. AR_TOBJ_VOID, // Represents the type for functions with not returned valued.
  424. AR_TOBJ_BASIC, // Represents a primitive type.
  425. AR_TOBJ_COMPOUND, // Represents a struct or class.
  426. AR_TOBJ_INTERFACE, // Represents an interface.
  427. AR_TOBJ_POINTER, // Represents a pointer to another type.
  428. AR_TOBJ_OBJECT, // Represents a built-in object.
  429. AR_TOBJ_ARRAY, // Represents an array of other types.
  430. AR_TOBJ_MATRIX, // Represents a matrix of basic types.
  431. AR_TOBJ_VECTOR, // Represents a vector of basic types.
  432. AR_TOBJ_QUALIFIER, // Represents another type plus an ArTypeQualifier.
  433. AR_TOBJ_INNER_OBJ, // Represents a built-in inner object, such as an
  434. // indexer object used to implement .mips[1].
  435. };
  436. enum TYPE_CONVERSION_FLAGS
  437. {
  438. TYPE_CONVERSION_DEFAULT = 0x00000000, // Indicates an implicit conversion is done.
  439. TYPE_CONVERSION_EXPLICIT = 0x00000001, // Indicates a conversion is done through an explicit cast.
  440. TYPE_CONVERSION_BY_REFERENCE = 0x00000002, // Indicates a conversion is done to an output parameter.
  441. };
  442. enum TYPE_CONVERSION_REMARKS
  443. {
  444. TYPE_CONVERSION_NONE = 0x00000000,
  445. TYPE_CONVERSION_PRECISION_LOSS = 0x00000001,
  446. TYPE_CONVERSION_IDENTICAL = 0x00000002,
  447. TYPE_CONVERSION_TO_VOID = 0x00000004,
  448. TYPE_CONVERSION_ELT_TRUNCATION = 0x00000008,
  449. };
  450. BITWISE_ENUM_OPS(TYPE_CONVERSION_REMARKS)
  451. #define AR_TOBJ_SCALAR AR_TOBJ_BASIC
  452. #define AR_TOBJ_UNKNOWN AR_TOBJ_INVALID
  453. #define AR_TPROP_VOID 0x0000000000000001
  454. #define AR_TPROP_CONST 0x0000000000000002
  455. #define AR_TPROP_IMP_CONST 0x0000000000000004
  456. #define AR_TPROP_OBJECT 0x0000000000000008
  457. #define AR_TPROP_SCALAR 0x0000000000000010
  458. #define AR_TPROP_UNSIGNED 0x0000000000000020
  459. #define AR_TPROP_NUMERIC 0x0000000000000040
  460. #define AR_TPROP_INTEGRAL 0x0000000000000080
  461. #define AR_TPROP_FLOATING 0x0000000000000100
  462. #define AR_TPROP_LITERAL 0x0000000000000200
  463. #define AR_TPROP_POINTER 0x0000000000000400
  464. #define AR_TPROP_INPUT_PATCH 0x0000000000000800
  465. #define AR_TPROP_OUTPUT_PATCH 0x0000000000001000
  466. #define AR_TPROP_INH_IFACE 0x0000000000002000
  467. #define AR_TPROP_HAS_COMPOUND 0x0000000000004000
  468. #define AR_TPROP_HAS_TEXTURES 0x0000000000008000
  469. #define AR_TPROP_HAS_SAMPLERS 0x0000000000010000
  470. #define AR_TPROP_HAS_SAMPLER_CMPS 0x0000000000020000
  471. #define AR_TPROP_HAS_STREAMS 0x0000000000040000
  472. #define AR_TPROP_HAS_OTHER_OBJECTS 0x0000000000080000
  473. #define AR_TPROP_HAS_BASIC 0x0000000000100000
  474. #define AR_TPROP_HAS_BUFFERS 0x0000000000200000
  475. #define AR_TPROP_HAS_ROBJECTS 0x0000000000400000
  476. #define AR_TPROP_HAS_POINTERS 0x0000000000800000
  477. #define AR_TPROP_INDEXABLE 0x0000000001000000
  478. #define AR_TPROP_HAS_MIPS 0x0000000002000000
  479. #define AR_TPROP_WRITABLE_GLOBAL 0x0000000004000000
  480. #define AR_TPROP_HAS_UAVS 0x0000000008000000
  481. #define AR_TPROP_HAS_BYTEADDRESS 0x0000000010000000
  482. #define AR_TPROP_HAS_STRUCTURED 0x0000000020000000
  483. #define AR_TPROP_HAS_SAMPLE 0x0000000040000000
  484. #define AR_TPROP_MIN_PRECISION 0x0000000080000000
  485. #define AR_TPROP_HAS_CBUFFERS 0x0000000100008000
  486. #define AR_TPROP_HAS_TBUFFERS 0x0000000200008000
  487. #define AR_TPROP_ALL 0xffffffffffffffff
  488. #define AR_TPROP_HAS_OBJECTS \
  489. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  490. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_STREAMS | \
  491. AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BUFFERS | \
  492. AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_UAVS | \
  493. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED)
  494. #define AR_TPROP_HAS_BASIC_RESOURCES \
  495. (AR_TPROP_HAS_TEXTURES | AR_TPROP_HAS_SAMPLERS | \
  496. AR_TPROP_HAS_SAMPLER_CMPS | AR_TPROP_HAS_BUFFERS | \
  497. AR_TPROP_HAS_UAVS)
  498. #define AR_TPROP_UNION_BITS \
  499. (AR_TPROP_INH_IFACE | AR_TPROP_HAS_COMPOUND | AR_TPROP_HAS_TEXTURES | \
  500. AR_TPROP_HAS_SAMPLERS | AR_TPROP_HAS_SAMPLER_CMPS | \
  501. AR_TPROP_HAS_STREAMS | AR_TPROP_HAS_OTHER_OBJECTS | AR_TPROP_HAS_BASIC | \
  502. AR_TPROP_HAS_BUFFERS | AR_TPROP_HAS_ROBJECTS | AR_TPROP_HAS_POINTERS | \
  503. AR_TPROP_WRITABLE_GLOBAL | AR_TPROP_HAS_UAVS | \
  504. AR_TPROP_HAS_BYTEADDRESS | AR_TPROP_HAS_STRUCTURED | AR_TPROP_MIN_PRECISION)
  505. #define AR_TINFO_ALLOW_COMPLEX 0x00000001
  506. #define AR_TINFO_ALLOW_OBJECTS 0x00000002
  507. #define AR_TINFO_IGNORE_QUALIFIERS 0x00000004
  508. #define AR_TINFO_OBJECTS_AS_ELEMENTS 0x00000008
  509. #define AR_TINFO_PACK_SCALAR 0x00000010
  510. #define AR_TINFO_PACK_ROW_MAJOR 0x00000020
  511. #define AR_TINFO_PACK_TEMP_ARRAY 0x00000040
  512. #define AR_TINFO_ALL_VAR_INFO 0x00000080
  513. #define AR_TINFO_ALLOW_ALL (AR_TINFO_ALLOW_COMPLEX | AR_TINFO_ALLOW_OBJECTS)
  514. #define AR_TINFO_PACK_CBUFFER 0
  515. #define AR_TINFO_LAYOUT_PACK_ALL (AR_TINFO_PACK_SCALAR | AR_TINFO_PACK_TEMP_ARRAY)
  516. #define AR_TINFO_SIMPLE_OBJECTS \
  517. (AR_TINFO_ALLOW_OBJECTS | AR_TINFO_OBJECTS_AS_ELEMENTS)
  518. struct ArTypeInfo {
  519. ArTypeObjectKind ShapeKind; // The shape of the type (basic, matrix, etc.)
  520. ArBasicKind EltKind; // The primitive type of elements in this type.
  521. ArBasicKind ObjKind; // The object type for this type (textures, buffers, etc.)
  522. UINT uRows;
  523. UINT uCols;
  524. UINT uTotalElts;
  525. };
  526. using namespace clang;
  527. using namespace clang::sema;
  528. using namespace hlsl;
  529. extern const char *HLSLScalarTypeNames[];
  530. static const int FirstTemplateDepth = 0;
  531. static const int FirstParamPosition = 0;
  532. static const bool ExplicitConversionFalse = false;// a conversion operation is not the result of an explicit cast
  533. static const bool InheritedFalse = false; // template parameter default value is not inherited.
  534. static const bool ParameterPackFalse = false; // template parameter is not an ellipsis.
  535. static const bool TypenameTrue = false; // 'typename' specified rather than 'class' for a template argument.
  536. static const bool DelayTypeCreationTrue = true; // delay type creation for a declaration
  537. static const bool DelayTypeCreationFalse = false; // immediately create a type when the declaration is created
  538. static const unsigned int NoQuals = 0; // no qualifiers in effect
  539. static const SourceLocation NoLoc; // no source location attribution available
  540. static const SourceRange NoRange; // no source range attribution available
  541. static const bool HasWrittenPrototypeTrue = true; // function had the prototype written
  542. static const bool InlineSpecifiedFalse = false; // function was not specified as inline
  543. static const bool IsConstexprFalse = false; // function is not constexpr
  544. static const bool ListInitializationFalse = false;// not performing a list initialization
  545. static const bool SuppressWarningsFalse = false; // do not suppress warning diagnostics
  546. static const bool SuppressWarningsTrue = true; // suppress warning diagnostics
  547. static const bool SuppressErrorsFalse = false; // do not suppress error diagnostics
  548. static const bool SuppressErrorsTrue = true; // suppress error diagnostics
  549. static const int OneRow = 1; // a single row for a type
  550. static const bool MipsFalse = false; // a type does not support the .mips member
  551. static const bool MipsTrue = true; // a type supports the .mips member
  552. static const bool SampleFalse = false; // a type does not support the .sample member
  553. static const bool SampleTrue = true; // a type supports the .sample member
  554. static const size_t MaxVectorSize = 4; // maximum size for a vector
  555. static
  556. QualType GetOrCreateTemplateSpecialization(
  557. ASTContext& context,
  558. Sema& sema,
  559. _In_ ClassTemplateDecl* templateDecl,
  560. ArrayRef<TemplateArgument> templateArgs
  561. )
  562. {
  563. DXASSERT_NOMSG(templateDecl);
  564. DeclContext* currentDeclContext = context.getTranslationUnitDecl();
  565. SmallVector<TemplateArgument, 3> templateArgsForDecl;
  566. for (const TemplateArgument& Arg : templateArgs) {
  567. if (Arg.getKind() == TemplateArgument::Type) {
  568. // the class template need to use CanonicalType
  569. templateArgsForDecl.emplace_back(TemplateArgument(Arg.getAsType().getCanonicalType()));
  570. }else
  571. templateArgsForDecl.emplace_back(Arg);
  572. }
  573. // First, try looking up existing specialization
  574. void* InsertPos = nullptr;
  575. ClassTemplateSpecializationDecl* specializationDecl =
  576. templateDecl->findSpecialization(templateArgsForDecl, InsertPos);
  577. if (specializationDecl) {
  578. // Instantiate the class template if not yet.
  579. if (specializationDecl->getInstantiatedFrom().isNull()) {
  580. // InstantiateClassTemplateSpecialization returns true if it finds an
  581. // error.
  582. DXVERIFY_NOMSG(false ==
  583. sema.InstantiateClassTemplateSpecialization(
  584. NoLoc, specializationDecl,
  585. TemplateSpecializationKind::TSK_ImplicitInstantiation,
  586. true));
  587. }
  588. return context.getTemplateSpecializationType(
  589. TemplateName(templateDecl), templateArgs.data(), templateArgs.size(),
  590. context.getTypeDeclType(specializationDecl));
  591. }
  592. specializationDecl = ClassTemplateSpecializationDecl::Create(
  593. context, TagDecl::TagKind::TTK_Class, currentDeclContext, NoLoc, NoLoc,
  594. templateDecl, templateArgsForDecl.data(), templateArgsForDecl.size(), nullptr);
  595. // InstantiateClassTemplateSpecialization returns true if it finds an error.
  596. DXVERIFY_NOMSG(false == sema.InstantiateClassTemplateSpecialization(
  597. NoLoc, specializationDecl, TemplateSpecializationKind::TSK_ImplicitInstantiation, true));
  598. templateDecl->AddSpecialization(specializationDecl, InsertPos);
  599. specializationDecl->setImplicit(true);
  600. QualType canonType = context.getTypeDeclType(specializationDecl);
  601. DXASSERT(isa<RecordType>(canonType), "type of non-dependent specialization is not a RecordType");
  602. TemplateArgumentListInfo templateArgumentList(NoLoc, NoLoc);
  603. TemplateArgumentLocInfo NoTemplateArgumentLocInfo;
  604. for (unsigned i = 0; i < templateArgs.size(); i++) {
  605. templateArgumentList.addArgument(TemplateArgumentLoc(templateArgs[i], NoTemplateArgumentLocInfo));
  606. }
  607. return context.getTemplateSpecializationType(
  608. TemplateName(templateDecl), templateArgumentList, canonType);
  609. }
  610. /// <summary>Instantiates a new matrix type specialization or gets an existing one from the AST.</summary>
  611. static
  612. QualType GetOrCreateMatrixSpecialization(ASTContext& context, Sema* sema,
  613. _In_ ClassTemplateDecl* matrixTemplateDecl,
  614. QualType elementType, uint64_t rowCount, uint64_t colCount)
  615. {
  616. DXASSERT_NOMSG(sema);
  617. TemplateArgument templateArgs[3] = {
  618. TemplateArgument(elementType),
  619. TemplateArgument(
  620. context,
  621. llvm::APSInt(
  622. llvm::APInt(context.getIntWidth(context.IntTy), rowCount), false),
  623. context.IntTy),
  624. TemplateArgument(
  625. context,
  626. llvm::APSInt(
  627. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  628. context.IntTy)};
  629. QualType matrixSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, matrixTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  630. #ifdef DBG
  631. // Verify that we can read the field member from the template record.
  632. DXASSERT(matrixSpecializationType->getAsCXXRecordDecl(),
  633. "type of non-dependent specialization is not a RecordType");
  634. DeclContext::lookup_result lookupResult = matrixSpecializationType->getAsCXXRecordDecl()->
  635. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  636. DXASSERT(!lookupResult.empty(), "otherwise matrix handle cannot be looked up");
  637. #endif
  638. return matrixSpecializationType;
  639. }
  640. /// <summary>Instantiates a new vector type specialization or gets an existing one from the AST.</summary>
  641. static
  642. QualType GetOrCreateVectorSpecialization(ASTContext& context, Sema* sema,
  643. _In_ ClassTemplateDecl* vectorTemplateDecl,
  644. QualType elementType, uint64_t colCount)
  645. {
  646. DXASSERT_NOMSG(sema);
  647. DXASSERT_NOMSG(vectorTemplateDecl);
  648. TemplateArgument templateArgs[2] = {
  649. TemplateArgument(elementType),
  650. TemplateArgument(
  651. context,
  652. llvm::APSInt(
  653. llvm::APInt(context.getIntWidth(context.IntTy), colCount), false),
  654. context.IntTy)};
  655. QualType vectorSpecializationType = GetOrCreateTemplateSpecialization(context, *sema, vectorTemplateDecl, ArrayRef<TemplateArgument>(templateArgs));
  656. #ifdef DBG
  657. // Verify that we can read the field member from the template record.
  658. DXASSERT(vectorSpecializationType->getAsCXXRecordDecl(),
  659. "type of non-dependent specialization is not a RecordType");
  660. DeclContext::lookup_result lookupResult = vectorSpecializationType->getAsCXXRecordDecl()->
  661. lookup(DeclarationName(&context.Idents.get(StringRef("h"))));
  662. DXASSERT(!lookupResult.empty(), "otherwise vector handle cannot be looked up");
  663. #endif
  664. return vectorSpecializationType;
  665. }
  666. // Decls.cpp constants start here - these should be refactored or, better, replaced with clang::Type-based constructs.
  667. static const LPCSTR kBuiltinIntrinsicTableName = "op";
  668. static const unsigned kAtomicDstOperandIdx = 1;
  669. static const ArTypeObjectKind g_ScalarTT[] =
  670. {
  671. AR_TOBJ_SCALAR,
  672. AR_TOBJ_UNKNOWN
  673. };
  674. static const ArTypeObjectKind g_VectorTT[] =
  675. {
  676. AR_TOBJ_VECTOR,
  677. AR_TOBJ_UNKNOWN
  678. };
  679. static const ArTypeObjectKind g_MatrixTT[] =
  680. {
  681. AR_TOBJ_MATRIX,
  682. AR_TOBJ_UNKNOWN
  683. };
  684. static const ArTypeObjectKind g_AnyTT[] =
  685. {
  686. AR_TOBJ_SCALAR,
  687. AR_TOBJ_VECTOR,
  688. AR_TOBJ_MATRIX,
  689. AR_TOBJ_UNKNOWN
  690. };
  691. static const ArTypeObjectKind g_ObjectTT[] =
  692. {
  693. AR_TOBJ_OBJECT,
  694. AR_TOBJ_UNKNOWN
  695. };
  696. static const ArTypeObjectKind g_NullTT[] =
  697. {
  698. AR_TOBJ_VOID,
  699. AR_TOBJ_UNKNOWN
  700. };
  701. const ArTypeObjectKind* g_LegalIntrinsicTemplates[] =
  702. {
  703. g_NullTT,
  704. g_ScalarTT,
  705. g_VectorTT,
  706. g_MatrixTT,
  707. g_AnyTT,
  708. g_ObjectTT,
  709. };
  710. C_ASSERT(ARRAYSIZE(g_LegalIntrinsicTemplates) == LITEMPLATE_COUNT);
  711. //
  712. // The first one is used to name the representative group, so make
  713. // sure its name will make sense in error messages.
  714. //
  715. static const ArBasicKind g_BoolCT[] =
  716. {
  717. AR_BASIC_BOOL,
  718. AR_BASIC_UNKNOWN
  719. };
  720. static const ArBasicKind g_IntCT[] =
  721. {
  722. AR_BASIC_INT32,
  723. AR_BASIC_LITERAL_INT,
  724. AR_BASIC_UNKNOWN
  725. };
  726. static const ArBasicKind g_UIntCT[] =
  727. {
  728. AR_BASIC_UINT32,
  729. AR_BASIC_LITERAL_INT,
  730. AR_BASIC_UNKNOWN
  731. };
  732. static const ArBasicKind g_AnyIntCT[] =
  733. {
  734. AR_BASIC_INT16,
  735. AR_BASIC_INT32,
  736. AR_BASIC_UINT16,
  737. AR_BASIC_UINT32,
  738. AR_BASIC_INT64,
  739. AR_BASIC_UINT64,
  740. AR_BASIC_LITERAL_INT,
  741. AR_BASIC_UNKNOWN
  742. };
  743. static const ArBasicKind g_AnyInt32CT[] =
  744. {
  745. AR_BASIC_INT32,
  746. AR_BASIC_UINT32,
  747. AR_BASIC_LITERAL_INT,
  748. AR_BASIC_UNKNOWN
  749. };
  750. static const ArBasicKind g_UIntOnlyCT[] =
  751. {
  752. AR_BASIC_UINT32,
  753. AR_BASIC_UINT64,
  754. AR_BASIC_LITERAL_INT,
  755. AR_BASIC_NOCAST,
  756. AR_BASIC_UNKNOWN
  757. };
  758. static const ArBasicKind g_FloatCT[] =
  759. {
  760. AR_BASIC_FLOAT32,
  761. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  762. AR_BASIC_LITERAL_FLOAT,
  763. AR_BASIC_UNKNOWN
  764. };
  765. static const ArBasicKind g_AnyFloatCT[] =
  766. {
  767. AR_BASIC_FLOAT32,
  768. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  769. AR_BASIC_FLOAT16,
  770. AR_BASIC_FLOAT64,
  771. AR_BASIC_LITERAL_FLOAT,
  772. AR_BASIC_MIN10FLOAT,
  773. AR_BASIC_MIN16FLOAT,
  774. AR_BASIC_UNKNOWN
  775. };
  776. static const ArBasicKind g_FloatLikeCT[] =
  777. {
  778. AR_BASIC_FLOAT32,
  779. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  780. AR_BASIC_FLOAT16,
  781. AR_BASIC_LITERAL_FLOAT,
  782. AR_BASIC_MIN10FLOAT,
  783. AR_BASIC_MIN16FLOAT,
  784. AR_BASIC_UNKNOWN
  785. };
  786. static const ArBasicKind g_FloatDoubleCT[] =
  787. {
  788. AR_BASIC_FLOAT32,
  789. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  790. AR_BASIC_FLOAT64,
  791. AR_BASIC_LITERAL_FLOAT,
  792. AR_BASIC_UNKNOWN
  793. };
  794. static const ArBasicKind g_DoubleCT[] =
  795. {
  796. AR_BASIC_FLOAT64,
  797. AR_BASIC_LITERAL_FLOAT,
  798. AR_BASIC_UNKNOWN
  799. };
  800. static const ArBasicKind g_DoubleOnlyCT[] =
  801. {
  802. AR_BASIC_FLOAT64,
  803. AR_BASIC_NOCAST,
  804. AR_BASIC_UNKNOWN
  805. };
  806. static const ArBasicKind g_NumericCT[] =
  807. {
  808. AR_BASIC_LITERAL_FLOAT,
  809. AR_BASIC_FLOAT32,
  810. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  811. AR_BASIC_FLOAT16,
  812. AR_BASIC_FLOAT64,
  813. AR_BASIC_MIN10FLOAT,
  814. AR_BASIC_MIN16FLOAT,
  815. AR_BASIC_LITERAL_INT,
  816. AR_BASIC_INT16,
  817. AR_BASIC_INT32,
  818. AR_BASIC_UINT16,
  819. AR_BASIC_UINT32,
  820. AR_BASIC_MIN12INT,
  821. AR_BASIC_MIN16INT,
  822. AR_BASIC_MIN16UINT,
  823. AR_BASIC_INT64,
  824. AR_BASIC_UINT64,
  825. AR_BASIC_UNKNOWN
  826. };
  827. static const ArBasicKind g_Numeric32CT[] =
  828. {
  829. AR_BASIC_LITERAL_FLOAT,
  830. AR_BASIC_FLOAT32,
  831. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  832. AR_BASIC_LITERAL_INT,
  833. AR_BASIC_INT32,
  834. AR_BASIC_UINT32,
  835. AR_BASIC_UNKNOWN
  836. };
  837. static const ArBasicKind g_Numeric32OnlyCT[] =
  838. {
  839. AR_BASIC_LITERAL_FLOAT,
  840. AR_BASIC_FLOAT32,
  841. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  842. AR_BASIC_LITERAL_INT,
  843. AR_BASIC_INT32,
  844. AR_BASIC_UINT32,
  845. AR_BASIC_NOCAST,
  846. AR_BASIC_UNKNOWN
  847. };
  848. static const ArBasicKind g_AnyCT[] =
  849. {
  850. AR_BASIC_LITERAL_FLOAT,
  851. AR_BASIC_FLOAT32,
  852. AR_BASIC_FLOAT32_PARTIAL_PRECISION,
  853. AR_BASIC_FLOAT16,
  854. AR_BASIC_FLOAT64,
  855. AR_BASIC_MIN10FLOAT,
  856. AR_BASIC_MIN16FLOAT,
  857. AR_BASIC_LITERAL_INT,
  858. AR_BASIC_INT16,
  859. AR_BASIC_UINT16,
  860. AR_BASIC_INT32,
  861. AR_BASIC_UINT32,
  862. AR_BASIC_MIN12INT,
  863. AR_BASIC_MIN16INT,
  864. AR_BASIC_MIN16UINT,
  865. AR_BASIC_BOOL,
  866. AR_BASIC_INT64,
  867. AR_BASIC_UINT64,
  868. AR_BASIC_UNKNOWN
  869. };
  870. static const ArBasicKind g_Sampler1DCT[] =
  871. {
  872. AR_OBJECT_SAMPLER1D,
  873. AR_BASIC_UNKNOWN
  874. };
  875. static const ArBasicKind g_Sampler2DCT[] =
  876. {
  877. AR_OBJECT_SAMPLER2D,
  878. AR_BASIC_UNKNOWN
  879. };
  880. static const ArBasicKind g_Sampler3DCT[] =
  881. {
  882. AR_OBJECT_SAMPLER3D,
  883. AR_BASIC_UNKNOWN
  884. };
  885. static const ArBasicKind g_SamplerCUBECT[] =
  886. {
  887. AR_OBJECT_SAMPLERCUBE,
  888. AR_BASIC_UNKNOWN
  889. };
  890. static const ArBasicKind g_SamplerCmpCT[] =
  891. {
  892. AR_OBJECT_SAMPLERCOMPARISON,
  893. AR_BASIC_UNKNOWN
  894. };
  895. static const ArBasicKind g_SamplerCT[] =
  896. {
  897. AR_OBJECT_SAMPLER,
  898. AR_BASIC_UNKNOWN
  899. };
  900. static const ArBasicKind g_StringCT[] =
  901. {
  902. AR_OBJECT_STRING,
  903. AR_BASIC_UNKNOWN
  904. };
  905. static const ArBasicKind g_NullCT[] =
  906. {
  907. AR_OBJECT_NULL,
  908. AR_BASIC_UNKNOWN
  909. };
  910. static const ArBasicKind g_WaveCT[] =
  911. {
  912. AR_OBJECT_WAVE,
  913. AR_BASIC_UNKNOWN
  914. };
  915. static const ArBasicKind g_UInt64CT[] =
  916. {
  917. AR_BASIC_UINT64,
  918. AR_BASIC_UNKNOWN
  919. };
  920. static const ArBasicKind g_UInt163264CT[] =
  921. {
  922. AR_BASIC_UINT32,
  923. AR_BASIC_UINT16,
  924. AR_BASIC_UINT64,
  925. AR_BASIC_LITERAL_INT,
  926. AR_BASIC_UNKNOWN
  927. };
  928. static const ArBasicKind g_Float16CT[] =
  929. {
  930. AR_BASIC_FLOAT16,
  931. AR_BASIC_LITERAL_FLOAT,
  932. AR_BASIC_UNKNOWN
  933. };
  934. static const ArBasicKind g_Int16CT[] =
  935. {
  936. AR_BASIC_INT16,
  937. AR_BASIC_LITERAL_INT,
  938. AR_BASIC_UNKNOWN
  939. };
  940. static const ArBasicKind g_UInt16CT[] =
  941. {
  942. AR_BASIC_UINT16,
  943. AR_BASIC_LITERAL_INT,
  944. AR_BASIC_UNKNOWN
  945. };
  946. static const ArBasicKind g_Numeric16OnlyCT[] =
  947. {
  948. AR_BASIC_FLOAT16,
  949. AR_BASIC_INT16,
  950. AR_BASIC_UINT16,
  951. AR_BASIC_LITERAL_FLOAT,
  952. AR_BASIC_LITERAL_INT,
  953. AR_BASIC_NOCAST,
  954. AR_BASIC_UNKNOWN
  955. };
  956. // Basic kinds, indexed by a LEGAL_INTRINSIC_COMPTYPES value.
  957. const ArBasicKind* g_LegalIntrinsicCompTypes[] =
  958. {
  959. g_NullCT, // LICOMPTYPE_VOID
  960. g_BoolCT, // LICOMPTYPE_BOOL
  961. g_IntCT, // LICOMPTYPE_INT
  962. g_UIntCT, // LICOMPTYPE_UINT
  963. g_AnyIntCT, // LICOMPTYPE_ANY_INT
  964. g_AnyInt32CT, // LICOMPTYPE_ANY_INT32
  965. g_UIntOnlyCT, // LICOMPTYPE_UINT_ONLY
  966. g_FloatCT, // LICOMPTYPE_FLOAT
  967. g_AnyFloatCT, // LICOMPTYPE_ANY_FLOAT
  968. g_FloatLikeCT, // LICOMPTYPE_FLOAT_LIKE
  969. g_FloatDoubleCT, // LICOMPTYPE_FLOAT_DOUBLE
  970. g_DoubleCT, // LICOMPTYPE_DOUBLE
  971. g_DoubleOnlyCT, // LICOMPTYPE_DOUBLE_ONLY
  972. g_NumericCT, // LICOMPTYPE_NUMERIC
  973. g_Numeric32CT, // LICOMPTYPE_NUMERIC32
  974. g_Numeric32OnlyCT, // LICOMPTYPE_NUMERIC32_ONLY
  975. g_AnyCT, // LICOMPTYPE_ANY
  976. g_Sampler1DCT, // LICOMPTYPE_SAMPLER1D
  977. g_Sampler2DCT, // LICOMPTYPE_SAMPLER2D
  978. g_Sampler3DCT, // LICOMPTYPE_SAMPLER3D
  979. g_SamplerCUBECT, // LICOMPTYPE_SAMPLERCUBE
  980. g_SamplerCmpCT, // LICOMPTYPE_SAMPLERCMP
  981. g_SamplerCT, // LICOMPTYPE_SAMPLER
  982. g_StringCT, // LICOMPTYPE_STRING
  983. g_WaveCT, // LICOMPTYPE_WAVE
  984. g_UInt64CT, // LICOMPTYPE_UINT64
  985. g_UInt163264CT, // LICOMPTYPE_UINT16_32_64
  986. g_Float16CT, // LICOMPTYPE_FLOAT16
  987. g_Int16CT, // LICOMPTYPE_INT16
  988. g_UInt16CT, // LICOMPTYPE_UINT16
  989. g_Numeric16OnlyCT // LICOMPTYPE_NUMERIC16_ONLY
  990. };
  991. C_ASSERT(ARRAYSIZE(g_LegalIntrinsicCompTypes) == LICOMPTYPE_COUNT);
  992. // Decls.cpp constants ends here - these should be refactored or, better, replaced with clang::Type-based constructs.
  993. // Basic kind objects that are represented as HLSL structures or templates.
  994. static
  995. const ArBasicKind g_ArBasicKindsAsTypes[] =
  996. {
  997. AR_OBJECT_BUFFER, // Buffer
  998. // AR_OBJECT_TEXTURE,
  999. AR_OBJECT_TEXTURE1D, // Texture1D
  1000. AR_OBJECT_TEXTURE1D_ARRAY, // Texture1DArray
  1001. AR_OBJECT_TEXTURE2D, // Texture2D
  1002. AR_OBJECT_TEXTURE2D_ARRAY, // Texture2DArray
  1003. AR_OBJECT_TEXTURE3D, // Texture3D
  1004. AR_OBJECT_TEXTURECUBE, // TextureCube
  1005. AR_OBJECT_TEXTURECUBE_ARRAY, // TextureCubeArray
  1006. AR_OBJECT_TEXTURE2DMS, // Texture2DMS
  1007. AR_OBJECT_TEXTURE2DMS_ARRAY, // Texture2DMSArray
  1008. AR_OBJECT_SAMPLER,
  1009. //AR_OBJECT_SAMPLER1D,
  1010. //AR_OBJECT_SAMPLER2D,
  1011. //AR_OBJECT_SAMPLER3D,
  1012. //AR_OBJECT_SAMPLERCUBE,
  1013. AR_OBJECT_SAMPLERCOMPARISON,
  1014. AR_OBJECT_POINTSTREAM,
  1015. AR_OBJECT_LINESTREAM,
  1016. AR_OBJECT_TRIANGLESTREAM,
  1017. AR_OBJECT_INPUTPATCH,
  1018. AR_OBJECT_OUTPUTPATCH,
  1019. AR_OBJECT_RWTEXTURE1D,
  1020. AR_OBJECT_RWTEXTURE1D_ARRAY,
  1021. AR_OBJECT_RWTEXTURE2D,
  1022. AR_OBJECT_RWTEXTURE2D_ARRAY,
  1023. AR_OBJECT_RWTEXTURE3D,
  1024. AR_OBJECT_RWBUFFER,
  1025. AR_OBJECT_BYTEADDRESS_BUFFER,
  1026. AR_OBJECT_RWBYTEADDRESS_BUFFER,
  1027. AR_OBJECT_STRUCTURED_BUFFER,
  1028. AR_OBJECT_RWSTRUCTURED_BUFFER,
  1029. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  1030. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  1031. AR_OBJECT_APPEND_STRUCTURED_BUFFER,
  1032. AR_OBJECT_CONSUME_STRUCTURED_BUFFER,
  1033. AR_OBJECT_ROVBUFFER,
  1034. AR_OBJECT_ROVBYTEADDRESS_BUFFER,
  1035. AR_OBJECT_ROVSTRUCTURED_BUFFER,
  1036. AR_OBJECT_ROVTEXTURE1D,
  1037. AR_OBJECT_ROVTEXTURE1D_ARRAY,
  1038. AR_OBJECT_ROVTEXTURE2D,
  1039. AR_OBJECT_ROVTEXTURE2D_ARRAY,
  1040. AR_OBJECT_ROVTEXTURE3D,
  1041. // SPIRV change starts
  1042. #ifdef ENABLE_SPIRV_CODEGEN
  1043. AR_OBJECT_VK_SUBPASS_INPUT,
  1044. AR_OBJECT_VK_SUBPASS_INPUT_MS,
  1045. #endif // ENABLE_SPIRV_CODEGEN
  1046. // SPIRV change ends
  1047. AR_OBJECT_LEGACY_EFFECT, // Used for all unsupported but ignored legacy effect types
  1048. AR_OBJECT_WAVE
  1049. };
  1050. // Count of template arguments for basic kind of objects that look like templates (one or more type arguments).
  1051. static
  1052. const uint8_t g_ArBasicKindsTemplateCount[] =
  1053. {
  1054. 1, // AR_OBJECT_BUFFER
  1055. // AR_OBJECT_TEXTURE,
  1056. 1, // AR_OBJECT_TEXTURE1D
  1057. 1, // AR_OBJECT_TEXTURE1D_ARRAY
  1058. 1, // AR_OBJECT_TEXTURE2D
  1059. 1, // AR_OBJECT_TEXTURE2D_ARRAY
  1060. 1, // AR_OBJECT_TEXTURE3D
  1061. 1, // AR_OBJECT_TEXTURECUBE
  1062. 1, // AR_OBJECT_TEXTURECUBE_ARRAY
  1063. 2, // AR_OBJECT_TEXTURE2DMS
  1064. 2, // AR_OBJECT_TEXTURE2DMS_ARRAY
  1065. 0, // AR_OBJECT_SAMPLER
  1066. //AR_OBJECT_SAMPLER1D,
  1067. //AR_OBJECT_SAMPLER2D,
  1068. //AR_OBJECT_SAMPLER3D,
  1069. //AR_OBJECT_SAMPLERCUBE,
  1070. 0, // AR_OBJECT_SAMPLERCOMPARISON
  1071. 1, // AR_OBJECT_POINTSTREAM
  1072. 1, // AR_OBJECT_LINESTREAM
  1073. 1, // AR_OBJECT_TRIANGLESTREAM
  1074. 2, // AR_OBJECT_INPUTPATCH
  1075. 2, // AR_OBJECT_OUTPUTPATCH
  1076. 1, // AR_OBJECT_RWTEXTURE1D
  1077. 1, // AR_OBJECT_RWTEXTURE1D_ARRAY
  1078. 1, // AR_OBJECT_RWTEXTURE2D
  1079. 1, // AR_OBJECT_RWTEXTURE2D_ARRAY
  1080. 1, // AR_OBJECT_RWTEXTURE3D
  1081. 1, // AR_OBJECT_RWBUFFER
  1082. 0, // AR_OBJECT_BYTEADDRESS_BUFFER
  1083. 0, // AR_OBJECT_RWBYTEADDRESS_BUFFER
  1084. 1, // AR_OBJECT_STRUCTURED_BUFFER
  1085. 1, // AR_OBJECT_RWSTRUCTURED_BUFFER
  1086. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC
  1087. // 1, // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME
  1088. 1, // AR_OBJECT_APPEND_STRUCTURED_BUFFER
  1089. 1, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER
  1090. 1, // AR_OBJECT_ROVBUFFER
  1091. 0, // AR_OBJECT_ROVBYTEADDRESS_BUFFER
  1092. 1, // AR_OBJECT_ROVSTRUCTURED_BUFFER
  1093. 1, // AR_OBJECT_ROVTEXTURE1D
  1094. 1, // AR_OBJECT_ROVTEXTURE1D_ARRAY
  1095. 1, // AR_OBJECT_ROVTEXTURE2D
  1096. 1, // AR_OBJECT_ROVTEXTURE2D_ARRAY
  1097. 1, // AR_OBJECT_ROVTEXTURE3D
  1098. // SPIRV change starts
  1099. #ifdef ENABLE_SPIRV_CODEGEN
  1100. 1, // AR_OBJECT_VK_SUBPASS_INPUT
  1101. 1, // AR_OBJECT_VK_SUBPASS_INPUT_MS
  1102. #endif // ENABLE_SPIRV_CODEGEN
  1103. // SPIRV change ends
  1104. 0, // AR_OBJECT_LEGACY_EFFECT // Used for all unsupported but ignored legacy effect types
  1105. 0, // AR_OBJECT_WAVE
  1106. };
  1107. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsTemplateCount));
  1108. /// <summary>Describes the how the subscript or indexing operators work on a given type.</summary>
  1109. struct SubscriptOperatorRecord
  1110. {
  1111. unsigned int SubscriptCardinality : 4; // Number of elements expected in subscript - zero if operator not supported.
  1112. bool HasMips : 1; // true if the kind has a mips member; false otherwise
  1113. bool HasSample : 1; // true if the kind has a sample member; false otherwise
  1114. };
  1115. // Subscript operators for objects that are represented as HLSL structures or templates.
  1116. static
  1117. const SubscriptOperatorRecord g_ArBasicKindsSubscripts[] =
  1118. {
  1119. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_BUFFER (Buffer)
  1120. // AR_OBJECT_TEXTURE,
  1121. { 1, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D (Texture1D)
  1122. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE1D_ARRAY (Texture1DArray)
  1123. { 2, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D (Texture2D)
  1124. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE2D_ARRAY (Texture2DArray)
  1125. { 3, MipsTrue, SampleFalse }, // AR_OBJECT_TEXTURE3D (Texture3D)
  1126. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE (TextureCube)
  1127. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TEXTURECUBE_ARRAY (TextureCubeArray)
  1128. { 2, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS (Texture2DMS)
  1129. { 3, MipsFalse, SampleTrue }, // AR_OBJECT_TEXTURE2DMS_ARRAY (Texture2DMSArray)
  1130. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLER (SamplerState)
  1131. //AR_OBJECT_SAMPLER1D,
  1132. //AR_OBJECT_SAMPLER2D,
  1133. //AR_OBJECT_SAMPLER3D,
  1134. //AR_OBJECT_SAMPLERCUBE,
  1135. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_SAMPLERCOMPARISON (SamplerComparison)
  1136. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_POINTSTREAM (PointStream)
  1137. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LINESTREAM (LineStream)
  1138. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_TRIANGLESTREAM (TriangleStream)
  1139. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_INPUTPATCH (InputPatch)
  1140. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_OUTPUTPATCH (OutputPatch)
  1141. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D (RWTexture1D)
  1142. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE1D_ARRAY (RWTexture1DArray)
  1143. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D (RWTexture2D)
  1144. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE2D_ARRAY (RWTexture2DArray)
  1145. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_RWTEXTURE3D (RWTexture3D)
  1146. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWBUFFER (RWBuffer)
  1147. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_BYTEADDRESS_BUFFER (ByteAddressBuffer)
  1148. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_RWBYTEADDRESS_BUFFER (RWByteAddressBuffer)
  1149. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_STRUCTURED_BUFFER (StructuredBuffer)
  1150. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_RWSTRUCTURED_BUFFER (RWStructuredBuffer)
  1151. // AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC,
  1152. // AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME,
  1153. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_APPEND_STRUCTURED_BUFFER (AppendStructuredBuffer)
  1154. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_CONSUME_STRUCTURED_BUFFER (ConsumeStructuredBuffer)
  1155. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBUFFER (ROVBuffer)
  1156. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_ROVBYTEADDRESS_BUFFER (ROVByteAddressBuffer)
  1157. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVSTRUCTURED_BUFFER (ROVStructuredBuffer)
  1158. { 1, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D (ROVTexture1D)
  1159. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE1D_ARRAY (ROVTexture1DArray)
  1160. { 2, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D (ROVTexture2D)
  1161. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE2D_ARRAY (ROVTexture2DArray)
  1162. { 3, MipsFalse, SampleFalse }, // AR_OBJECT_ROVTEXTURE3D (ROVTexture3D)
  1163. // SPIRV change starts
  1164. #ifdef ENABLE_SPIRV_CODEGEN
  1165. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_VK_SUBPASS_INPUT (SubpassInput)
  1166. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_VK_SUBPASS_INPUT_MS (SubpassInputMS)
  1167. #endif // ENABLE_SPIRV_CODEGEN
  1168. // SPIRV change ends
  1169. { 0, MipsFalse, SampleFalse }, // AR_OBJECT_LEGACY_EFFECT (legacy effect objects)
  1170. { 0, MipsFalse, SampleFalse } // AR_OBJECT_WAVE
  1171. };
  1172. C_ASSERT(_countof(g_ArBasicKindsAsTypes) == _countof(g_ArBasicKindsSubscripts));
  1173. // Type names for ArBasicKind values.
  1174. static
  1175. const char* g_ArBasicTypeNames[] =
  1176. {
  1177. "bool", "float", "half", "half", "float", "double",
  1178. "int", "sbyte", "byte", "short", "ushort",
  1179. "int", "uint", "long", "ulong",
  1180. "min10float", "min16float",
  1181. "min12int", "min16int", "min16uint",
  1182. "enum",
  1183. "<count>",
  1184. "<none>",
  1185. "<unknown>",
  1186. "<nocast>",
  1187. "<pointer>",
  1188. "enum class",
  1189. "null",
  1190. "string",
  1191. // "texture",
  1192. "Texture1D",
  1193. "Texture1DArray",
  1194. "Texture2D",
  1195. "Texture2DArray",
  1196. "Texture3D",
  1197. "TextureCube",
  1198. "TextureCubeArray",
  1199. "Texture2DMS",
  1200. "Texture2DMSArray",
  1201. "SamplerState",
  1202. "sampler1D",
  1203. "sampler2D",
  1204. "sampler3D",
  1205. "samplerCUBE",
  1206. "SamplerComparisonState",
  1207. "Buffer",
  1208. "RenderTargetView",
  1209. "DepthStencilView",
  1210. "ComputeShader",
  1211. "DomainShader",
  1212. "GeometryShader",
  1213. "HullShader",
  1214. "PixelShader",
  1215. "VertexShader",
  1216. "pixelfragment",
  1217. "vertexfragment",
  1218. "StateBlock",
  1219. "Rasterizer",
  1220. "DepthStencil",
  1221. "Blend",
  1222. "PointStream",
  1223. "LineStream",
  1224. "TriangleStream",
  1225. "InputPatch",
  1226. "OutputPatch",
  1227. "RWTexture1D",
  1228. "RWTexture1DArray",
  1229. "RWTexture2D",
  1230. "RWTexture2DArray",
  1231. "RWTexture3D",
  1232. "RWBuffer",
  1233. "ByteAddressBuffer",
  1234. "RWByteAddressBuffer",
  1235. "StructuredBuffer",
  1236. "RWStructuredBuffer",
  1237. "RWStructuredBuffer(Incrementable)",
  1238. "RWStructuredBuffer(Decrementable)",
  1239. "AppendStructuredBuffer",
  1240. "ConsumeStructuredBuffer",
  1241. "ConstantBuffer",
  1242. "TextureBuffer",
  1243. "RasterizerOrderedBuffer",
  1244. "RasterizerOrderedByteAddressBuffer",
  1245. "RasterizerOrderedStructuredBuffer",
  1246. "RasterizerOrderedTexture1D",
  1247. "RasterizerOrderedTexture1DArray",
  1248. "RasterizerOrderedTexture2D",
  1249. "RasterizerOrderedTexture2DArray",
  1250. "RasterizerOrderedTexture3D",
  1251. // SPIRV change starts
  1252. #ifdef ENABLE_SPIRV_CODEGEN
  1253. "SubpassInput",
  1254. "SubpassInputMS",
  1255. #endif // ENABLE_SPIRV_CODEGEN
  1256. // SPIRV change ends
  1257. "<internal inner type object>",
  1258. "deprecated effect object",
  1259. "wave_t"
  1260. };
  1261. C_ASSERT(_countof(g_ArBasicTypeNames) == AR_BASIC_MAXIMUM_COUNT);
  1262. // kind should never be a flag value or effects framework type - we simply do not expect to deal with these
  1263. #define DXASSERT_VALIDBASICKIND(kind) \
  1264. DXASSERT(\
  1265. kind != AR_BASIC_COUNT && \
  1266. kind != AR_BASIC_NONE && \
  1267. kind != AR_BASIC_UNKNOWN && \
  1268. kind != AR_BASIC_NOCAST && \
  1269. kind != AR_BASIC_POINTER && \
  1270. kind != AR_OBJECT_RENDERTARGETVIEW && \
  1271. kind != AR_OBJECT_DEPTHSTENCILVIEW && \
  1272. kind != AR_OBJECT_COMPUTESHADER && \
  1273. kind != AR_OBJECT_DOMAINSHADER && \
  1274. kind != AR_OBJECT_GEOMETRYSHADER && \
  1275. kind != AR_OBJECT_HULLSHADER && \
  1276. kind != AR_OBJECT_PIXELSHADER && \
  1277. kind != AR_OBJECT_VERTEXSHADER && \
  1278. kind != AR_OBJECT_PIXELFRAGMENT && \
  1279. kind != AR_OBJECT_VERTEXFRAGMENT, "otherwise caller is using a special flag or an unsupported kind value");
  1280. static
  1281. const char* g_DeprecatedEffectObjectNames[] =
  1282. {
  1283. // These are case insensitive in fxc, but we'll just create two case aliases
  1284. // to capture the majority of cases
  1285. "texture", "Texture",
  1286. "pixelshader", "PixelShader",
  1287. "vertexshader", "VertexShader",
  1288. // These are case sensitive in fxc
  1289. "pixelfragment", // 13
  1290. "vertexfragment", // 14
  1291. "ComputeShader", // 13
  1292. "DomainShader", // 12
  1293. "GeometryShader", // 14
  1294. "HullShader", // 10
  1295. "BlendState", // 10
  1296. "DepthStencilState",// 17
  1297. "DepthStencilView", // 16
  1298. "RasterizerState", // 15
  1299. "RenderTargetView", // 16
  1300. };
  1301. // The CompareStringsWithLen function lexicographically compares LHS and RHS and
  1302. // returns a value indicating the relationship between the strings - < 0 if LHS is
  1303. // less than RHS, 0 if they are equal, > 0 if LHS is greater than RHS.
  1304. static
  1305. int CompareStringsWithLen(
  1306. _In_count_(LHSlen) const char* LHS, size_t LHSlen,
  1307. _In_count_(RHSlen) const char* RHS, size_t RHSlen
  1308. )
  1309. {
  1310. // Check whether the name is greater or smaller (without walking past end).
  1311. size_t maxNameComparable = std::min(LHSlen, RHSlen);
  1312. int comparison = strncmp(LHS, RHS, maxNameComparable);
  1313. if (comparison != 0) return comparison;
  1314. // Check whether the name is greater or smaller based on extra characters.
  1315. return LHSlen - RHSlen;
  1316. }
  1317. static hlsl::ParameterModifier
  1318. ParamModsFromIntrinsicArg(const HLSL_INTRINSIC_ARGUMENT *pArg) {
  1319. if (pArg->qwUsage == AR_QUAL_IN_OUT) {
  1320. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::InOut);
  1321. }
  1322. if (pArg->qwUsage == AR_QUAL_OUT) {
  1323. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::Out);
  1324. }
  1325. DXASSERT(pArg->qwUsage & AR_QUAL_IN, "else usage is incorrect");
  1326. return hlsl::ParameterModifier(hlsl::ParameterModifier::Kind::In);
  1327. }
  1328. static void InitParamMods(const HLSL_INTRINSIC *pIntrinsic,
  1329. SmallVectorImpl<hlsl::ParameterModifier> &paramMods) {
  1330. // The first argument is the return value, which isn't included.
  1331. for (UINT i = 1; i < pIntrinsic->uNumArgs; ++i) {
  1332. paramMods.push_back(ParamModsFromIntrinsicArg(&pIntrinsic->pArgs[i]));
  1333. }
  1334. }
  1335. static bool IsAtomicOperation(IntrinsicOp op) {
  1336. switch (op) {
  1337. case IntrinsicOp::IOP_InterlockedAdd:
  1338. case IntrinsicOp::IOP_InterlockedAnd:
  1339. case IntrinsicOp::IOP_InterlockedCompareExchange:
  1340. case IntrinsicOp::IOP_InterlockedCompareStore:
  1341. case IntrinsicOp::IOP_InterlockedExchange:
  1342. case IntrinsicOp::IOP_InterlockedMax:
  1343. case IntrinsicOp::IOP_InterlockedMin:
  1344. case IntrinsicOp::IOP_InterlockedOr:
  1345. case IntrinsicOp::IOP_InterlockedXor:
  1346. case IntrinsicOp::MOP_InterlockedAdd:
  1347. case IntrinsicOp::MOP_InterlockedAnd:
  1348. case IntrinsicOp::MOP_InterlockedCompareExchange:
  1349. case IntrinsicOp::MOP_InterlockedCompareStore:
  1350. case IntrinsicOp::MOP_InterlockedExchange:
  1351. case IntrinsicOp::MOP_InterlockedMax:
  1352. case IntrinsicOp::MOP_InterlockedMin:
  1353. case IntrinsicOp::MOP_InterlockedOr:
  1354. case IntrinsicOp::MOP_InterlockedXor:
  1355. return true;
  1356. default:
  1357. return false;
  1358. }
  1359. }
  1360. static bool IsBuiltinTable(LPCSTR tableName) {
  1361. return tableName == kBuiltinIntrinsicTableName;
  1362. }
  1363. static void AddHLSLIntrinsicAttr(FunctionDecl *FD, ASTContext &context,
  1364. LPCSTR tableName, LPCSTR lowering,
  1365. const HLSL_INTRINSIC *pIntrinsic) {
  1366. unsigned opcode = (unsigned)pIntrinsic->Op;
  1367. if (HasUnsignedOpcode(opcode) && IsBuiltinTable(tableName)) {
  1368. QualType Ty = FD->getReturnType();
  1369. IntrinsicOp intrinOp = static_cast<IntrinsicOp>(pIntrinsic->Op);
  1370. if (pIntrinsic->iOverloadParamIndex != -1) {
  1371. const FunctionProtoType *FT =
  1372. FD->getFunctionType()->getAs<FunctionProtoType>();
  1373. Ty = FT->getParamType(pIntrinsic->iOverloadParamIndex);
  1374. }
  1375. // TODO: refine the code for getting element type
  1376. if (const ExtVectorType *VecTy = hlsl::ConvertHLSLVecMatTypeToExtVectorType(context, Ty)) {
  1377. Ty = VecTy->getElementType();
  1378. }
  1379. if (Ty->isUnsignedIntegerType()) {
  1380. opcode = hlsl::GetUnsignedOpcode(opcode);
  1381. }
  1382. }
  1383. FD->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, tableName, lowering, opcode));
  1384. if (pIntrinsic->bReadNone)
  1385. FD->addAttr(ConstAttr::CreateImplicit(context));
  1386. if (pIntrinsic->bReadOnly)
  1387. FD->addAttr(PureAttr::CreateImplicit(context));
  1388. }
  1389. static
  1390. FunctionDecl *AddHLSLIntrinsicFunction(
  1391. ASTContext &context, _In_ NamespaceDecl *NS,
  1392. LPCSTR tableName, LPCSTR lowering,
  1393. _In_ const HLSL_INTRINSIC *pIntrinsic,
  1394. _In_count_(functionArgTypeCount) QualType *functionArgQualTypes,
  1395. _In_range_(0, g_MaxIntrinsicParamCount - 1) size_t functionArgTypeCount) {
  1396. DXASSERT(functionArgTypeCount - 1 < g_MaxIntrinsicParamCount,
  1397. "otherwise g_MaxIntrinsicParamCount should be larger");
  1398. DeclContext *currentDeclContext = context.getTranslationUnitDecl();
  1399. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  1400. InitParamMods(pIntrinsic, paramMods);
  1401. // Change dest address into reference type for atomic.
  1402. if (IsBuiltinTable(tableName)) {
  1403. if (IsAtomicOperation(static_cast<IntrinsicOp>(pIntrinsic->Op))) {
  1404. DXASSERT(functionArgTypeCount > kAtomicDstOperandIdx,
  1405. "else operation was misrecognized");
  1406. functionArgQualTypes[kAtomicDstOperandIdx] =
  1407. context.getLValueReferenceType(functionArgQualTypes[kAtomicDstOperandIdx]);
  1408. }
  1409. }
  1410. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1411. // Change out/inout param to reference type.
  1412. if (paramMods[i-1].isAnyOut()) {
  1413. functionArgQualTypes[i] = context.getLValueReferenceType(functionArgQualTypes[i]);
  1414. }
  1415. }
  1416. IdentifierInfo &functionId = context.Idents.get(
  1417. StringRef(pIntrinsic->pArgs[0].pName), tok::TokenKind::identifier);
  1418. DeclarationName functionName(&functionId);
  1419. QualType returnQualType = functionArgQualTypes[0];
  1420. QualType functionType = context.getFunctionType(
  1421. functionArgQualTypes[0],
  1422. ArrayRef<QualType>(functionArgQualTypes + 1,
  1423. functionArgQualTypes + functionArgTypeCount),
  1424. clang::FunctionProtoType::ExtProtoInfo(), paramMods);
  1425. FunctionDecl *functionDecl = FunctionDecl::Create(
  1426. context, currentDeclContext, NoLoc,
  1427. DeclarationNameInfo(functionName, NoLoc), functionType, nullptr,
  1428. StorageClass::SC_Extern, InlineSpecifiedFalse, HasWrittenPrototypeTrue);
  1429. currentDeclContext->addDecl(functionDecl);
  1430. functionDecl->setLexicalDeclContext(currentDeclContext);
  1431. // put under hlsl namespace
  1432. functionDecl->setDeclContext(NS);
  1433. // Add intrinsic attribute
  1434. AddHLSLIntrinsicAttr(functionDecl, context, tableName, lowering, pIntrinsic);
  1435. ParmVarDecl *paramDecls[g_MaxIntrinsicParamCount];
  1436. for (size_t i = 1; i < functionArgTypeCount; i++) {
  1437. IdentifierInfo &parameterId = context.Idents.get(
  1438. StringRef(pIntrinsic->pArgs[i].pName), tok::TokenKind::identifier);
  1439. ParmVarDecl *paramDecl =
  1440. ParmVarDecl::Create(context, functionDecl, NoLoc, NoLoc, &parameterId,
  1441. functionArgQualTypes[i], nullptr,
  1442. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  1443. functionDecl->addDecl(paramDecl);
  1444. paramDecls[i - 1] = paramDecl;
  1445. }
  1446. functionDecl->setParams(
  1447. ArrayRef<ParmVarDecl *>(paramDecls, functionArgTypeCount - 1));
  1448. functionDecl->setImplicit(true);
  1449. return functionDecl;
  1450. }
  1451. /// <summary>
  1452. /// Checks whether the specified expression is a (possibly parenthesized) comma operator.
  1453. /// </summary>
  1454. static
  1455. bool IsExpressionBinaryComma(_In_ const Expr* expr)
  1456. {
  1457. DXASSERT_NOMSG(expr != nullptr);
  1458. expr = expr->IgnoreParens();
  1459. return
  1460. expr->getStmtClass() == Expr::StmtClass::BinaryOperatorClass &&
  1461. cast<BinaryOperator>(expr)->getOpcode() == BinaryOperatorKind::BO_Comma;
  1462. }
  1463. /// <summary>
  1464. /// Silences diagnostics for the initialization sequence, typically because they have already
  1465. /// been emitted.
  1466. /// </summary>
  1467. static
  1468. void SilenceSequenceDiagnostics(_Inout_ InitializationSequence* initSequence)
  1469. {
  1470. DXASSERT_NOMSG(initSequence != nullptr);
  1471. initSequence->SetFailed(InitializationSequence::FK_ListInitializationFailed);
  1472. }
  1473. class UsedIntrinsic
  1474. {
  1475. public:
  1476. static int compareArgs(const QualType& LHS, const QualType& RHS)
  1477. {
  1478. // The canonical representations are unique'd in an ASTContext, and so these
  1479. // should be stable.
  1480. return RHS.getTypePtr() - LHS.getTypePtr();
  1481. }
  1482. static int compareIntrinsic(const HLSL_INTRINSIC* LHS, const HLSL_INTRINSIC* RHS)
  1483. {
  1484. // The intrinsics are defined in a single static table, and so should be stable.
  1485. return RHS - LHS;
  1486. }
  1487. int compare(const UsedIntrinsic& other) const
  1488. {
  1489. // Check whether it's the same instance.
  1490. if (this == &other) return 0;
  1491. int result = compareIntrinsic(m_intrinsicSource, other.m_intrinsicSource);
  1492. if (result != 0) return result;
  1493. // At this point, it's the exact same intrinsic name.
  1494. // Compare the arguments for ordering then.
  1495. DXASSERT(m_argLength == other.m_argLength, "intrinsics aren't overloaded on argument count, so we should never create a key with different #s");
  1496. for (size_t i = 0; i < m_argLength; i++) {
  1497. int argComparison = compareArgs(m_args[i], other.m_args[i]);
  1498. if (argComparison != 0) return argComparison;
  1499. }
  1500. // Exactly the same.
  1501. return 0;
  1502. }
  1503. public:
  1504. UsedIntrinsic(const HLSL_INTRINSIC* intrinsicSource, _In_count_(argCount) QualType* args, size_t argCount)
  1505. : m_argLength(argCount), m_intrinsicSource(intrinsicSource), m_functionDecl(nullptr)
  1506. {
  1507. std::copy(args, args + argCount, m_args);
  1508. }
  1509. void setFunctionDecl(FunctionDecl* value) const
  1510. {
  1511. DXASSERT(value != nullptr, "no reason to clear this out");
  1512. DXASSERT(m_functionDecl == nullptr, "otherwise cached value is being invaldiated");
  1513. m_functionDecl = value;
  1514. }
  1515. FunctionDecl* getFunctionDecl() const { return m_functionDecl; }
  1516. bool operator==(const UsedIntrinsic& other) const
  1517. {
  1518. return compare(other) == 0;
  1519. }
  1520. bool operator<(const UsedIntrinsic& other) const
  1521. {
  1522. return compare(other) < 0;
  1523. }
  1524. private:
  1525. QualType m_args[g_MaxIntrinsicParamCount];
  1526. size_t m_argLength;
  1527. const HLSL_INTRINSIC* m_intrinsicSource;
  1528. mutable FunctionDecl* m_functionDecl;
  1529. };
  1530. template <typename T>
  1531. inline void AssignOpt(T value, _Out_opt_ T* ptr)
  1532. {
  1533. if (ptr != nullptr)
  1534. {
  1535. *ptr = value;
  1536. }
  1537. }
  1538. static bool CombineBasicTypes(
  1539. ArBasicKind LeftKind,
  1540. ArBasicKind RightKind,
  1541. _Out_ ArBasicKind* pOutKind,
  1542. _Out_opt_ CastKind* leftCastKind = nullptr,
  1543. _Out_opt_ CastKind* rightCastKind = nullptr)
  1544. {
  1545. AssignOpt(CastKind::CK_NoOp, leftCastKind);
  1546. AssignOpt(CastKind::CK_NoOp, rightCastKind);
  1547. if ((LeftKind < 0 || LeftKind >= AR_BASIC_COUNT) ||
  1548. (RightKind < 0 || RightKind >= AR_BASIC_COUNT)) {
  1549. return false;
  1550. }
  1551. if (LeftKind == RightKind) {
  1552. *pOutKind = LeftKind;
  1553. return true;
  1554. }
  1555. UINT uLeftProps = GetBasicKindProps(LeftKind);
  1556. UINT uRightProps = GetBasicKindProps(RightKind);
  1557. UINT uBits = GET_BPROP_BITS(uLeftProps) > GET_BPROP_BITS(uRightProps) ?
  1558. GET_BPROP_BITS(uLeftProps) : GET_BPROP_BITS(uRightProps);
  1559. UINT uBothFlags = uLeftProps & uRightProps;
  1560. UINT uEitherFlags = uLeftProps | uRightProps;
  1561. if ((BPROP_BOOLEAN & uBothFlags) != 0)
  1562. {
  1563. *pOutKind = AR_BASIC_BOOL;
  1564. return true;
  1565. }
  1566. if ((BPROP_LITERAL & uBothFlags) != 0)
  1567. {
  1568. if ((BPROP_INTEGER & uBothFlags) != 0)
  1569. {
  1570. *pOutKind = AR_BASIC_LITERAL_INT;
  1571. }
  1572. else
  1573. {
  1574. *pOutKind = AR_BASIC_LITERAL_FLOAT;
  1575. }
  1576. return true;
  1577. }
  1578. if ((BPROP_UNSIGNED & uBothFlags) != 0)
  1579. {
  1580. switch (uBits)
  1581. {
  1582. case BPROP_BITS8: *pOutKind = AR_BASIC_UINT8; break;
  1583. case BPROP_BITS16: (uEitherFlags & BPROP_MIN_PRECISION) ?
  1584. *pOutKind = AR_BASIC_MIN16UINT : *pOutKind = AR_BASIC_UINT16; break;
  1585. case BPROP_BITS32: *pOutKind = AR_BASIC_UINT32; break;
  1586. case BPROP_BITS64: *pOutKind = AR_BASIC_UINT64; break;
  1587. default: DXASSERT_NOMSG(false); break;
  1588. }
  1589. AssignOpt(CK_IntegralCast, leftCastKind);
  1590. AssignOpt(CK_IntegralCast, rightCastKind);
  1591. return true;
  1592. }
  1593. if ((BPROP_INTEGER & uBothFlags) != 0)
  1594. {
  1595. if ((BPROP_UNSIGNED & uEitherFlags) != 0)
  1596. {
  1597. switch (uBits)
  1598. {
  1599. case BPROP_BITS8: *pOutKind = AR_BASIC_UINT8; break;
  1600. case BPROP_BITS16: (uEitherFlags & BPROP_MIN_PRECISION) ?
  1601. *pOutKind = AR_BASIC_MIN16UINT : *pOutKind = AR_BASIC_UINT16; break;
  1602. case BPROP_BITS32: *pOutKind = AR_BASIC_UINT32; break;
  1603. case BPROP_BITS64: *pOutKind = AR_BASIC_UINT64; break;
  1604. default: DXASSERT_NOMSG(false); break;
  1605. }
  1606. }
  1607. else
  1608. {
  1609. switch (uBits)
  1610. {
  1611. case BPROP_BITS0: *pOutKind = AR_BASIC_LITERAL_INT; break;
  1612. case BPROP_BITS8: *pOutKind = AR_BASIC_INT8; break;
  1613. case BPROP_BITS12: *pOutKind = AR_BASIC_MIN12INT; break;
  1614. case BPROP_BITS16: (uEitherFlags & BPROP_MIN_PRECISION) ?
  1615. *pOutKind = AR_BASIC_MIN16INT : *pOutKind = AR_BASIC_INT16; break;
  1616. case BPROP_BITS32: *pOutKind = AR_BASIC_INT32; break;
  1617. case BPROP_BITS64: *pOutKind = AR_BASIC_INT64; break;
  1618. default: DXASSERT_NOMSG(false); break;
  1619. }
  1620. }
  1621. AssignOpt(CK_IntegralCast, leftCastKind);
  1622. AssignOpt(CK_IntegralCast, rightCastKind);
  1623. return true;
  1624. }
  1625. // At least one side is floating-point. Assume both are and fix later
  1626. // in this function.
  1627. DXASSERT_NOMSG((BPROP_FLOATING & uEitherFlags) != 0);
  1628. AssignOpt(CK_FloatingCast, leftCastKind);
  1629. AssignOpt(CK_FloatingCast, rightCastKind);
  1630. if ((BPROP_FLOATING & uBothFlags) == 0)
  1631. {
  1632. // One side is floating-point and one isn't,
  1633. // convert to the floating-point type.
  1634. if ((BPROP_FLOATING & uLeftProps) != 0)
  1635. {
  1636. uBits = GET_BPROP_BITS(uLeftProps);
  1637. AssignOpt(CK_IntegralToFloating, rightCastKind);
  1638. }
  1639. else
  1640. {
  1641. DXASSERT_NOMSG((BPROP_FLOATING & uRightProps) != 0);
  1642. uBits = GET_BPROP_BITS(uRightProps);
  1643. AssignOpt(CK_IntegralToFloating, leftCastKind);
  1644. }
  1645. if (uBits == 0)
  1646. {
  1647. // We have a literal plus a non-literal so drop
  1648. // any literalness.
  1649. uBits = BPROP_BITS32;
  1650. }
  1651. }
  1652. switch (uBits)
  1653. {
  1654. case BPROP_BITS10:
  1655. *pOutKind = AR_BASIC_MIN10FLOAT;
  1656. break;
  1657. case BPROP_BITS16:
  1658. if ((uEitherFlags & BPROP_MIN_PRECISION) != 0)
  1659. {
  1660. *pOutKind = AR_BASIC_MIN16FLOAT;
  1661. }
  1662. else
  1663. {
  1664. *pOutKind = AR_BASIC_FLOAT16;
  1665. }
  1666. break;
  1667. case BPROP_BITS32:
  1668. if ((uEitherFlags & BPROP_LITERAL) != 0 &&
  1669. (uEitherFlags & BPROP_PARTIAL_PRECISION) != 0)
  1670. {
  1671. *pOutKind = AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  1672. }
  1673. else if ((uBothFlags & BPROP_PARTIAL_PRECISION) != 0)
  1674. {
  1675. *pOutKind = AR_BASIC_FLOAT32_PARTIAL_PRECISION;
  1676. }
  1677. else
  1678. {
  1679. *pOutKind = AR_BASIC_FLOAT32;
  1680. }
  1681. break;
  1682. case BPROP_BITS64:
  1683. *pOutKind = AR_BASIC_FLOAT64;
  1684. break;
  1685. default:
  1686. DXASSERT(false, "unexpected bit count");
  1687. *pOutKind = AR_BASIC_FLOAT32;
  1688. break;
  1689. }
  1690. return true;
  1691. }
  1692. class UsedIntrinsicStore : public std::set<UsedIntrinsic>
  1693. {
  1694. };
  1695. static
  1696. void GetIntrinsicMethods(ArBasicKind kind, _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics, _Out_ size_t* intrinsicCount)
  1697. {
  1698. DXASSERT_NOMSG(intrinsics != nullptr);
  1699. DXASSERT_NOMSG(intrinsicCount != nullptr);
  1700. switch (kind)
  1701. {
  1702. case AR_OBJECT_TRIANGLESTREAM:
  1703. case AR_OBJECT_POINTSTREAM:
  1704. case AR_OBJECT_LINESTREAM:
  1705. *intrinsics = g_StreamMethods;
  1706. *intrinsicCount = _countof(g_StreamMethods);
  1707. break;
  1708. case AR_OBJECT_TEXTURE1D:
  1709. *intrinsics = g_Texture1DMethods;
  1710. *intrinsicCount = _countof(g_Texture1DMethods);
  1711. break;
  1712. case AR_OBJECT_TEXTURE1D_ARRAY:
  1713. *intrinsics = g_Texture1DArrayMethods;
  1714. *intrinsicCount = _countof(g_Texture1DArrayMethods);
  1715. break;
  1716. case AR_OBJECT_TEXTURE2D:
  1717. *intrinsics = g_Texture2DMethods;
  1718. *intrinsicCount = _countof(g_Texture2DMethods);
  1719. break;
  1720. case AR_OBJECT_TEXTURE2DMS:
  1721. *intrinsics = g_Texture2DMSMethods;
  1722. *intrinsicCount = _countof(g_Texture2DMSMethods);
  1723. break;
  1724. case AR_OBJECT_TEXTURE2D_ARRAY:
  1725. *intrinsics = g_Texture2DArrayMethods;
  1726. *intrinsicCount = _countof(g_Texture2DArrayMethods);
  1727. break;
  1728. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  1729. *intrinsics = g_Texture2DArrayMSMethods;
  1730. *intrinsicCount = _countof(g_Texture2DArrayMSMethods);
  1731. break;
  1732. case AR_OBJECT_TEXTURE3D:
  1733. *intrinsics = g_Texture3DMethods;
  1734. *intrinsicCount = _countof(g_Texture3DMethods);
  1735. break;
  1736. case AR_OBJECT_TEXTURECUBE:
  1737. *intrinsics = g_TextureCUBEMethods;
  1738. *intrinsicCount = _countof(g_TextureCUBEMethods);
  1739. break;
  1740. case AR_OBJECT_TEXTURECUBE_ARRAY:
  1741. *intrinsics = g_TextureCUBEArrayMethods;
  1742. *intrinsicCount = _countof(g_TextureCUBEArrayMethods);
  1743. break;
  1744. case AR_OBJECT_BUFFER:
  1745. *intrinsics = g_BufferMethods;
  1746. *intrinsicCount = _countof(g_BufferMethods);
  1747. break;
  1748. case AR_OBJECT_RWTEXTURE1D:
  1749. case AR_OBJECT_ROVTEXTURE1D:
  1750. *intrinsics = g_RWTexture1DMethods;
  1751. *intrinsicCount = _countof(g_RWTexture1DMethods);
  1752. break;
  1753. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  1754. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  1755. *intrinsics = g_RWTexture1DArrayMethods;
  1756. *intrinsicCount = _countof(g_RWTexture1DArrayMethods);
  1757. break;
  1758. case AR_OBJECT_RWTEXTURE2D:
  1759. case AR_OBJECT_ROVTEXTURE2D:
  1760. *intrinsics = g_RWTexture2DMethods;
  1761. *intrinsicCount = _countof(g_RWTexture2DMethods);
  1762. break;
  1763. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  1764. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  1765. *intrinsics = g_RWTexture2DArrayMethods;
  1766. *intrinsicCount = _countof(g_RWTexture2DArrayMethods);
  1767. break;
  1768. case AR_OBJECT_RWTEXTURE3D:
  1769. case AR_OBJECT_ROVTEXTURE3D:
  1770. *intrinsics = g_RWTexture3DMethods;
  1771. *intrinsicCount = _countof(g_RWTexture3DMethods);
  1772. break;
  1773. case AR_OBJECT_RWBUFFER:
  1774. case AR_OBJECT_ROVBUFFER:
  1775. *intrinsics = g_RWBufferMethods;
  1776. *intrinsicCount = _countof(g_RWBufferMethods);
  1777. break;
  1778. case AR_OBJECT_BYTEADDRESS_BUFFER:
  1779. *intrinsics = g_ByteAddressBufferMethods;
  1780. *intrinsicCount = _countof(g_ByteAddressBufferMethods);
  1781. break;
  1782. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  1783. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  1784. *intrinsics = g_RWByteAddressBufferMethods;
  1785. *intrinsicCount = _countof(g_RWByteAddressBufferMethods);
  1786. break;
  1787. case AR_OBJECT_STRUCTURED_BUFFER:
  1788. *intrinsics = g_StructuredBufferMethods;
  1789. *intrinsicCount = _countof(g_StructuredBufferMethods);
  1790. break;
  1791. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  1792. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  1793. *intrinsics = g_RWStructuredBufferMethods;
  1794. *intrinsicCount = _countof(g_RWStructuredBufferMethods);
  1795. break;
  1796. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  1797. *intrinsics = g_AppendStructuredBufferMethods;
  1798. *intrinsicCount = _countof(g_AppendStructuredBufferMethods);
  1799. break;
  1800. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  1801. *intrinsics = g_ConsumeStructuredBufferMethods;
  1802. *intrinsicCount = _countof(g_ConsumeStructuredBufferMethods);
  1803. break;
  1804. // SPIRV change starts
  1805. #ifdef ENABLE_SPIRV_CODEGEN
  1806. case AR_OBJECT_VK_SUBPASS_INPUT:
  1807. *intrinsics = g_VkSubpassInputMethods;
  1808. *intrinsicCount = _countof(g_VkSubpassInputMethods);
  1809. break;
  1810. case AR_OBJECT_VK_SUBPASS_INPUT_MS:
  1811. *intrinsics = g_VkSubpassInputMSMethods;
  1812. *intrinsicCount = _countof(g_VkSubpassInputMSMethods);
  1813. break;
  1814. #endif // ENABLE_SPIRV_CODEGEN
  1815. // SPIRV change ends
  1816. default:
  1817. *intrinsics = nullptr;
  1818. *intrinsicCount = 0;
  1819. break;
  1820. }
  1821. }
  1822. static
  1823. bool IsRowOrColumnVariable(size_t value)
  1824. {
  1825. return IA_SPECIAL_BASE <= value && value <= (IA_SPECIAL_BASE + IA_SPECIAL_SLOTS - 1);
  1826. }
  1827. static
  1828. bool DoesComponentTypeAcceptMultipleTypes(LEGAL_INTRINSIC_COMPTYPES value)
  1829. {
  1830. return
  1831. value == LICOMPTYPE_ANY_INT || // signed or unsigned ints
  1832. value == LICOMPTYPE_ANY_INT32 || // signed or unsigned ints
  1833. value == LICOMPTYPE_ANY_FLOAT || // float or double
  1834. value == LICOMPTYPE_FLOAT_LIKE || // float or min16
  1835. value == LICOMPTYPE_FLOAT_DOUBLE || // float or double
  1836. value == LICOMPTYPE_NUMERIC || // all sorts of numbers
  1837. value == LICOMPTYPE_NUMERIC32 || // all sorts of numbers
  1838. value == LICOMPTYPE_NUMERIC32_ONLY || // all sorts of numbers
  1839. value == LICOMPTYPE_ANY; // any time
  1840. }
  1841. static
  1842. bool DoesComponentTypeAcceptMultipleTypes(BYTE value)
  1843. {
  1844. return DoesComponentTypeAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_COMPTYPES>(value));
  1845. }
  1846. static
  1847. bool DoesLegalTemplateAcceptMultipleTypes(LEGAL_INTRINSIC_TEMPLATES value)
  1848. {
  1849. // Note that LITEMPLATE_OBJECT can accept different types, but it
  1850. // specifies a single 'layout'. In practice, this information is used
  1851. // together with a component type that specifies a single object.
  1852. return value == LITEMPLATE_ANY; // Any layout
  1853. }
  1854. static
  1855. bool DoesLegalTemplateAcceptMultipleTypes(BYTE value)
  1856. {
  1857. return DoesLegalTemplateAcceptMultipleTypes(static_cast<LEGAL_INTRINSIC_TEMPLATES>(value));
  1858. }
  1859. static
  1860. bool DoesIntrinsicRequireTemplate(const HLSL_INTRINSIC* intrinsic)
  1861. {
  1862. const HLSL_INTRINSIC_ARGUMENT* argument = intrinsic->pArgs;
  1863. for (size_t i = 0; i < intrinsic->uNumArgs; i++)
  1864. {
  1865. // The intrinsic will require a template for any of these reasons:
  1866. // - A type template (layout) or component needs to match something else.
  1867. // - A parameter can take multiple types.
  1868. // - Row or columns numbers may vary.
  1869. if (
  1870. argument->uTemplateId != i ||
  1871. DoesLegalTemplateAcceptMultipleTypes(argument->uLegalTemplates) ||
  1872. DoesComponentTypeAcceptMultipleTypes(argument->uLegalComponentTypes) ||
  1873. IsRowOrColumnVariable(argument->uCols) ||
  1874. IsRowOrColumnVariable(argument->uRows))
  1875. {
  1876. return true;
  1877. }
  1878. argument++;
  1879. }
  1880. return false;
  1881. }
  1882. static
  1883. bool TemplateHasDefaultType(ArBasicKind kind)
  1884. {
  1885. switch (kind) {
  1886. case AR_OBJECT_BUFFER:
  1887. case AR_OBJECT_TEXTURE1D:
  1888. case AR_OBJECT_TEXTURE2D:
  1889. case AR_OBJECT_TEXTURE3D:
  1890. case AR_OBJECT_TEXTURE1D_ARRAY:
  1891. case AR_OBJECT_TEXTURE2D_ARRAY:
  1892. case AR_OBJECT_TEXTURECUBE:
  1893. case AR_OBJECT_TEXTURECUBE_ARRAY:
  1894. // SPIRV change starts
  1895. #ifdef ENABLE_SPIRV_CODEGEN
  1896. case AR_OBJECT_VK_SUBPASS_INPUT:
  1897. case AR_OBJECT_VK_SUBPASS_INPUT_MS:
  1898. #endif // ENABLE_SPIRV_CODEGEN
  1899. // SPIRV change ends
  1900. return true;
  1901. }
  1902. return false;
  1903. }
  1904. /// <summary>
  1905. /// Use this class to iterate over intrinsic definitions that come from an external source.
  1906. /// </summary>
  1907. class IntrinsicTableDefIter
  1908. {
  1909. private:
  1910. StringRef _typeName;
  1911. StringRef _functionName;
  1912. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& _tables;
  1913. const HLSL_INTRINSIC* _tableIntrinsic;
  1914. UINT64 _tableLookupCookie;
  1915. unsigned _tableIndex;
  1916. unsigned _argCount;
  1917. bool _firstChecked;
  1918. IntrinsicTableDefIter(
  1919. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  1920. StringRef typeName,
  1921. StringRef functionName,
  1922. unsigned argCount) :
  1923. _typeName(typeName), _functionName(functionName), _tables(tables),
  1924. _tableIntrinsic(nullptr), _tableLookupCookie(0), _tableIndex(0),
  1925. _argCount(argCount), _firstChecked(false)
  1926. {
  1927. }
  1928. void CheckForIntrinsic() {
  1929. if (_tableIndex >= _tables.size()) {
  1930. return;
  1931. }
  1932. _firstChecked = true;
  1933. // TODO: review this - this will allocate at least once per string
  1934. CA2WEX<> typeName(_typeName.str().c_str(), CP_UTF8);
  1935. CA2WEX<> functionName(_functionName.str().c_str(), CP_UTF8);
  1936. if (FAILED(_tables[_tableIndex]->LookupIntrinsic(
  1937. typeName, functionName, &_tableIntrinsic, &_tableLookupCookie))) {
  1938. _tableLookupCookie = 0;
  1939. _tableIntrinsic = nullptr;
  1940. }
  1941. }
  1942. void MoveToNext() {
  1943. for (;;) {
  1944. // If we don't have an intrinsic, try the following table.
  1945. if (_firstChecked && _tableIntrinsic == nullptr) {
  1946. _tableIndex++;
  1947. }
  1948. CheckForIntrinsic();
  1949. if (_tableIndex == _tables.size() ||
  1950. (_tableIntrinsic != nullptr &&
  1951. _tableIntrinsic->uNumArgs ==
  1952. (_argCount + 1))) // uNumArgs includes return
  1953. break;
  1954. }
  1955. }
  1956. public:
  1957. static IntrinsicTableDefIter CreateStart(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables,
  1958. StringRef typeName,
  1959. StringRef functionName,
  1960. unsigned argCount)
  1961. {
  1962. IntrinsicTableDefIter result(tables, typeName, functionName, argCount);
  1963. return result;
  1964. }
  1965. static IntrinsicTableDefIter CreateEnd(llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2>& tables)
  1966. {
  1967. IntrinsicTableDefIter result(tables, StringRef(), StringRef(), 0);
  1968. result._tableIndex = tables.size();
  1969. return result;
  1970. }
  1971. bool operator!=(const IntrinsicTableDefIter& other)
  1972. {
  1973. if (!_firstChecked) {
  1974. MoveToNext();
  1975. }
  1976. return _tableIndex != other._tableIndex; // More things could be compared but we only match end.
  1977. }
  1978. const HLSL_INTRINSIC* operator*()
  1979. {
  1980. DXASSERT(_firstChecked, "otherwise deref without comparing to end");
  1981. return _tableIntrinsic;
  1982. }
  1983. LPCSTR GetTableName()
  1984. {
  1985. LPCSTR tableName = nullptr;
  1986. if (FAILED(_tables[_tableIndex]->GetTableName(&tableName))) {
  1987. return nullptr;
  1988. }
  1989. return tableName;
  1990. }
  1991. LPCSTR GetLoweringStrategy()
  1992. {
  1993. LPCSTR lowering = nullptr;
  1994. if (FAILED(_tables[_tableIndex]->GetLoweringStrategy(_tableIntrinsic->Op, &lowering))) {
  1995. return nullptr;
  1996. }
  1997. return lowering;
  1998. }
  1999. IntrinsicTableDefIter& operator++()
  2000. {
  2001. MoveToNext();
  2002. return *this;
  2003. }
  2004. };
  2005. /// <summary>
  2006. /// Use this class to iterate over intrinsic definitions that have the same name and parameter count.
  2007. /// </summary>
  2008. class IntrinsicDefIter
  2009. {
  2010. const HLSL_INTRINSIC* _current;
  2011. const HLSL_INTRINSIC* _end;
  2012. IntrinsicTableDefIter _tableIter;
  2013. IntrinsicDefIter(const HLSL_INTRINSIC* value, const HLSL_INTRINSIC* end, IntrinsicTableDefIter tableIter) :
  2014. _current(value), _end(end), _tableIter(tableIter)
  2015. { }
  2016. public:
  2017. static IntrinsicDefIter CreateStart(const HLSL_INTRINSIC* table, size_t count, const HLSL_INTRINSIC* start, IntrinsicTableDefIter tableIter)
  2018. {
  2019. return IntrinsicDefIter(start, table + count, tableIter);
  2020. }
  2021. static IntrinsicDefIter CreateEnd(const HLSL_INTRINSIC* table, size_t count, IntrinsicTableDefIter tableIter)
  2022. {
  2023. return IntrinsicDefIter(table + count, table + count, tableIter);
  2024. }
  2025. bool operator!=(const IntrinsicDefIter& other)
  2026. {
  2027. return _current != other._current || _tableIter.operator!=(other._tableIter);
  2028. }
  2029. const HLSL_INTRINSIC* operator*()
  2030. {
  2031. return (_current != _end) ? _current : *_tableIter;
  2032. }
  2033. LPCSTR GetTableName()
  2034. {
  2035. return (_current != _end) ? kBuiltinIntrinsicTableName : _tableIter.GetTableName();
  2036. }
  2037. LPCSTR GetLoweringStrategy()
  2038. {
  2039. return (_current != _end) ? "" : _tableIter.GetLoweringStrategy();
  2040. }
  2041. IntrinsicDefIter& operator++()
  2042. {
  2043. if (_current != _end) {
  2044. const HLSL_INTRINSIC* next = _current + 1;
  2045. if (next != _end && _current->uNumArgs == next->uNumArgs && 0 == strcmp(_current->pArgs[0].pName, next->pArgs[0].pName)) {
  2046. _current = next;
  2047. }
  2048. else {
  2049. _current = _end;
  2050. }
  2051. } else {
  2052. ++_tableIter;
  2053. }
  2054. return *this;
  2055. }
  2056. };
  2057. static void AddHLSLSubscriptAttr(Decl *D, ASTContext &context, HLSubscriptOpcode opcode) {
  2058. StringRef group = GetHLOpcodeGroupName(HLOpcodeGroup::HLSubscript);
  2059. D->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, group, "", static_cast<unsigned>(opcode)));
  2060. }
  2061. //
  2062. // This is similar to clang/Analysis/CallGraph, but the following differences
  2063. // motivate this:
  2064. //
  2065. // - track traversed vs. observed nodes explicitly
  2066. // - fully visit all reachable functions
  2067. // - merge graph visiting with checking for recursion
  2068. // - track global variables and types used (NYI)
  2069. //
  2070. namespace hlsl {
  2071. struct CallNode {
  2072. FunctionDecl *CallerFn;
  2073. ::llvm::SmallPtrSet<FunctionDecl *, 4> CalleeFns;
  2074. };
  2075. typedef ::llvm::DenseMap<FunctionDecl*, CallNode> CallNodes;
  2076. typedef ::llvm::SmallPtrSet<Decl *, 8> FnCallStack;
  2077. typedef ::llvm::SmallPtrSet<FunctionDecl*, 128> FunctionSet;
  2078. typedef ::llvm::SmallVector<FunctionDecl*, 32> PendingFunctions;
  2079. // Returns the definition of a function.
  2080. // This serves two purposes - ignore built-in functions, and pick
  2081. // a single Decl * to be used in maps and sets.
  2082. static FunctionDecl *getFunctionWithBody(FunctionDecl *F) {
  2083. if (!F) return nullptr;
  2084. if (F->doesThisDeclarationHaveABody()) return F;
  2085. F = F->getFirstDecl();
  2086. for (auto &&Candidate : F->redecls()) {
  2087. if (Candidate->doesThisDeclarationHaveABody()) {
  2088. return Candidate;
  2089. }
  2090. }
  2091. return nullptr;
  2092. }
  2093. // AST visitor that maintains visited and pending collections, as well
  2094. // as recording nodes of caller/callees.
  2095. class FnReferenceVisitor : public RecursiveASTVisitor<FnReferenceVisitor> {
  2096. private:
  2097. CallNodes &m_callNodes;
  2098. FunctionSet &m_visitedFunctions;
  2099. PendingFunctions &m_pendingFunctions;
  2100. FunctionDecl *m_source;
  2101. CallNodes::iterator m_sourceIt;
  2102. public:
  2103. FnReferenceVisitor(FunctionSet &visitedFunctions,
  2104. PendingFunctions &pendingFunctions, CallNodes &callNodes)
  2105. : m_callNodes(callNodes),
  2106. m_visitedFunctions(visitedFunctions),
  2107. m_pendingFunctions(pendingFunctions) {}
  2108. void setSourceFn(FunctionDecl *F) {
  2109. F = getFunctionWithBody(F);
  2110. m_source = F;
  2111. m_sourceIt = m_callNodes.find(F);
  2112. }
  2113. bool VisitDeclRefExpr(DeclRefExpr *ref) {
  2114. ValueDecl *valueDecl = ref->getDecl();
  2115. FunctionDecl *fnDecl = dyn_cast_or_null<FunctionDecl>(valueDecl);
  2116. fnDecl = getFunctionWithBody(fnDecl);
  2117. if (fnDecl) {
  2118. if (m_sourceIt == m_callNodes.end()) {
  2119. auto result = m_callNodes.insert(
  2120. std::pair<FunctionDecl *, CallNode>(m_source, CallNode{ m_source }));
  2121. DXASSERT(result.second == true,
  2122. "else setSourceFn didn't assign m_sourceIt");
  2123. m_sourceIt = result.first;
  2124. }
  2125. m_sourceIt->second.CalleeFns.insert(fnDecl);
  2126. if (!m_visitedFunctions.count(fnDecl)) {
  2127. m_pendingFunctions.push_back(fnDecl);
  2128. }
  2129. }
  2130. return true;
  2131. }
  2132. };
  2133. // A call graph that can check for reachability and recursion efficiently.
  2134. class CallGraphWithRecurseGuard {
  2135. private:
  2136. CallNodes m_callNodes;
  2137. FunctionSet m_visitedFunctions;
  2138. FunctionDecl *CheckRecursion(FnCallStack &CallStack,
  2139. FunctionDecl *D) const {
  2140. if (CallStack.insert(D).second == false)
  2141. return D;
  2142. auto node = m_callNodes.find(D);
  2143. if (node != m_callNodes.end()) {
  2144. for (FunctionDecl *Callee : node->second.CalleeFns) {
  2145. FunctionDecl *pResult = CheckRecursion(CallStack, Callee);
  2146. if (pResult)
  2147. return pResult;
  2148. }
  2149. }
  2150. CallStack.erase(D);
  2151. return nullptr;
  2152. }
  2153. public:
  2154. void BuildForEntry(FunctionDecl *EntryFnDecl) {
  2155. DXASSERT_NOMSG(EntryFnDecl);
  2156. EntryFnDecl = getFunctionWithBody(EntryFnDecl);
  2157. PendingFunctions pendingFunctions;
  2158. FnReferenceVisitor visitor(m_visitedFunctions, pendingFunctions, m_callNodes);
  2159. pendingFunctions.push_back(EntryFnDecl);
  2160. while (!pendingFunctions.empty()) {
  2161. FunctionDecl *pendingDecl = pendingFunctions.pop_back_val();
  2162. if (m_visitedFunctions.insert(pendingDecl).second == true) {
  2163. visitor.setSourceFn(pendingDecl);
  2164. visitor.TraverseDecl(pendingDecl);
  2165. }
  2166. }
  2167. }
  2168. FunctionDecl *CheckRecursion(FunctionDecl *EntryFnDecl) const {
  2169. FnCallStack CallStack;
  2170. EntryFnDecl = getFunctionWithBody(EntryFnDecl);
  2171. return CheckRecursion(CallStack, EntryFnDecl);
  2172. }
  2173. void dump() const {
  2174. OutputDebugStringW(L"Call Nodes:\r\n");
  2175. for (auto &node : m_callNodes) {
  2176. OutputDebugFormatA("%s [%p]:\r\n", node.first->getName().str().c_str(), node.first);
  2177. for (auto callee : node.second.CalleeFns) {
  2178. OutputDebugFormatA(" %s [%p]\r\n", callee->getName().str().c_str(), callee);
  2179. }
  2180. }
  2181. }
  2182. };
  2183. }
  2184. /// <summary>Creates a Typedef in the specified ASTContext.</summary>
  2185. static
  2186. TypedefDecl *CreateGlobalTypedef(ASTContext* context, const char* ident, QualType baseType)
  2187. {
  2188. DXASSERT_NOMSG(context != nullptr);
  2189. DXASSERT_NOMSG(ident != nullptr);
  2190. DXASSERT_NOMSG(!baseType.isNull());
  2191. DeclContext* declContext = context->getTranslationUnitDecl();
  2192. TypeSourceInfo* typeSource = context->getTrivialTypeSourceInfo(baseType);
  2193. TypedefDecl* decl = TypedefDecl::Create(*context, declContext, NoLoc, NoLoc, &context->Idents.get(ident), typeSource);
  2194. declContext->addDecl(decl);
  2195. decl->setImplicit(true);
  2196. return decl;
  2197. }
  2198. class HLSLExternalSource : public ExternalSemaSource {
  2199. private:
  2200. // Inner types.
  2201. struct FindStructBasicTypeResult {
  2202. ArBasicKind Kind; // Kind of struct (eg, AR_OBJECT_TEXTURE2D)
  2203. unsigned int BasicKindsAsTypeIndex; // Index into g_ArBasicKinds*
  2204. FindStructBasicTypeResult(ArBasicKind kind,
  2205. unsigned int basicKindAsTypeIndex)
  2206. : Kind(kind), BasicKindsAsTypeIndex(basicKindAsTypeIndex) {}
  2207. bool Found() const { return Kind != AR_BASIC_UNKNOWN; }
  2208. };
  2209. // Declaration for matrix and vector templates.
  2210. ClassTemplateDecl* m_matrixTemplateDecl;
  2211. ClassTemplateDecl* m_vectorTemplateDecl;
  2212. // Namespace decl for hlsl intrin functions
  2213. NamespaceDecl* m_hlslNSDecl;
  2214. // Context being processed.
  2215. _Notnull_ ASTContext* m_context;
  2216. // Semantic analyzer being processed.
  2217. Sema* m_sema;
  2218. // Intrinsic tables available externally.
  2219. llvm::SmallVector<CComPtr<IDxcIntrinsicTable>, 2> m_intrinsicTables;
  2220. // Scalar types indexed by HLSLScalarType.
  2221. QualType m_scalarTypes[HLSLScalarTypeCount];
  2222. // Scalar types already built.
  2223. TypedefDecl* m_scalarTypeDefs[HLSLScalarTypeCount];
  2224. // 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.
  2225. QualType m_matrixTypes[HLSLScalarTypeCount][4][4];
  2226. // Matrix types already built, in shorthand form.
  2227. TypedefDecl* m_matrixShorthandTypes[HLSLScalarTypeCount][4][4];
  2228. // Vector types already built.
  2229. QualType m_vectorTypes[HLSLScalarTypeCount][4];
  2230. TypedefDecl* m_vectorTypedefs[HLSLScalarTypeCount][4];
  2231. // BuiltinType for each scalar type.
  2232. QualType m_baseTypes[HLSLScalarTypeCount];
  2233. // Built-in object types declarations, indexed by basic kind constant.
  2234. CXXRecordDecl* m_objectTypeDecls[_countof(g_ArBasicKindsAsTypes)];
  2235. // Map from object decl to the object index.
  2236. using ObjectTypeDeclMapType = std::array<std::pair<CXXRecordDecl*,unsigned>, _countof(g_ArBasicKindsAsTypes)+_countof(g_DeprecatedEffectObjectNames)>;
  2237. ObjectTypeDeclMapType m_objectTypeDeclsMap;
  2238. // Mask for object which not has methods created.
  2239. uint64_t m_objectTypeLazyInitMask;
  2240. UsedIntrinsicStore m_usedIntrinsics;
  2241. /// <summary>Add all base QualTypes for each hlsl scalar types.</summary>
  2242. void AddBaseTypes();
  2243. /// <summary>Adds all supporting declarations to reference scalar types.</summary>
  2244. void AddHLSLScalarTypes();
  2245. QualType GetTemplateObjectDataType(_In_ CXXRecordDecl* recordDecl)
  2246. {
  2247. DXASSERT_NOMSG(recordDecl != nullptr);
  2248. TemplateParameterList* parameterList = recordDecl->getTemplateParameterList(0);
  2249. NamedDecl* parameterDecl = parameterList->getParam(0);
  2250. DXASSERT(parameterDecl->getKind() == Decl::Kind::TemplateTypeParm, "otherwise recordDecl isn't one of the built-in objects with templates");
  2251. TemplateTypeParmDecl* parmDecl = dyn_cast<TemplateTypeParmDecl>(parameterDecl);
  2252. return QualType(parmDecl->getTypeForDecl(), 0);
  2253. }
  2254. // Determines whether the given intrinsic parameter type has a single QualType mapping.
  2255. QualType GetSingleQualTypeForMapping(const HLSL_INTRINSIC* intrinsic, int index)
  2256. {
  2257. int templateRef = intrinsic->pArgs[index].uTemplateId;
  2258. int componentRef = intrinsic->pArgs[index].uComponentTypeId;
  2259. const HLSL_INTRINSIC_ARGUMENT* templateArg = &intrinsic->pArgs[templateRef];
  2260. const HLSL_INTRINSIC_ARGUMENT* componentArg = &intrinsic->pArgs[componentRef];
  2261. const HLSL_INTRINSIC_ARGUMENT* matrixArg = &intrinsic->pArgs[index];
  2262. if (
  2263. templateRef >= 0 &&
  2264. templateArg->uTemplateId == templateRef &&
  2265. !DoesLegalTemplateAcceptMultipleTypes(templateArg->uLegalTemplates) &&
  2266. componentRef >= 0 &&
  2267. componentRef != INTRIN_COMPTYPE_FROM_TYPE_ELT0 &&
  2268. componentArg->uComponentTypeId == 0 &&
  2269. !DoesComponentTypeAcceptMultipleTypes(componentArg->uLegalComponentTypes) &&
  2270. !IsRowOrColumnVariable(matrixArg->uCols) &&
  2271. !IsRowOrColumnVariable(matrixArg->uRows))
  2272. {
  2273. ArTypeObjectKind templateKind = g_LegalIntrinsicTemplates[templateArg->uLegalTemplates][0];
  2274. ArBasicKind elementKind = g_LegalIntrinsicCompTypes[componentArg->uLegalComponentTypes][0];
  2275. return NewSimpleAggregateType(templateKind, elementKind, 0, matrixArg->uRows, matrixArg->uCols);
  2276. }
  2277. return QualType();
  2278. }
  2279. // Adds a new template parameter declaration to the specified array and returns the type for the parameter.
  2280. QualType AddTemplateParamToArray(_In_z_ const char* name, _Inout_ CXXRecordDecl* recordDecl, int templateDepth,
  2281. _Inout_count_c_(g_MaxIntrinsicParamCount + 1) NamedDecl* (&templateParamNamedDecls)[g_MaxIntrinsicParamCount + 1],
  2282. _Inout_ size_t* templateParamNamedDeclsCount)
  2283. {
  2284. DXASSERT_NOMSG(name != nullptr);
  2285. DXASSERT_NOMSG(recordDecl != nullptr);
  2286. DXASSERT_NOMSG(templateParamNamedDecls != nullptr);
  2287. DXASSERT_NOMSG(templateParamNamedDeclsCount != nullptr);
  2288. DXASSERT(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls), "otherwise constants should be updated");
  2289. _Analysis_assume_(*templateParamNamedDeclsCount < _countof(templateParamNamedDecls));
  2290. // Create the declaration for the template parameter.
  2291. IdentifierInfo* id = &m_context->Idents.get(StringRef(name));
  2292. TemplateTypeParmDecl* templateTypeParmDecl =
  2293. TemplateTypeParmDecl::Create(*m_context, recordDecl, NoLoc, NoLoc, templateDepth, *templateParamNamedDeclsCount,
  2294. id, TypenameTrue, ParameterPackFalse);
  2295. templateParamNamedDecls[*templateParamNamedDeclsCount] = templateTypeParmDecl;
  2296. // Create the type that the parameter represents.
  2297. QualType result = m_context->getTemplateTypeParmType(
  2298. templateDepth, *templateParamNamedDeclsCount, ParameterPackFalse, templateTypeParmDecl);
  2299. // Increment the declaration count for the array; as long as caller passes in both arguments,
  2300. // it need not concern itself with maintaining this value.
  2301. (*templateParamNamedDeclsCount)++;
  2302. return result;
  2303. }
  2304. // Adds a function specified by the given intrinsic to a record declaration.
  2305. // The template depth will be zero for records that don't have a "template<>" line
  2306. // even if conceptual; or one if it does have one.
  2307. void AddObjectIntrinsicTemplate(_Inout_ CXXRecordDecl* recordDecl, int templateDepth, _In_ const HLSL_INTRINSIC* intrinsic)
  2308. {
  2309. DXASSERT_NOMSG(recordDecl != nullptr);
  2310. DXASSERT_NOMSG(intrinsic != nullptr);
  2311. DXASSERT(intrinsic->uNumArgs > 0, "otherwise there isn't even an intrinsic name");
  2312. DXASSERT(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1), "otherwise g_MaxIntrinsicParamCount should be updated");
  2313. // uNumArgs includes the result type, g_MaxIntrinsicParamCount doesn't, thus the +1.
  2314. _Analysis_assume_(intrinsic->uNumArgs <= (g_MaxIntrinsicParamCount + 1));
  2315. // TODO: implement template parameter constraints for HLSL intrinsic methods in declarations
  2316. //
  2317. // Build template parameters, parameter types, and the return type.
  2318. // Parameter declarations are built after the function is created, to use it as their scope.
  2319. //
  2320. unsigned int numParams = intrinsic->uNumArgs - 1;
  2321. NamedDecl* templateParamNamedDecls[g_MaxIntrinsicParamCount + 1];
  2322. size_t templateParamNamedDeclsCount = 0;
  2323. QualType argsQTs[g_MaxIntrinsicParamCount];
  2324. StringRef argNames[g_MaxIntrinsicParamCount];
  2325. QualType functionResultQT;
  2326. DXASSERT(
  2327. _countof(templateParamNamedDecls) >= numParams + 1,
  2328. "need enough templates for all parameters and the return type, otherwise constants need updating");
  2329. // Handle the return type.
  2330. // functionResultQT = GetSingleQualTypeForMapping(intrinsic, 0);
  2331. // if (functionResultQT.isNull()) {
  2332. // Workaround for template parameter argument count mismatch.
  2333. // Create template parameter for return type always
  2334. // TODO: reenable the check and skip template argument.
  2335. functionResultQT = AddTemplateParamToArray(
  2336. "TResult", recordDecl, templateDepth, templateParamNamedDecls,
  2337. &templateParamNamedDeclsCount);
  2338. // }
  2339. SmallVector<hlsl::ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  2340. InitParamMods(intrinsic, paramMods);
  2341. // Consider adding more cases where return type can be handled a priori. Ultimately #260431 should do significantly better.
  2342. // Handle parameters.
  2343. for (unsigned int i = 1; i < intrinsic->uNumArgs; i++)
  2344. {
  2345. //
  2346. // GetSingleQualTypeForMapping can be used here to remove unnecessary template arguments.
  2347. //
  2348. // However this may produce template instantiations with equivalent template arguments
  2349. // for overloaded methods. It's possible to resolve some of these by generating specializations,
  2350. // but the current intrinsic table has rules that are hard to process in their current form
  2351. // to find all cases.
  2352. //
  2353. char name[g_MaxIntrinsicParamName + 2];
  2354. name[0] = 'T';
  2355. name[1] = '\0';
  2356. strcat_s(name, intrinsic->pArgs[i].pName);
  2357. argsQTs[i - 1] = AddTemplateParamToArray(name, recordDecl, templateDepth, templateParamNamedDecls, &templateParamNamedDeclsCount);
  2358. // Change out/inout param to reference type.
  2359. if (paramMods[i-1].isAnyOut())
  2360. argsQTs[i - 1] = m_context->getLValueReferenceType(argsQTs[i - 1]);
  2361. argNames[i - 1] = StringRef(intrinsic->pArgs[i].pName);
  2362. }
  2363. // Create the declaration.
  2364. IdentifierInfo* ii = &m_context->Idents.get(StringRef(intrinsic->pArgs[0].pName));
  2365. DeclarationName declarationName = DeclarationName(ii);
  2366. CXXMethodDecl* functionDecl = CreateObjectFunctionDeclarationWithParams(*m_context, recordDecl,
  2367. functionResultQT, ArrayRef<QualType>(argsQTs, numParams), ArrayRef<StringRef>(argNames, numParams),
  2368. declarationName, true);
  2369. functionDecl->setImplicit(true);
  2370. // If the function is a template function, create the declaration and cross-reference.
  2371. if (templateParamNamedDeclsCount > 0)
  2372. {
  2373. hlsl::CreateFunctionTemplateDecl(
  2374. *m_context, recordDecl, functionDecl, templateParamNamedDecls, templateParamNamedDeclsCount);
  2375. }
  2376. }
  2377. // Checks whether the two specified intrinsics generate equivalent templates.
  2378. // For example: foo (any_int) and foo (any_float) are only unambiguous in the context
  2379. // of HLSL intrinsic rules, and their difference can't be expressed with C++ templates.
  2380. bool AreIntrinsicTemplatesEquivalent(const HLSL_INTRINSIC* left, const HLSL_INTRINSIC* right)
  2381. {
  2382. if (left == right)
  2383. {
  2384. return true;
  2385. }
  2386. if (left == nullptr || right == nullptr)
  2387. {
  2388. return false;
  2389. }
  2390. return (left->uNumArgs == right->uNumArgs &&
  2391. 0 == strcmp(left->pArgs[0].pName, right->pArgs[0].pName));
  2392. }
  2393. // Adds all the intrinsic methods that correspond to the specified type.
  2394. void AddObjectMethods(ArBasicKind kind, _In_ CXXRecordDecl* recordDecl, int templateDepth)
  2395. {
  2396. DXASSERT_NOMSG(recordDecl != nullptr);
  2397. DXASSERT_NOMSG(templateDepth >= 0);
  2398. const HLSL_INTRINSIC* intrinsics;
  2399. const HLSL_INTRINSIC* prior = nullptr;
  2400. size_t intrinsicCount;
  2401. GetIntrinsicMethods(kind, &intrinsics, &intrinsicCount);
  2402. DXASSERT(
  2403. (intrinsics == nullptr) == (intrinsicCount == 0),
  2404. "intrinsic table pointer must match count (null for zero, something valid otherwise");
  2405. while (intrinsicCount--)
  2406. {
  2407. if (!AreIntrinsicTemplatesEquivalent(intrinsics, prior))
  2408. {
  2409. AddObjectIntrinsicTemplate(recordDecl, templateDepth, intrinsics);
  2410. prior = intrinsics;
  2411. }
  2412. intrinsics++;
  2413. }
  2414. }
  2415. void AddDoubleSubscriptSupport(
  2416. _In_ ClassTemplateDecl* typeDecl,
  2417. _In_ CXXRecordDecl* recordDecl,
  2418. _In_z_ const char* memberName, QualType elementType, TemplateTypeParmDecl* templateTypeParmDecl,
  2419. _In_z_ const char* type0Name,
  2420. _In_z_ const char* type1Name,
  2421. _In_z_ const char* indexer0Name, QualType indexer0Type,
  2422. _In_z_ const char* indexer1Name, QualType indexer1Type)
  2423. {
  2424. DXASSERT_NOMSG(typeDecl != nullptr);
  2425. DXASSERT_NOMSG(recordDecl != nullptr);
  2426. DXASSERT_NOMSG(memberName != nullptr);
  2427. DXASSERT_NOMSG(!elementType.isNull());
  2428. DXASSERT_NOMSG(templateTypeParmDecl != nullptr);
  2429. DXASSERT_NOMSG(type0Name != nullptr);
  2430. DXASSERT_NOMSG(type1Name != nullptr);
  2431. DXASSERT_NOMSG(indexer0Name != nullptr);
  2432. DXASSERT_NOMSG(!indexer0Type.isNull());
  2433. DXASSERT_NOMSG(indexer1Name != nullptr);
  2434. DXASSERT_NOMSG(!indexer1Type.isNull());
  2435. //
  2436. // Add inner types to the templates to represent the following C++ code inside the class.
  2437. // public:
  2438. // class sample_slice_type
  2439. // {
  2440. // public: TElement operator[](uint3 index);
  2441. // };
  2442. // class sample_type
  2443. // {
  2444. // public: sample_slice_type operator[](uint slice);
  2445. // };
  2446. // sample_type sample;
  2447. //
  2448. // Variable names reflect this structure, but this code will also produce the types
  2449. // for .mips access.
  2450. //
  2451. const bool MutableTrue = true;
  2452. DeclarationName subscriptName = m_context->DeclarationNames.getCXXOperatorName(OO_Subscript);
  2453. CXXRecordDecl* sampleSliceTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2454. &m_context->Idents.get(StringRef(type1Name)));
  2455. sampleSliceTypeDecl->setAccess(AS_public);
  2456. sampleSliceTypeDecl->setImplicit();
  2457. recordDecl->addDecl(sampleSliceTypeDecl);
  2458. sampleSliceTypeDecl->startDefinition();
  2459. const bool MutableFalse = false;
  2460. FieldDecl* sliceHandleDecl = FieldDecl::Create(*m_context, sampleSliceTypeDecl, NoLoc, NoLoc,
  2461. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2462. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2463. sliceHandleDecl->setAccess(AS_private);
  2464. sampleSliceTypeDecl->addDecl(sliceHandleDecl);
  2465. CXXMethodDecl* sampleSliceSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2466. sampleSliceTypeDecl, elementType,
  2467. ArrayRef<QualType>(indexer1Type), ArrayRef<StringRef>(StringRef(indexer1Name)), subscriptName, true);
  2468. hlsl::CreateFunctionTemplateDecl(*m_context, sampleSliceTypeDecl, sampleSliceSubscriptDecl,
  2469. reinterpret_cast<NamedDecl**>(&templateTypeParmDecl), 1);
  2470. sampleSliceTypeDecl->completeDefinition();
  2471. CXXRecordDecl* sampleTypeDecl = CXXRecordDecl::Create(*m_context, TTK_Class, recordDecl, NoLoc, NoLoc,
  2472. &m_context->Idents.get(StringRef(type0Name)));
  2473. sampleTypeDecl->setAccess(AS_public);
  2474. recordDecl->addDecl(sampleTypeDecl);
  2475. sampleTypeDecl->startDefinition();
  2476. sampleTypeDecl->setImplicit();
  2477. FieldDecl* sampleHandleDecl = FieldDecl::Create(*m_context, sampleTypeDecl, NoLoc, NoLoc,
  2478. &m_context->Idents.get(StringRef("handle")), indexer0Type,
  2479. m_context->CreateTypeSourceInfo(indexer0Type), nullptr, MutableFalse, ICIS_NoInit);
  2480. sampleHandleDecl->setAccess(AS_private);
  2481. sampleTypeDecl->addDecl(sampleHandleDecl);
  2482. QualType sampleSliceType = m_context->getRecordType(sampleSliceTypeDecl);
  2483. CXXMethodDecl* sampleSubscriptDecl = CreateObjectFunctionDeclarationWithParams(*m_context,
  2484. sampleTypeDecl, m_context->getRValueReferenceType(sampleSliceType), // TODO: choose LValueRef if writable.
  2485. ArrayRef<QualType>(indexer0Type), ArrayRef<StringRef>(StringRef(indexer0Name)), subscriptName, true);
  2486. sampleTypeDecl->completeDefinition();
  2487. // Add subscript attribute
  2488. AddHLSLSubscriptAttr(sampleSubscriptDecl, *m_context, HLSubscriptOpcode::DoubleSubscript);
  2489. QualType sampleTypeQT = m_context->getRecordType(sampleTypeDecl);
  2490. FieldDecl* sampleFieldDecl = FieldDecl::Create(*m_context, recordDecl, NoLoc, NoLoc,
  2491. &m_context->Idents.get(StringRef(memberName)), sampleTypeQT,
  2492. m_context->CreateTypeSourceInfo(sampleTypeQT), nullptr, MutableTrue, ICIS_NoInit);
  2493. sampleFieldDecl->setAccess(AS_public);
  2494. recordDecl->addDecl(sampleFieldDecl);
  2495. }
  2496. void AddObjectSubscripts(ArBasicKind kind, _In_ ClassTemplateDecl *typeDecl,
  2497. _In_ CXXRecordDecl *recordDecl,
  2498. SubscriptOperatorRecord op) {
  2499. DXASSERT_NOMSG(typeDecl != nullptr);
  2500. DXASSERT_NOMSG(recordDecl != nullptr);
  2501. DXASSERT_NOMSG(0 <= op.SubscriptCardinality &&
  2502. op.SubscriptCardinality <= 3);
  2503. DXASSERT(op.SubscriptCardinality > 0 ||
  2504. (op.HasMips == false && op.HasSample == false),
  2505. "objects that have .mips or .sample member also have a plain "
  2506. "subscript defined (otherwise static table is "
  2507. "likely incorrect, and this function won't know the cardinality "
  2508. "of the position parameter");
  2509. bool isReadWrite = GetBasicKindProps(kind) & BPROP_RWBUFFER;
  2510. DXASSERT(!isReadWrite || (op.HasMips == false && op.HasSample == false),
  2511. "read/write objects don't have .mips or .sample members");
  2512. // Return early if there is no work to be done.
  2513. if (op.SubscriptCardinality == 0) {
  2514. return;
  2515. }
  2516. const unsigned int templateDepth = 1;
  2517. // Add an operator[].
  2518. TemplateTypeParmDecl *templateTypeParmDecl = cast<TemplateTypeParmDecl>(
  2519. typeDecl->getTemplateParameters()->getParam(0));
  2520. QualType resultType = m_context->getTemplateTypeParmType(
  2521. templateDepth, 0, ParameterPackFalse, templateTypeParmDecl);
  2522. if (isReadWrite)
  2523. resultType = m_context->getLValueReferenceType(resultType, false);
  2524. else
  2525. resultType = m_context->getRValueReferenceType(resultType);
  2526. QualType indexType =
  2527. op.SubscriptCardinality == 1
  2528. ? m_context->UnsignedIntTy
  2529. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  2530. op.SubscriptCardinality);
  2531. CXXMethodDecl *functionDecl = CreateObjectFunctionDeclarationWithParams(
  2532. *m_context, recordDecl, resultType, ArrayRef<QualType>(indexType),
  2533. ArrayRef<StringRef>(StringRef("index")),
  2534. m_context->DeclarationNames.getCXXOperatorName(OO_Subscript), true);
  2535. hlsl::CreateFunctionTemplateDecl(
  2536. *m_context, recordDecl, functionDecl,
  2537. reinterpret_cast<NamedDecl **>(&templateTypeParmDecl), 1);
  2538. // Add a .mips member if necessary.
  2539. QualType uintType = m_context->UnsignedIntTy;
  2540. if (op.HasMips) {
  2541. AddDoubleSubscriptSupport(typeDecl, recordDecl, "mips", resultType,
  2542. templateTypeParmDecl, "mips_type",
  2543. "mips_slice_type", "mipSlice", uintType, "pos",
  2544. indexType);
  2545. }
  2546. // Add a .sample member if necessary.
  2547. if (op.HasSample) {
  2548. AddDoubleSubscriptSupport(typeDecl, recordDecl, "sample", resultType,
  2549. templateTypeParmDecl, "sample_type",
  2550. "sample_slice_type", "sampleSlice", uintType,
  2551. "pos", indexType);
  2552. // TODO: support operator[][](indexType, uint).
  2553. }
  2554. }
  2555. static bool ObjectTypeDeclMapTypeCmp(const std::pair<CXXRecordDecl*,unsigned> &a,
  2556. const std::pair<CXXRecordDecl*,unsigned> &b) {
  2557. return a.first < b.first;
  2558. };
  2559. int FindObjectBasicKindIndex(const CXXRecordDecl* recordDecl) {
  2560. auto begin = m_objectTypeDeclsMap.begin();
  2561. auto end = m_objectTypeDeclsMap.end();
  2562. auto val = std::make_pair(const_cast<CXXRecordDecl*>(recordDecl), 0);
  2563. auto low = std::lower_bound(begin, end, val, ObjectTypeDeclMapTypeCmp);
  2564. if (low == end)
  2565. return -1;
  2566. if (recordDecl == low->first)
  2567. return low->second;
  2568. else
  2569. return -1;
  2570. }
  2571. // Adds all built-in HLSL object types.
  2572. void AddObjectTypes()
  2573. {
  2574. DXASSERT(m_context != nullptr, "otherwise caller hasn't initialized context yet");
  2575. QualType float4Type = LookupVectorType(HLSLScalarType_float, 4);
  2576. TypeSourceInfo *float4TypeSourceInfo = m_context->getTrivialTypeSourceInfo(float4Type, NoLoc);
  2577. m_objectTypeLazyInitMask = 0;
  2578. unsigned effectKindIndex = 0;
  2579. for (int i = 0; i < _countof(g_ArBasicKindsAsTypes); i++)
  2580. {
  2581. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  2582. if (kind == AR_OBJECT_WAVE) { // wave objects are currently unused
  2583. continue;
  2584. }
  2585. if (kind == AR_OBJECT_LEGACY_EFFECT)
  2586. effectKindIndex = i;
  2587. DXASSERT(kind < _countof(g_ArBasicTypeNames), "g_ArBasicTypeNames has the wrong number of entries");
  2588. _Analysis_assume_(kind < _countof(g_ArBasicTypeNames));
  2589. const char* typeName = g_ArBasicTypeNames[kind];
  2590. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  2591. CXXRecordDecl* recordDecl = nullptr;
  2592. if (templateArgCount == 0)
  2593. {
  2594. AddRecordTypeWithHandle(*m_context, &recordDecl, typeName);
  2595. DXASSERT(recordDecl != nullptr, "AddRecordTypeWithHandle failed to return the object declaration");
  2596. recordDecl->setImplicit(true);
  2597. }
  2598. else
  2599. {
  2600. DXASSERT(templateArgCount == 1 || templateArgCount == 2, "otherwise a new case has been added");
  2601. ClassTemplateDecl* typeDecl = nullptr;
  2602. TypeSourceInfo* typeDefault = TemplateHasDefaultType(kind) ? float4TypeSourceInfo : nullptr;
  2603. AddTemplateTypeWithHandle(*m_context, &typeDecl, &recordDecl, typeName, templateArgCount, typeDefault);
  2604. DXASSERT(typeDecl != nullptr, "AddTemplateTypeWithHandle failed to return the object declaration");
  2605. typeDecl->setImplicit(true);
  2606. recordDecl->setImplicit(true);
  2607. }
  2608. m_objectTypeDecls[i] = recordDecl;
  2609. m_objectTypeDeclsMap[i] = std::make_pair(recordDecl, i);
  2610. m_objectTypeLazyInitMask |= ((uint64_t)1)<<i;
  2611. }
  2612. // Create an alias for SamplerState. 'sampler' is very commonly used.
  2613. {
  2614. DeclContext* currentDeclContext = m_context->getTranslationUnitDecl();
  2615. IdentifierInfo& samplerId = m_context->Idents.get(StringRef("sampler"), tok::TokenKind::identifier);
  2616. TypeSourceInfo* samplerTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_SAMPLER));
  2617. TypedefDecl* samplerDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &samplerId, samplerTypeSource);
  2618. currentDeclContext->addDecl(samplerDecl);
  2619. samplerDecl->setImplicit(true);
  2620. // Create decls for each deprecated effect object type:
  2621. unsigned effectObjBase = _countof(g_ArBasicKindsAsTypes);
  2622. // TypeSourceInfo* effectObjTypeSource = m_context->getTrivialTypeSourceInfo(GetBasicKindType(AR_OBJECT_LEGACY_EFFECT));
  2623. for (int i = 0; i < _countof(g_DeprecatedEffectObjectNames); i++) {
  2624. IdentifierInfo& idInfo = m_context->Idents.get(StringRef(g_DeprecatedEffectObjectNames[i]), tok::TokenKind::identifier);
  2625. //TypedefDecl* effectObjDecl = TypedefDecl::Create(*m_context, currentDeclContext, NoLoc, NoLoc, &idInfo, effectObjTypeSource);
  2626. CXXRecordDecl *effectObjDecl = CXXRecordDecl::Create(*m_context, TagTypeKind::TTK_Struct, currentDeclContext, NoLoc, NoLoc, &idInfo);
  2627. currentDeclContext->addDecl(effectObjDecl);
  2628. effectObjDecl->setImplicit(true);
  2629. m_objectTypeDeclsMap[i+effectObjBase] = std::make_pair(effectObjDecl, effectKindIndex);
  2630. }
  2631. }
  2632. // Make sure it's in order.
  2633. std::sort(m_objectTypeDeclsMap.begin(), m_objectTypeDeclsMap.end(), ObjectTypeDeclMapTypeCmp);
  2634. }
  2635. FunctionDecl* AddSubscriptSpecialization(
  2636. _In_ FunctionTemplateDecl* functionTemplate,
  2637. QualType objectElement,
  2638. const FindStructBasicTypeResult& findResult);
  2639. ImplicitCastExpr* CreateLValueToRValueCast(Expr* input) {
  2640. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  2641. }
  2642. ImplicitCastExpr* CreateFlatConversionCast(Expr* input) {
  2643. return ImplicitCastExpr::Create(*m_context, input->getType(), CK_LValueToRValue, input, nullptr, VK_RValue);
  2644. }
  2645. HRESULT CombineDimensions(QualType leftType, QualType rightType, QualType *resultType);
  2646. clang::TypedefDecl *LookupMatrixShorthandType(HLSLScalarType scalarType, UINT rowCount, UINT colCount) {
  2647. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  2648. rowCount >= 0 && rowCount <= 4 && colCount >= 0 &&
  2649. colCount <= 4);
  2650. TypedefDecl *qts =
  2651. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1];
  2652. if (qts == nullptr) {
  2653. QualType type = LookupMatrixType(scalarType, rowCount, colCount);
  2654. qts = CreateMatrixSpecializationShorthand(*m_context, type, scalarType,
  2655. rowCount, colCount);
  2656. m_matrixShorthandTypes[scalarType][rowCount - 1][colCount - 1] = qts;
  2657. }
  2658. return qts;
  2659. }
  2660. clang::TypedefDecl *LookupVectorShorthandType(HLSLScalarType scalarType, UINT colCount) {
  2661. DXASSERT_NOMSG(scalarType != HLSLScalarType::HLSLScalarType_unknown &&
  2662. colCount >= 0 && colCount <= 4);
  2663. TypedefDecl *qts = m_vectorTypedefs[scalarType][colCount - 1];
  2664. if (qts == nullptr) {
  2665. QualType type = LookupVectorType(scalarType, colCount);
  2666. qts = CreateVectorSpecializationShorthand(*m_context, type, scalarType,
  2667. colCount);
  2668. m_vectorTypedefs[scalarType][colCount - 1] = qts;
  2669. }
  2670. return qts;
  2671. }
  2672. public:
  2673. HLSLExternalSource() :
  2674. m_matrixTemplateDecl(nullptr),
  2675. m_vectorTemplateDecl(nullptr),
  2676. m_context(nullptr),
  2677. m_sema(nullptr)
  2678. {
  2679. memset(m_matrixTypes, 0, sizeof(m_matrixTypes));
  2680. memset(m_matrixShorthandTypes, 0, sizeof(m_matrixShorthandTypes));
  2681. memset(m_vectorTypes, 0, sizeof(m_vectorTypes));
  2682. memset(m_vectorTypedefs, 0, sizeof(m_vectorTypedefs));
  2683. memset(m_scalarTypes, 0, sizeof(m_scalarTypes));
  2684. memset(m_scalarTypeDefs, 0, sizeof(m_scalarTypeDefs));
  2685. memset(m_baseTypes, 0, sizeof(m_baseTypes));
  2686. }
  2687. ~HLSLExternalSource() { }
  2688. static HLSLExternalSource* FromSema(_In_ Sema* self)
  2689. {
  2690. DXASSERT_NOMSG(self != nullptr);
  2691. ExternalSemaSource* externalSource = self->getExternalSource();
  2692. DXASSERT(externalSource != nullptr, "otherwise caller shouldn't call HLSL-specific function");
  2693. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  2694. return hlsl;
  2695. }
  2696. void InitializeSema(Sema& S) override
  2697. {
  2698. m_sema = &S;
  2699. S.addExternalSource(this);
  2700. AddObjectTypes();
  2701. AddStdIsEqualImplementation(S.getASTContext(), S);
  2702. for (auto && intrinsic : m_intrinsicTables) {
  2703. AddIntrinsicTableMethods(intrinsic);
  2704. }
  2705. }
  2706. void ForgetSema() override
  2707. {
  2708. m_sema = nullptr;
  2709. }
  2710. Sema* getSema() {
  2711. return m_sema;
  2712. }
  2713. TypedefDecl* LookupScalarTypeDef(HLSLScalarType scalarType) {
  2714. // We shouldn't create Typedef for built in scalar types.
  2715. // For built in scalar types, this funciton may be called for
  2716. // TypoCorrection. In that case, we return a nullptr.
  2717. if (m_scalarTypes[scalarType].isNull()) {
  2718. m_scalarTypeDefs[scalarType] = CreateGlobalTypedef(m_context, HLSLScalarTypeNames[scalarType], m_baseTypes[scalarType]);
  2719. m_scalarTypes[scalarType] = m_context->getTypeDeclType(m_scalarTypeDefs[scalarType]);
  2720. }
  2721. return m_scalarTypeDefs[scalarType];
  2722. }
  2723. QualType LookupMatrixType(HLSLScalarType scalarType, unsigned int rowCount, unsigned int colCount)
  2724. {
  2725. QualType qt = m_matrixTypes[scalarType][rowCount - 1][colCount - 1];
  2726. if (qt.isNull()) {
  2727. // lazy initialization of scalar types
  2728. if (m_scalarTypes[scalarType].isNull()) {
  2729. LookupScalarTypeDef(scalarType);
  2730. }
  2731. qt = GetOrCreateMatrixSpecialization(*m_context, m_sema, m_matrixTemplateDecl, m_scalarTypes[scalarType], rowCount, colCount);
  2732. m_matrixTypes[scalarType][rowCount - 1][colCount - 1] = qt;
  2733. }
  2734. return qt;
  2735. }
  2736. QualType LookupVectorType(HLSLScalarType scalarType, unsigned int colCount)
  2737. {
  2738. QualType qt = m_vectorTypes[scalarType][colCount - 1];
  2739. if (qt.isNull()) {
  2740. if (m_scalarTypes[scalarType].isNull()) {
  2741. LookupScalarTypeDef(scalarType);
  2742. }
  2743. qt = GetOrCreateVectorSpecialization(*m_context, m_sema, m_vectorTemplateDecl, m_scalarTypes[scalarType], colCount);
  2744. m_vectorTypes[scalarType][colCount - 1] = qt;
  2745. }
  2746. return qt;
  2747. }
  2748. void WarnMinPrecision(HLSLScalarType type, SourceLocation loc) {
  2749. // TODO: enalbe this once we introduce precise master option
  2750. bool UseMinPrecision = m_context->getLangOpts().UseMinPrecision;
  2751. if (type == HLSLScalarType_int_min12) {
  2752. const char *PromotedType =
  2753. UseMinPrecision ? HLSLScalarTypeNames[HLSLScalarType_int_min16]
  2754. : HLSLScalarTypeNames[HLSLScalarType_int16];
  2755. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  2756. << HLSLScalarTypeNames[type] << PromotedType;
  2757. } else if (type == HLSLScalarType_float_min10) {
  2758. const char *PromotedType =
  2759. UseMinPrecision ? HLSLScalarTypeNames[HLSLScalarType_float_min16]
  2760. : HLSLScalarTypeNames[HLSLScalarType_float16];
  2761. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  2762. << HLSLScalarTypeNames[type] << PromotedType;
  2763. }
  2764. if (!UseMinPrecision) {
  2765. if (type == HLSLScalarType_float_min16) {
  2766. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  2767. << HLSLScalarTypeNames[type]
  2768. << HLSLScalarTypeNames[HLSLScalarType_float16];
  2769. } else if (type == HLSLScalarType_int_min16) {
  2770. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  2771. << HLSLScalarTypeNames[type]
  2772. << HLSLScalarTypeNames[HLSLScalarType_int16];
  2773. } else if (type == HLSLScalarType_uint_min16) {
  2774. m_sema->Diag(loc, diag::warn_hlsl_sema_minprecision_promotion)
  2775. << HLSLScalarTypeNames[type]
  2776. << HLSLScalarTypeNames[HLSLScalarType_uint16];
  2777. }
  2778. }
  2779. }
  2780. bool DiagnoseHLSLScalarType(HLSLScalarType type, SourceLocation Loc) {
  2781. if (getSema()->getLangOpts().HLSLVersion < 2018) {
  2782. switch (type) {
  2783. case HLSLScalarType_float16:
  2784. case HLSLScalarType_float32:
  2785. case HLSLScalarType_float64:
  2786. case HLSLScalarType_int16:
  2787. case HLSLScalarType_int32:
  2788. case HLSLScalarType_uint16:
  2789. case HLSLScalarType_uint32:
  2790. m_sema->Diag(Loc, diag::err_hlsl_unsupported_keyword_for_version)
  2791. << HLSLScalarTypeNames[type] << "2018";
  2792. return false;
  2793. default:
  2794. break;
  2795. }
  2796. }
  2797. if (getSema()->getLangOpts().UseMinPrecision) {
  2798. switch (type) {
  2799. case HLSLScalarType_float16:
  2800. case HLSLScalarType_int16:
  2801. case HLSLScalarType_uint16:
  2802. m_sema->Diag(Loc, diag::err_hlsl_unsupported_keyword_for_min_precision)
  2803. << HLSLScalarTypeNames[type];
  2804. return false;
  2805. default:
  2806. break;
  2807. }
  2808. }
  2809. return true;
  2810. }
  2811. bool LookupUnqualified(LookupResult &R, Scope *S) override
  2812. {
  2813. const DeclarationNameInfo declName = R.getLookupNameInfo();
  2814. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  2815. if (idInfo == nullptr) {
  2816. return false;
  2817. }
  2818. // Currently template instantiation is blocked when a fatal error is
  2819. // detected. So no faulting-in types at this point, instead we simply
  2820. // back out.
  2821. if (this->m_sema->Diags.hasFatalErrorOccurred()) {
  2822. return false;
  2823. }
  2824. StringRef nameIdentifier = idInfo->getName();
  2825. HLSLScalarType parsedType;
  2826. int rowCount;
  2827. int colCount;
  2828. // Try parsing hlsl scalar types that is not initialized at AST time.
  2829. if (TryParseAny(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &rowCount, &colCount, getSema()->getLangOpts())) {
  2830. assert(parsedType != HLSLScalarType_unknown && "otherwise, TryParseHLSLScalarType should not have succeeded.");
  2831. if (rowCount == 0 && colCount == 0) { // scalar
  2832. TypedefDecl *typeDecl = LookupScalarTypeDef(parsedType);
  2833. if (!typeDecl) return false;
  2834. R.addDecl(typeDecl);
  2835. }
  2836. else if (rowCount == 0) { // vector
  2837. QualType qt = LookupVectorType(parsedType, colCount);
  2838. TypedefDecl *qts = LookupVectorShorthandType(parsedType, colCount);
  2839. R.addDecl(qts);
  2840. }
  2841. else { // matrix
  2842. QualType qt = LookupMatrixType(parsedType, rowCount, colCount);
  2843. TypedefDecl* qts = LookupMatrixShorthandType(parsedType, rowCount, colCount);
  2844. R.addDecl(qts);
  2845. }
  2846. return true;
  2847. }
  2848. return false;
  2849. }
  2850. /// <summary>
  2851. /// Determines whether the specify record type is a matrix, another HLSL object, or a user-defined structure.
  2852. /// </sumary>
  2853. ArTypeObjectKind ClassifyRecordType(const RecordType* type)
  2854. {
  2855. DXASSERT_NOMSG(type != nullptr);
  2856. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  2857. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  2858. if (templateSpecializationDecl) {
  2859. ClassTemplateDecl *decl = templateSpecializationDecl->getSpecializedTemplate();
  2860. if (decl == m_matrixTemplateDecl)
  2861. return AR_TOBJ_MATRIX;
  2862. else if (decl == m_vectorTemplateDecl)
  2863. return AR_TOBJ_VECTOR;
  2864. DXASSERT(decl->isImplicit(), "otherwise object template decl is not set to implicit");
  2865. return AR_TOBJ_OBJECT;
  2866. }
  2867. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  2868. if (typeRecordDecl->getDeclContext()->isFileContext())
  2869. return AR_TOBJ_OBJECT;
  2870. else
  2871. return AR_TOBJ_INNER_OBJ;
  2872. }
  2873. return AR_TOBJ_COMPOUND;
  2874. }
  2875. /// <summary>Given a Clang type, determines whether it is a built-in object type (sampler, texture, etc).</summary>
  2876. bool IsBuiltInObjectType(QualType type)
  2877. {
  2878. type = GetStructuralForm(type);
  2879. if (!type.isNull() && type->isStructureOrClassType()) {
  2880. const RecordType* recordType = type->getAs<RecordType>();
  2881. return ClassifyRecordType(recordType) == AR_TOBJ_OBJECT;
  2882. }
  2883. return false;
  2884. }
  2885. /// <summary>
  2886. /// Given the specified type (typed a DeclContext for convenience), determines its RecordDecl,
  2887. /// possibly refering to original template record if it's a specialization; this makes the result
  2888. /// suitable for looking up in initialization tables.
  2889. /// </summary>
  2890. const CXXRecordDecl* GetRecordDeclForBuiltInOrStruct(const DeclContext* context)
  2891. {
  2892. const CXXRecordDecl* recordDecl;
  2893. if (const ClassTemplateSpecializationDecl* decl = dyn_cast<ClassTemplateSpecializationDecl>(context))
  2894. {
  2895. recordDecl = decl->getSpecializedTemplate()->getTemplatedDecl();
  2896. }
  2897. else
  2898. {
  2899. recordDecl = dyn_cast<CXXRecordDecl>(context);
  2900. }
  2901. return recordDecl;
  2902. }
  2903. /// <summary>Given a Clang type, return the ArTypeObjectKind classification, (eg AR_TOBJ_VECTOR).</summary>
  2904. ArTypeObjectKind GetTypeObjectKind(QualType type)
  2905. {
  2906. DXASSERT_NOMSG(!type.isNull());
  2907. type = GetStructuralForm(type);
  2908. if (type->isVoidType()) return AR_TOBJ_VOID;
  2909. if (type->isArrayType()) return AR_TOBJ_ARRAY;
  2910. if (type->isPointerType()) {
  2911. return AR_TOBJ_POINTER;
  2912. }
  2913. if (type->isStructureOrClassType()) {
  2914. const RecordType* recordType = type->getAs<RecordType>();
  2915. return ClassifyRecordType(recordType);
  2916. } else if (const InjectedClassNameType *ClassNameTy =
  2917. type->getAs<InjectedClassNameType>()) {
  2918. const CXXRecordDecl *typeRecordDecl = ClassNameTy->getDecl();
  2919. const ClassTemplateSpecializationDecl *templateSpecializationDecl =
  2920. dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  2921. if (templateSpecializationDecl) {
  2922. ClassTemplateDecl *decl =
  2923. templateSpecializationDecl->getSpecializedTemplate();
  2924. if (decl == m_matrixTemplateDecl)
  2925. return AR_TOBJ_MATRIX;
  2926. else if (decl == m_vectorTemplateDecl)
  2927. return AR_TOBJ_VECTOR;
  2928. DXASSERT(decl->isImplicit(),
  2929. "otherwise object template decl is not set to implicit");
  2930. return AR_TOBJ_OBJECT;
  2931. }
  2932. if (typeRecordDecl && typeRecordDecl->isImplicit()) {
  2933. if (typeRecordDecl->getDeclContext()->isFileContext())
  2934. return AR_TOBJ_OBJECT;
  2935. else
  2936. return AR_TOBJ_INNER_OBJ;
  2937. }
  2938. return AR_TOBJ_COMPOUND;
  2939. }
  2940. if (type->isBuiltinType()) return AR_TOBJ_BASIC;
  2941. if (type->isEnumeralType()) return AR_TOBJ_BASIC;
  2942. return AR_TOBJ_INVALID;
  2943. }
  2944. /// <summary>Gets the element type of a matrix or vector type (eg, the 'float' in 'float4x4' or 'float4').</summary>
  2945. QualType GetMatrixOrVectorElementType(QualType type)
  2946. {
  2947. type = GetStructuralForm(type);
  2948. const CXXRecordDecl* typeRecordDecl = type->getAsCXXRecordDecl();
  2949. DXASSERT_NOMSG(typeRecordDecl);
  2950. const ClassTemplateSpecializationDecl* templateSpecializationDecl = dyn_cast<ClassTemplateSpecializationDecl>(typeRecordDecl);
  2951. DXASSERT_NOMSG(templateSpecializationDecl);
  2952. DXASSERT_NOMSG(templateSpecializationDecl->getSpecializedTemplate() == m_matrixTemplateDecl ||
  2953. templateSpecializationDecl->getSpecializedTemplate() == m_vectorTemplateDecl);
  2954. return templateSpecializationDecl->getTemplateArgs().get(0).getAsType();
  2955. }
  2956. /// <summary>Gets the type with structural information (elements and shape) for the given type.</summary>
  2957. /// <remarks>This function will strip lvalue/rvalue references, attributes and qualifiers.</remarks>
  2958. QualType GetStructuralForm(QualType type)
  2959. {
  2960. if (type.isNull()) {
  2961. return type;
  2962. }
  2963. const ReferenceType *RefType = nullptr;
  2964. const AttributedType *AttrType = nullptr;
  2965. while ( (RefType = dyn_cast<ReferenceType>(type)) ||
  2966. (AttrType = dyn_cast<AttributedType>(type)))
  2967. {
  2968. type = RefType ? RefType->getPointeeType() : AttrType->getEquivalentType();
  2969. }
  2970. return type->getCanonicalTypeUnqualified();
  2971. }
  2972. /// <summary>Given a Clang type, return the ArBasicKind classification for its contents.</summary>
  2973. ArBasicKind GetTypeElementKind(QualType type)
  2974. {
  2975. type = GetStructuralForm(type);
  2976. ArTypeObjectKind kind = GetTypeObjectKind(type);
  2977. if (kind == AR_TOBJ_MATRIX || kind == AR_TOBJ_VECTOR) {
  2978. QualType elementType = GetMatrixOrVectorElementType(type);
  2979. return GetTypeElementKind(elementType);
  2980. }
  2981. if (type->isArrayType()) {
  2982. const ArrayType* arrayType = type->getAsArrayTypeUnsafe();
  2983. return GetTypeElementKind(arrayType->getElementType());
  2984. }
  2985. if (kind == AR_TOBJ_INNER_OBJ) {
  2986. return AR_OBJECT_INNER;
  2987. } else if (kind == AR_TOBJ_OBJECT) {
  2988. // Classify the object as the element type.
  2989. const CXXRecordDecl* typeRecordDecl = GetRecordDeclForBuiltInOrStruct(type->getAsCXXRecordDecl());
  2990. int index = FindObjectBasicKindIndex(typeRecordDecl);
  2991. // NOTE: this will likely need to be updated for specialized records
  2992. DXASSERT(index != -1, "otherwise can't find type we already determined was an object");
  2993. return g_ArBasicKindsAsTypes[index];
  2994. }
  2995. CanQualType canType = type->getCanonicalTypeUnqualified();
  2996. return BasicTypeForScalarType(canType);
  2997. }
  2998. ArBasicKind BasicTypeForScalarType(CanQualType type)
  2999. {
  3000. if (const BuiltinType *BT = dyn_cast<BuiltinType>(type))
  3001. {
  3002. switch (BT->getKind())
  3003. {
  3004. case BuiltinType::Bool: return AR_BASIC_BOOL;
  3005. case BuiltinType::Double: return AR_BASIC_FLOAT64;
  3006. case BuiltinType::Float: return AR_BASIC_FLOAT32;
  3007. case BuiltinType::Half: return m_context->getLangOpts().UseMinPrecision ? AR_BASIC_MIN16FLOAT : AR_BASIC_FLOAT16;
  3008. case BuiltinType::Int: return AR_BASIC_INT32;
  3009. case BuiltinType::UInt: return AR_BASIC_UINT32;
  3010. case BuiltinType::Short: return m_context->getLangOpts().UseMinPrecision ? AR_BASIC_MIN16INT : AR_BASIC_INT16;
  3011. case BuiltinType::UShort: return m_context->getLangOpts().UseMinPrecision ? AR_BASIC_MIN16UINT : AR_BASIC_UINT16;
  3012. case BuiltinType::Long: return AR_BASIC_INT32;
  3013. case BuiltinType::ULong: return AR_BASIC_UINT32;
  3014. case BuiltinType::LongLong: return AR_BASIC_INT64;
  3015. case BuiltinType::ULongLong: return AR_BASIC_UINT64;
  3016. case BuiltinType::Min12Int: return AR_BASIC_MIN12INT;
  3017. case BuiltinType::Min10Float: return AR_BASIC_MIN10FLOAT;
  3018. case BuiltinType::LitFloat: return AR_BASIC_LITERAL_FLOAT;
  3019. case BuiltinType::LitInt: return AR_BASIC_LITERAL_INT;
  3020. }
  3021. }
  3022. if (const EnumType *ET = dyn_cast<EnumType>(type)) {
  3023. if (ET->getDecl()->isScopedUsingClassTag())
  3024. return AR_BASIC_ENUM_CLASS;
  3025. return AR_BASIC_ENUM;
  3026. }
  3027. return AR_BASIC_UNKNOWN;
  3028. }
  3029. void AddIntrinsicTableMethods(_In_ IDxcIntrinsicTable *table) {
  3030. DXASSERT_NOMSG(table != nullptr);
  3031. // Function intrinsics are added on-demand, objects get template methods.
  3032. for (int i = 0; i < _countof(g_ArBasicKindsAsTypes); i++) {
  3033. // Grab information already processed by AddObjectTypes.
  3034. ArBasicKind kind = g_ArBasicKindsAsTypes[i];
  3035. const char *typeName = g_ArBasicTypeNames[kind];
  3036. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[i];
  3037. DXASSERT(0 <= templateArgCount && templateArgCount <= 2,
  3038. "otherwise a new case has been added");
  3039. int startDepth = (templateArgCount == 0) ? 0 : 1;
  3040. CXXRecordDecl *recordDecl = m_objectTypeDecls[i];
  3041. if (recordDecl == nullptr) {
  3042. DXASSERT(kind == AR_OBJECT_WAVE, "else objects other than reserved not initialized");
  3043. continue;
  3044. }
  3045. // This is a variation of AddObjectMethods using the new table.
  3046. const HLSL_INTRINSIC *pIntrinsic = nullptr;
  3047. const HLSL_INTRINSIC *pPrior = nullptr;
  3048. UINT64 lookupCookie = 0;
  3049. CA2W wideTypeName(typeName);
  3050. HRESULT found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  3051. while (pIntrinsic != nullptr && SUCCEEDED(found)) {
  3052. if (!AreIntrinsicTemplatesEquivalent(pIntrinsic, pPrior)) {
  3053. AddObjectIntrinsicTemplate(recordDecl, startDepth, pIntrinsic);
  3054. // NOTE: this only works with the current implementation because
  3055. // intrinsics are alive as long as the table is alive.
  3056. pPrior = pIntrinsic;
  3057. }
  3058. found = table->LookupIntrinsic(wideTypeName, L"*", &pIntrinsic, &lookupCookie);
  3059. }
  3060. }
  3061. }
  3062. void RegisterIntrinsicTable(_In_ IDxcIntrinsicTable *table) {
  3063. DXASSERT_NOMSG(table != nullptr);
  3064. m_intrinsicTables.push_back(table);
  3065. // If already initialized, add methods immediately.
  3066. if (m_sema != nullptr) {
  3067. AddIntrinsicTableMethods(table);
  3068. }
  3069. }
  3070. HLSLScalarType ScalarTypeForBasic(ArBasicKind kind)
  3071. {
  3072. DXASSERT(kind < AR_BASIC_COUNT, "otherwise caller didn't check that the value was in range");
  3073. switch (kind) {
  3074. case AR_BASIC_BOOL: return HLSLScalarType_bool;
  3075. case AR_BASIC_LITERAL_FLOAT: return HLSLScalarType_float_lit;
  3076. case AR_BASIC_FLOAT16: return HLSLScalarType_float_min16;
  3077. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  3078. return HLSLScalarType_float;
  3079. case AR_BASIC_FLOAT32: return HLSLScalarType_float;
  3080. case AR_BASIC_FLOAT64: return HLSLScalarType_double;
  3081. case AR_BASIC_LITERAL_INT: return HLSLScalarType_int_lit;
  3082. case AR_BASIC_INT8: return HLSLScalarType_int;
  3083. case AR_BASIC_UINT8: return HLSLScalarType_uint;
  3084. case AR_BASIC_INT16: return HLSLScalarType_int16;
  3085. case AR_BASIC_UINT16: return HLSLScalarType_uint16;
  3086. case AR_BASIC_INT32: return HLSLScalarType_int;
  3087. case AR_BASIC_UINT32: return HLSLScalarType_uint;
  3088. case AR_BASIC_MIN10FLOAT: return HLSLScalarType_float_min10;
  3089. case AR_BASIC_MIN16FLOAT: return HLSLScalarType_float_min16;
  3090. case AR_BASIC_MIN12INT: return HLSLScalarType_int_min12;
  3091. case AR_BASIC_MIN16INT: return HLSLScalarType_int_min16;
  3092. case AR_BASIC_MIN16UINT: return HLSLScalarType_uint_min16;
  3093. case AR_BASIC_INT64: return HLSLScalarType_int64;
  3094. case AR_BASIC_UINT64: return HLSLScalarType_uint64;
  3095. default:
  3096. return HLSLScalarType_unknown;
  3097. }
  3098. }
  3099. QualType GetBasicKindType(ArBasicKind kind)
  3100. {
  3101. DXASSERT_VALIDBASICKIND(kind);
  3102. switch (kind) {
  3103. case AR_OBJECT_NULL: return m_context->VoidTy;
  3104. case AR_BASIC_BOOL: return m_context->BoolTy;
  3105. case AR_BASIC_LITERAL_FLOAT: return m_context->LitFloatTy;
  3106. case AR_BASIC_FLOAT16: return m_context->HalfTy;
  3107. case AR_BASIC_FLOAT32_PARTIAL_PRECISION: return m_context->FloatTy;
  3108. case AR_BASIC_FLOAT32: return m_context->FloatTy;
  3109. case AR_BASIC_FLOAT64: return m_context->DoubleTy;
  3110. case AR_BASIC_LITERAL_INT: return m_context->LitIntTy;
  3111. case AR_BASIC_INT8: return m_context->IntTy;
  3112. case AR_BASIC_UINT8: return m_context->UnsignedIntTy;
  3113. case AR_BASIC_INT16: return m_context->ShortTy;
  3114. case AR_BASIC_UINT16: return m_context->UnsignedShortTy;
  3115. case AR_BASIC_INT32: return m_context->IntTy;
  3116. case AR_BASIC_UINT32: return m_context->UnsignedIntTy;
  3117. case AR_BASIC_INT64: return m_context->LongLongTy;
  3118. case AR_BASIC_UINT64: return m_context->UnsignedLongLongTy;
  3119. case AR_BASIC_MIN10FLOAT: return m_scalarTypes[HLSLScalarType_float_min10];
  3120. case AR_BASIC_MIN16FLOAT: return m_scalarTypes[HLSLScalarType_float_min16];
  3121. case AR_BASIC_MIN12INT: return m_scalarTypes[HLSLScalarType_int_min12];
  3122. case AR_BASIC_MIN16INT: return m_scalarTypes[HLSLScalarType_int_min16];
  3123. case AR_BASIC_MIN16UINT: return m_scalarTypes[HLSLScalarType_uint_min16];
  3124. case AR_OBJECT_STRING: return QualType();
  3125. case AR_OBJECT_LEGACY_EFFECT: // used for all legacy effect object types
  3126. case AR_OBJECT_TEXTURE1D:
  3127. case AR_OBJECT_TEXTURE1D_ARRAY:
  3128. case AR_OBJECT_TEXTURE2D:
  3129. case AR_OBJECT_TEXTURE2D_ARRAY:
  3130. case AR_OBJECT_TEXTURE3D:
  3131. case AR_OBJECT_TEXTURECUBE:
  3132. case AR_OBJECT_TEXTURECUBE_ARRAY:
  3133. case AR_OBJECT_TEXTURE2DMS:
  3134. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  3135. case AR_OBJECT_SAMPLER:
  3136. case AR_OBJECT_SAMPLERCOMPARISON:
  3137. case AR_OBJECT_BUFFER:
  3138. case AR_OBJECT_POINTSTREAM:
  3139. case AR_OBJECT_LINESTREAM:
  3140. case AR_OBJECT_TRIANGLESTREAM:
  3141. case AR_OBJECT_INPUTPATCH:
  3142. case AR_OBJECT_OUTPUTPATCH:
  3143. case AR_OBJECT_RWTEXTURE1D:
  3144. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  3145. case AR_OBJECT_RWTEXTURE2D:
  3146. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  3147. case AR_OBJECT_RWTEXTURE3D:
  3148. case AR_OBJECT_RWBUFFER:
  3149. case AR_OBJECT_BYTEADDRESS_BUFFER:
  3150. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  3151. case AR_OBJECT_STRUCTURED_BUFFER:
  3152. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  3153. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  3154. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  3155. case AR_OBJECT_WAVE:
  3156. {
  3157. const ArBasicKind* match = std::find(g_ArBasicKindsAsTypes, &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], kind);
  3158. DXASSERT(match != &g_ArBasicKindsAsTypes[_countof(g_ArBasicKindsAsTypes)], "otherwise can't find constant in basic kinds");
  3159. size_t index = match - g_ArBasicKindsAsTypes;
  3160. return m_context->getTagDeclType(this->m_objectTypeDecls[index]);
  3161. }
  3162. case AR_OBJECT_SAMPLER1D:
  3163. case AR_OBJECT_SAMPLER2D:
  3164. case AR_OBJECT_SAMPLER3D:
  3165. case AR_OBJECT_SAMPLERCUBE:
  3166. // Turn dimension-typed samplers into sampler states.
  3167. return GetBasicKindType(AR_OBJECT_SAMPLER);
  3168. case AR_OBJECT_STATEBLOCK:
  3169. case AR_OBJECT_RASTERIZER:
  3170. case AR_OBJECT_DEPTHSTENCIL:
  3171. case AR_OBJECT_BLEND:
  3172. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  3173. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  3174. default:
  3175. return QualType();
  3176. }
  3177. }
  3178. /// <summary>Promotes the specified expression to an integer type if it's a boolean type.</summary
  3179. /// <param name="E">Expression to typecast.</param>
  3180. /// <returns>E typecast to a integer type if it's a valid boolean type; E otherwise.</returns>
  3181. ExprResult PromoteToIntIfBool(ExprResult& E);
  3182. QualType NewQualifiedType(UINT64 qwUsages, QualType type)
  3183. {
  3184. // NOTE: NewQualifiedType does quite a bit more in the prior compiler
  3185. (qwUsages);
  3186. return type;
  3187. }
  3188. QualType NewSimpleAggregateType(
  3189. _In_ ArTypeObjectKind ExplicitKind,
  3190. _In_ ArBasicKind componentType,
  3191. _In_ UINT64 qwQual,
  3192. _In_ UINT uRows,
  3193. _In_ UINT uCols)
  3194. {
  3195. DXASSERT_VALIDBASICKIND(componentType);
  3196. QualType pType; // The type to return.
  3197. QualType pEltType = GetBasicKindType(componentType);
  3198. DXASSERT(!pEltType.isNull(), "otherwise caller is specifying an incorrect basic kind type");
  3199. // TODO: handle adding qualifications like const
  3200. pType = NewQualifiedType(
  3201. qwQual & ~(UINT64)(AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR),
  3202. pEltType);
  3203. if (uRows > 1 ||
  3204. uCols > 1 ||
  3205. ExplicitKind == AR_TOBJ_VECTOR ||
  3206. ExplicitKind == AR_TOBJ_MATRIX)
  3207. {
  3208. HLSLScalarType scalarType = ScalarTypeForBasic(componentType);
  3209. DXASSERT(scalarType != HLSLScalarType_unknown, "otherwise caller is specifying an incorrect type");
  3210. if ((uRows == 1 &&
  3211. ExplicitKind != AR_TOBJ_MATRIX) ||
  3212. ExplicitKind == AR_TOBJ_VECTOR)
  3213. {
  3214. pType = LookupVectorType(scalarType, uCols);
  3215. }
  3216. else
  3217. {
  3218. pType = LookupMatrixType(scalarType, uRows, uCols);
  3219. }
  3220. // TODO: handle colmajor/rowmajor
  3221. //if ((qwQual & (AR_QUAL_COLMAJOR | AR_QUAL_ROWMAJOR)) != 0)
  3222. //{
  3223. // VN(pType = NewQualifiedType(pSrcLoc,
  3224. // qwQual & (AR_QUAL_COLMAJOR |
  3225. // AR_QUAL_ROWMAJOR),
  3226. // pMatrix));
  3227. //}
  3228. //else
  3229. //{
  3230. // pType = pMatrix;
  3231. //}
  3232. }
  3233. return pType;
  3234. }
  3235. /// <summary>Attempts to match Args to the signature specification in pIntrinsic.</summary>
  3236. /// <param name="pIntrinsic">Intrinsic function to match.</param>
  3237. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  3238. /// <param name="Args">Invocation arguments to match.</param>
  3239. /// <param name="argTypes">After exectuion, type of arguments.</param>
  3240. /// <param name="argCount">After execution, number of arguments in argTypes.</param>
  3241. /// <remarks>On success, argTypes includes the clang Types to use for the signature, with the first being the return type.</remarks>
  3242. bool MatchArguments(
  3243. const _In_ HLSL_INTRINSIC *pIntrinsic,
  3244. _In_ QualType objectElement,
  3245. _In_ ArrayRef<Expr *> Args,
  3246. _Out_writes_(g_MaxIntrinsicParamCount + 1) QualType(&argTypes)[g_MaxIntrinsicParamCount + 1],
  3247. _Out_range_(0, g_MaxIntrinsicParamCount + 1) size_t* argCount);
  3248. /// <summary>Validate object element on intrinsic to catch case like integer on Sample.</summary>
  3249. /// <param name="pIntrinsic">Intrinsic function to validate.</param>
  3250. /// <param name="objectElement">Type element on the class intrinsic belongs to; possibly null (eg, 'float' in 'Texture2D<float>').</param>
  3251. bool IsValidateObjectElement(
  3252. _In_ const HLSL_INTRINSIC *pIntrinsic,
  3253. _In_ QualType objectElement);
  3254. // Returns the iterator with the first entry that matches the requirement
  3255. IntrinsicDefIter FindIntrinsicByNameAndArgCount(
  3256. _In_count_(tableSize) const HLSL_INTRINSIC* table,
  3257. size_t tableSize,
  3258. StringRef typeName,
  3259. StringRef nameIdentifier,
  3260. size_t argumentCount)
  3261. {
  3262. // This is implemented by a linear scan for now.
  3263. // We tested binary search on tables, and there was no performance gain on
  3264. // samples probably for the following reasons.
  3265. // 1. The tables are not big enough to make noticable difference
  3266. // 2. The user of this function assumes that it returns the first entry in
  3267. // the table that matches name and argument count. So even in the binary
  3268. // search, we have to scan backwards until the entry does not match the name
  3269. // or arg count. For linear search this is not a problem
  3270. for (unsigned int i = 0; i < tableSize; i++) {
  3271. const HLSL_INTRINSIC* pIntrinsic = &table[i];
  3272. // Do some quick checks to verify size and name.
  3273. if (pIntrinsic->uNumArgs != 1 + argumentCount) {
  3274. continue;
  3275. }
  3276. if (!nameIdentifier.equals(StringRef(pIntrinsic->pArgs[0].pName))) {
  3277. continue;
  3278. }
  3279. return IntrinsicDefIter::CreateStart(table, tableSize, pIntrinsic,
  3280. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  3281. }
  3282. return IntrinsicDefIter::CreateStart(table, tableSize, table + tableSize,
  3283. IntrinsicTableDefIter::CreateStart(m_intrinsicTables, typeName, nameIdentifier, argumentCount));
  3284. }
  3285. bool AddOverloadedCallCandidates(
  3286. UnresolvedLookupExpr *ULE,
  3287. ArrayRef<Expr *> Args,
  3288. OverloadCandidateSet &CandidateSet,
  3289. bool PartialOverloading) override
  3290. {
  3291. DXASSERT_NOMSG(ULE != nullptr);
  3292. const DeclarationNameInfo declName = ULE->getNameInfo();
  3293. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  3294. if (idInfo == nullptr)
  3295. {
  3296. return false;
  3297. }
  3298. StringRef nameIdentifier = idInfo->getName();
  3299. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(
  3300. g_Intrinsics, _countof(g_Intrinsics), StringRef(), nameIdentifier, Args.size());
  3301. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(
  3302. g_Intrinsics, _countof(g_Intrinsics), IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  3303. while (cursor != end)
  3304. {
  3305. // If this is the intrinsic we're interested in, build up a representation
  3306. // of the types we need.
  3307. const HLSL_INTRINSIC* pIntrinsic = *cursor;
  3308. LPCSTR tableName = cursor.GetTableName();
  3309. LPCSTR lowering = cursor.GetLoweringStrategy();
  3310. DXASSERT(
  3311. pIntrinsic->uNumArgs <= g_MaxIntrinsicParamCount + 1,
  3312. "otherwise g_MaxIntrinsicParamCount needs to be updated for wider signatures");
  3313. QualType functionArgTypes[g_MaxIntrinsicParamCount + 1];
  3314. size_t functionArgTypeCount = 0;
  3315. if (!MatchArguments(pIntrinsic, QualType(), Args, functionArgTypes, &functionArgTypeCount))
  3316. {
  3317. ++cursor;
  3318. continue;
  3319. }
  3320. // Get or create the overload we're interested in.
  3321. FunctionDecl* intrinsicFuncDecl = nullptr;
  3322. std::pair<UsedIntrinsicStore::iterator, bool> insertResult = m_usedIntrinsics.insert(UsedIntrinsic(
  3323. pIntrinsic, functionArgTypes, functionArgTypeCount));
  3324. bool insertedNewValue = insertResult.second;
  3325. if (insertedNewValue)
  3326. {
  3327. DXASSERT(tableName, "otherwise IDxcIntrinsicTable::GetTableName() failed");
  3328. intrinsicFuncDecl = AddHLSLIntrinsicFunction(*m_context, m_hlslNSDecl, tableName, lowering, pIntrinsic, functionArgTypes, functionArgTypeCount);
  3329. insertResult.first->setFunctionDecl(intrinsicFuncDecl);
  3330. }
  3331. else
  3332. {
  3333. intrinsicFuncDecl = (*insertResult.first).getFunctionDecl();
  3334. }
  3335. OverloadCandidate& candidate = CandidateSet.addCandidate();
  3336. candidate.Function = intrinsicFuncDecl;
  3337. candidate.FoundDecl.setDecl(intrinsicFuncDecl);
  3338. candidate.Viable = true;
  3339. return true;
  3340. }
  3341. return false;
  3342. }
  3343. bool Initialize(ASTContext& context)
  3344. {
  3345. m_context = &context;
  3346. m_hlslNSDecl = NamespaceDecl::Create(context, context.getTranslationUnitDecl(),
  3347. /*Inline*/ false, SourceLocation(),
  3348. SourceLocation(), &context.Idents.get("hlsl"),
  3349. /*PrevDecl*/ nullptr);
  3350. m_hlslNSDecl->setImplicit();
  3351. AddBaseTypes();
  3352. AddHLSLScalarTypes();
  3353. AddHLSLVectorTemplate(*m_context, &m_vectorTemplateDecl);
  3354. DXASSERT(m_vectorTemplateDecl != nullptr, "AddHLSLVectorTypes failed to return the vector template declaration");
  3355. AddHLSLMatrixTemplate(*m_context, m_vectorTemplateDecl, &m_matrixTemplateDecl);
  3356. DXASSERT(m_matrixTemplateDecl != nullptr, "AddHLSLMatrixTypes failed to return the matrix template declaration");
  3357. return true;
  3358. }
  3359. /// <summary>Checks whether the specified type is numeric or composed of numeric elements exclusively.</summary>
  3360. bool IsTypeNumeric(QualType type, _Out_ UINT* count);
  3361. /// <summary>Checks whether the specified type is a scalar type.</summary>
  3362. bool IsScalarType(const QualType& type) {
  3363. DXASSERT(!type.isNull(), "caller should validate its type is initialized");
  3364. return BasicTypeForScalarType(type->getCanonicalTypeUnqualified()) != AR_BASIC_UNKNOWN;
  3365. }
  3366. /// <summary>Checks whether the specified value is a valid vector size.</summary>
  3367. bool IsValidVectorSize(size_t length) {
  3368. return 1 <= length && length <= 4;
  3369. }
  3370. /// <summary>Checks whether the specified value is a valid matrix row or column size.</summary>
  3371. bool IsValidMatrixColOrRowSize(size_t length) {
  3372. return 1 <= length && length <= 4;
  3373. }
  3374. bool IsValidTemplateArgumentType(SourceLocation argLoc, const QualType& type, bool requireScalar) {
  3375. if (type.isNull()) {
  3376. return false;
  3377. }
  3378. if (type.hasQualifiers()) {
  3379. return false;
  3380. }
  3381. // TemplateTypeParm here will be construction of vector return template in matrix operator[]
  3382. if (type->getTypeClass() == Type::TemplateTypeParm)
  3383. return true;
  3384. QualType qt = GetStructuralForm(type);
  3385. if (requireScalar) {
  3386. if (!IsScalarType(qt)) {
  3387. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument_requires_scalar) << type;
  3388. return false;
  3389. }
  3390. return true;
  3391. }
  3392. else {
  3393. ArTypeObjectKind objectKind = GetTypeObjectKind(qt);
  3394. if (qt->isArrayType()) {
  3395. const ArrayType* arrayType = qt->getAsArrayTypeUnsafe();
  3396. return IsValidTemplateArgumentType(argLoc, arrayType->getElementType(), false);
  3397. }
  3398. else if (objectKind == AR_TOBJ_VECTOR) {
  3399. bool valid = true;
  3400. if (!IsValidVectorSize(GetHLSLVecSize(type))) {
  3401. valid = false;
  3402. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectorsize) << type << GetHLSLVecSize(type);
  3403. }
  3404. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  3405. valid = false;
  3406. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  3407. }
  3408. return valid;
  3409. }
  3410. else if (objectKind == AR_TOBJ_MATRIX) {
  3411. bool valid = true;
  3412. UINT rowCount, colCount;
  3413. GetRowsAndCols(type, rowCount, colCount);
  3414. if (!IsValidMatrixColOrRowSize(rowCount) || !IsValidMatrixColOrRowSize(colCount)) {
  3415. valid = false;
  3416. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedmatrixsize) << type << rowCount << colCount;
  3417. }
  3418. if (!IsScalarType(GetMatrixOrVectorElementType(type))) {
  3419. valid = false;
  3420. m_sema->Diag(argLoc, diag::err_hlsl_unsupportedvectortype) << type << GetMatrixOrVectorElementType(type);
  3421. }
  3422. return valid;
  3423. }
  3424. else if (qt->isStructureType()) {
  3425. const RecordType* recordType = qt->getAsStructureType();
  3426. objectKind = ClassifyRecordType(recordType);
  3427. switch (objectKind)
  3428. {
  3429. case AR_TOBJ_OBJECT:
  3430. m_sema->Diag(argLoc, diag::err_hlsl_objectintemplateargument) << type;
  3431. return false;
  3432. case AR_TOBJ_COMPOUND:
  3433. {
  3434. const RecordDecl* recordDecl = recordType->getDecl();
  3435. RecordDecl::field_iterator begin = recordDecl->field_begin();
  3436. RecordDecl::field_iterator end = recordDecl->field_end();
  3437. bool result = true;
  3438. while (begin != end) {
  3439. const FieldDecl* fieldDecl = *begin;
  3440. if (!IsValidTemplateArgumentType(argLoc, fieldDecl->getType(), false)) {
  3441. m_sema->Diag(argLoc, diag::note_field_type_usage)
  3442. << fieldDecl->getType() << fieldDecl->getIdentifier() << type;
  3443. result = false;
  3444. }
  3445. begin++;
  3446. }
  3447. return result;
  3448. }
  3449. default:
  3450. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  3451. return false;
  3452. }
  3453. }
  3454. else if(IsScalarType(qt)) {
  3455. return true;
  3456. }
  3457. else {
  3458. m_sema->Diag(argLoc, diag::err_hlsl_typeintemplateargument) << type;
  3459. return false;
  3460. }
  3461. }
  3462. }
  3463. /// <summary>Checks whether the source type can be converted to the target type.</summary>
  3464. bool CanConvert(SourceLocation loc, Expr* sourceExpr, QualType target, bool explicitConversion,
  3465. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  3466. _Inout_opt_ StandardConversionSequence* sequence);
  3467. /// <summary>Produces an expression that turns the given expression into the specified numeric type.</summary>
  3468. Expr* CastExprToTypeNumeric(Expr* expr, QualType targetType);
  3469. void CollectInfo(QualType type, _Out_ ArTypeInfo* pTypeInfo);
  3470. void GetConversionForm(
  3471. QualType type,
  3472. bool explicitConversion,
  3473. ArTypeInfo* pTypeInfo);
  3474. bool ValidateCast(SourceLocation Loc, _In_ Expr* source, QualType target, bool explicitConversion,
  3475. bool suppressWarnings, bool suppressErrors,
  3476. _Inout_opt_ StandardConversionSequence* sequence);
  3477. bool ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind);
  3478. bool ValidateTypeRequirements(
  3479. SourceLocation loc,
  3480. ArBasicKind elementKind,
  3481. ArTypeObjectKind objectKind,
  3482. bool requiresIntegrals,
  3483. bool requiresNumerics);
  3484. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  3485. /// <param name="OpLoc">Source location for operator.</param>
  3486. /// <param name="Opc">Kind of binary operator.</param>
  3487. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  3488. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  3489. /// <param name="ResultTy">Result type for operator expression.</param>
  3490. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  3491. /// <param name="CompResultTy">Type of computation result.</param>
  3492. void CheckBinOpForHLSL(
  3493. SourceLocation OpLoc,
  3494. BinaryOperatorKind Opc,
  3495. ExprResult& LHS,
  3496. ExprResult& RHS,
  3497. QualType& ResultTy,
  3498. QualType& CompLHSTy,
  3499. QualType& CompResultTy);
  3500. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  3501. /// <param name="OpLoc">Source location for operator.</param>
  3502. /// <param name="Opc">Kind of operator.</param>
  3503. /// <param name="InputExpr">Input expression to the operator.</param>
  3504. /// <param name="VK">Value kind for resulting expression.</param>
  3505. /// <param name="OK">Object kind for resulting expression.</param>
  3506. /// <returns>The result type for the expression.</returns>
  3507. QualType CheckUnaryOpForHLSL(
  3508. SourceLocation OpLoc,
  3509. UnaryOperatorKind Opc,
  3510. ExprResult& InputExpr,
  3511. ExprValueKind& VK,
  3512. ExprObjectKind& OK);
  3513. /// <summary>Checks vector conditional operator (Cond ? LHS : RHS).</summary>
  3514. /// <param name="Cond">Vector condition expression.</param>
  3515. /// <param name="LHS">Left hand side.</param>
  3516. /// <param name="RHS">Right hand side.</param>
  3517. /// <param name="QuestionLoc">Location of question mark in operator.</param>
  3518. /// <returns>Result type of vector conditional expression.</returns>
  3519. clang::QualType HLSLExternalSource::CheckVectorConditional(
  3520. _In_ ExprResult &Cond,
  3521. _In_ ExprResult &LHS,
  3522. _In_ ExprResult &RHS,
  3523. _In_ SourceLocation QuestionLoc);
  3524. clang::QualType ApplyTypeSpecSignToParsedType(
  3525. _In_ clang::QualType &type,
  3526. _In_ TypeSpecifierSign TSS,
  3527. _In_ SourceLocation Loc
  3528. );
  3529. bool CheckRangedTemplateArgument(SourceLocation diagLoc, llvm::APSInt& sintValue)
  3530. {
  3531. if (!sintValue.isStrictlyPositive() || sintValue.getLimitedValue() > 4)
  3532. {
  3533. m_sema->Diag(diagLoc, diag::err_hlsl_invalid_range_1_4);
  3534. return true;
  3535. }
  3536. return false;
  3537. }
  3538. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  3539. bool
  3540. CheckTemplateArgumentListForHLSL(_In_ TemplateDecl *Template,
  3541. SourceLocation /* TemplateLoc */,
  3542. TemplateArgumentListInfo &TemplateArgList) {
  3543. DXASSERT_NOMSG(Template != nullptr);
  3544. // Determine which object type the template refers to.
  3545. StringRef templateName = Template->getName();
  3546. // NOTE: this 'escape valve' allows unit tests to perform type checks.
  3547. if (templateName.equals(StringRef("is_same"))) {
  3548. return false;
  3549. }
  3550. bool isMatrix = Template->getCanonicalDecl() ==
  3551. m_matrixTemplateDecl->getCanonicalDecl();
  3552. bool isVector = Template->getCanonicalDecl() ==
  3553. m_vectorTemplateDecl->getCanonicalDecl();
  3554. bool requireScalar = isMatrix || isVector;
  3555. // Check constraints on the type. Right now we only check that template
  3556. // types are primitive types.
  3557. for (unsigned int i = 0; i < TemplateArgList.size(); i++) {
  3558. const TemplateArgumentLoc &argLoc = TemplateArgList[i];
  3559. SourceLocation argSrcLoc = argLoc.getLocation();
  3560. const TemplateArgument &arg = argLoc.getArgument();
  3561. if (arg.getKind() == TemplateArgument::ArgKind::Type) {
  3562. QualType argType = arg.getAsType();
  3563. if (!IsValidTemplateArgumentType(argSrcLoc, argType, requireScalar)) {
  3564. // NOTE: IsValidTemplateArgumentType emits its own diagnostics
  3565. return true;
  3566. }
  3567. }
  3568. else if (arg.getKind() == TemplateArgument::ArgKind::Expression) {
  3569. if (isMatrix || isVector) {
  3570. Expr *expr = arg.getAsExpr();
  3571. llvm::APSInt constantResult;
  3572. if (expr != nullptr &&
  3573. expr->isIntegerConstantExpr(constantResult, *m_context)) {
  3574. if (CheckRangedTemplateArgument(argSrcLoc, constantResult)) {
  3575. return true;
  3576. }
  3577. }
  3578. }
  3579. }
  3580. else if (arg.getKind() == TemplateArgument::ArgKind::Integral) {
  3581. if (isMatrix || isVector) {
  3582. llvm::APSInt Val = arg.getAsIntegral();
  3583. if (CheckRangedTemplateArgument(argSrcLoc, Val)) {
  3584. return true;
  3585. }
  3586. }
  3587. }
  3588. }
  3589. return false;
  3590. }
  3591. /// <summary>Diagnoses an assignment operation.</summary>
  3592. /// <param name="ConvTy">Type of conversion assignment.</param>
  3593. /// <param name="Loc">Location for operation.</param>
  3594. /// <param name="DstType">Destination type.</param>
  3595. /// <param name="SrcType">Source type.</param>
  3596. /// <param name="SrcExpr">Source expression.</param>
  3597. /// <param name="Action">Action that triggers the assignment (assignment, passing, return, etc).</param>
  3598. /// <param name="Complained">Whether a diagnostic was emitted.</param>
  3599. void DiagnoseAssignmentResultForHLSL(
  3600. Sema::AssignConvertType ConvTy,
  3601. SourceLocation Loc,
  3602. QualType DstType, QualType SrcType,
  3603. _In_ Expr *SrcExpr, Sema::AssignmentAction Action,
  3604. _Out_opt_ bool *Complained);
  3605. FindStructBasicTypeResult FindStructBasicType(_In_ DeclContext* functionDeclContext);
  3606. /// <summary>Finds the table of intrinsics for the declaration context of a member function.</summary>
  3607. /// <param name="functionDeclContext">Declaration context of function.</param>
  3608. /// <param name="name">After execution, the name of the object to which the table applies.</param>
  3609. /// <param name="intrinsics">After execution, the intrinsic table.</param>
  3610. /// <param name="intrinsicCount">After execution, the count of elements in the intrinsic table.</param>
  3611. void FindIntrinsicTable(
  3612. _In_ DeclContext* functionDeclContext,
  3613. _Outptr_result_z_ const char** name,
  3614. _Outptr_result_buffer_(*intrinsicCount) const HLSL_INTRINSIC** intrinsics,
  3615. _Out_ size_t* intrinsicCount);
  3616. /// <summary>Deduces the template arguments by comparing the argument types and the HLSL intrinsic tables.</summary>
  3617. /// <param name="FunctionTemplate">The declaration for the function template being deduced.</param>
  3618. /// <param name="ExplicitTemplateArgs">Explicitly-provided template arguments. Should be empty for an HLSL program.</param>
  3619. /// <param name="Args">Array of expressions being used as arguments.</param>
  3620. /// <param name="Specialization">The declaration for the resolved specialization.</param>
  3621. /// <param name="Info">Provides information about an attempted template argument deduction.</param>
  3622. /// <returns>The result of the template deduction, TDK_Invalid if no HLSL-specific processing done.</returns>
  3623. Sema::TemplateDeductionResult DeduceTemplateArgumentsForHLSL(
  3624. FunctionTemplateDecl *FunctionTemplate,
  3625. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  3626. FunctionDecl *&Specialization, TemplateDeductionInfo &Info);
  3627. clang::OverloadingResult GetBestViableFunction(
  3628. clang::SourceLocation Loc,
  3629. clang::OverloadCandidateSet& set,
  3630. clang::OverloadCandidateSet::iterator& Best);
  3631. /// <summary>
  3632. /// Initializes the specified <paramref name="initSequence" /> describing how
  3633. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  3634. /// </summary>
  3635. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  3636. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  3637. /// <param name="Args">Arguments to the initialization.</param>
  3638. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  3639. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  3640. void InitializeInitSequenceForHLSL(
  3641. const InitializedEntity& Entity,
  3642. const InitializationKind& Kind,
  3643. MultiExprArg Args,
  3644. bool TopLevelOfInitList,
  3645. _Inout_ InitializationSequence* initSequence);
  3646. /// <summary>
  3647. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  3648. /// </summary>
  3649. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  3650. bool IsConversionToLessOrEqualElements(
  3651. const ExprResult& sourceExpr,
  3652. const QualType& targetType,
  3653. bool explicitConversion);
  3654. /// <summary>
  3655. /// Checks whether the specified conversion occurs to a type of idential element type but less elements.
  3656. /// </summary>
  3657. /// <remarks>This is an important case because a cast of this type does not turn an lvalue into an rvalue.</remarks>
  3658. bool IsConversionToLessOrEqualElements(
  3659. const QualType& sourceType,
  3660. const QualType& targetType,
  3661. bool explicitConversion);
  3662. /// <summary>Performs a member lookup on the specified BaseExpr if it's a matrix.</summary>
  3663. /// <param name="BaseExpr">Base expression for member access.</param>
  3664. /// <param name="MemberName">Name of member to look up.</param>
  3665. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  3666. /// <param name="OpLoc">Location of access operand.</param>
  3667. /// <param name="MemberLoc">Location of member.</param>
  3668. /// <param name="result">Result of lookup operation.</param>
  3669. /// <returns>true if the base type is a matrix and the lookup has been handled.</returns>
  3670. bool LookupMatrixMemberExprForHLSL(
  3671. Expr& BaseExpr,
  3672. DeclarationName MemberName,
  3673. bool IsArrow,
  3674. SourceLocation OpLoc,
  3675. SourceLocation MemberLoc,
  3676. ExprResult* result);
  3677. /// <summary>Performs a member lookup on the specified BaseExpr if it's a vector.</summary>
  3678. /// <param name="BaseExpr">Base expression for member access.</param>
  3679. /// <param name="MemberName">Name of member to look up.</param>
  3680. /// <param name="IsArrow">Whether access is through arrow (a->b) rather than period (a.b).</param>
  3681. /// <param name="OpLoc">Location of access operand.</param>
  3682. /// <param name="MemberLoc">Location of member.</param>
  3683. /// <param name="result">Result of lookup operation.</param>
  3684. /// <returns>true if the base type is a vector and the lookup has been handled.</returns>
  3685. bool LookupVectorMemberExprForHLSL(
  3686. Expr& BaseExpr,
  3687. DeclarationName MemberName,
  3688. bool IsArrow,
  3689. SourceLocation OpLoc,
  3690. SourceLocation MemberLoc,
  3691. ExprResult* result);
  3692. /// <summary>If E is a scalar, converts it to a 1-element vector.</summary>
  3693. /// <param name="E">Expression to convert.</param>
  3694. /// <returns>The result of the conversion; or E if the type is not a scalar.</returns>
  3695. ExprResult MaybeConvertScalarToVector(_In_ clang::Expr* E);
  3696. clang::Expr *HLSLImpCastToScalar(
  3697. _In_ clang::Sema* self,
  3698. _In_ clang::Expr* From,
  3699. ArTypeObjectKind FromShape,
  3700. ArBasicKind EltKind);
  3701. clang::ExprResult PerformHLSLConversion(
  3702. _In_ clang::Expr* From,
  3703. _In_ clang::QualType targetType,
  3704. _In_ const clang::StandardConversionSequence &SCS,
  3705. _In_ clang::Sema::CheckedConversionKind CCK);
  3706. /// <summary>Diagnoses an error when precessing the specified type if nesting is too deep.</summary>
  3707. void ReportUnsupportedTypeNesting(SourceLocation loc, QualType type);
  3708. /// <summary>
  3709. /// Checks if a static cast can be performed, and performs it if possible.
  3710. /// </summary>
  3711. /// <param name="SrcExpr">Expression to cast.</param>
  3712. /// <param name="DestType">Type to cast SrcExpr to.</param>
  3713. /// <param name="CCK">Kind of conversion: implicit, C-style, functional, other.</param>
  3714. /// <param name="OpRange">Source range for the cast operation.</param>
  3715. /// <param name="msg">Error message from the diag::* enumeration to fail with; zero to suppress messages.</param>
  3716. /// <param name="Kind">The kind of operation required for a conversion.</param>
  3717. /// <param name="BasePath">A simple array of base specifiers.</param>
  3718. /// <param name="ListInitialization">Whether the cast is in the context of a list initialization.</param>
  3719. /// <param name="SuppressWarnings">Whether warnings should be omitted.</param>
  3720. /// <param name="SuppressErrors">Whether errors should be omitted.</param>
  3721. bool TryStaticCastForHLSL(ExprResult &SrcExpr,
  3722. QualType DestType,
  3723. Sema::CheckedConversionKind CCK,
  3724. const SourceRange &OpRange, unsigned &msg,
  3725. CastKind &Kind, CXXCastPath &BasePath,
  3726. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  3727. _Inout_opt_ StandardConversionSequence* standard);
  3728. /// <summary>
  3729. /// Checks if a subscript index argument can be initialized from the given expression.
  3730. /// </summary>
  3731. /// <param name="SrcExpr">Source expression used as argument.</param>
  3732. /// <param name="DestType">Parameter type to initialize.</param>
  3733. /// <remarks>
  3734. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  3735. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  3736. /// </remarks>
  3737. ImplicitConversionSequence TrySubscriptIndexInitialization(_In_ clang::Expr* SrcExpr, clang::QualType DestType);
  3738. void AddHLSLObjectMethodsIfNotReady(QualType qt) {
  3739. static_assert((sizeof(uint64_t)*8) >= _countof(g_ArBasicKindsAsTypes), "Bitmask size is too small");
  3740. // Everything is ready.
  3741. if (m_objectTypeLazyInitMask == 0)
  3742. return;
  3743. CXXRecordDecl *recordDecl = const_cast<CXXRecordDecl *>(GetRecordDeclForBuiltInOrStruct(qt->getAsCXXRecordDecl()));
  3744. int idx = FindObjectBasicKindIndex(recordDecl);
  3745. // Not object type.
  3746. if (idx == -1)
  3747. return;
  3748. uint64_t bit = ((uint64_t)1)<<idx;
  3749. // Already created.
  3750. if ((m_objectTypeLazyInitMask & bit) == 0)
  3751. return;
  3752. ArBasicKind kind = g_ArBasicKindsAsTypes[idx];
  3753. uint8_t templateArgCount = g_ArBasicKindsTemplateCount[idx];
  3754. int startDepth = 0;
  3755. if (templateArgCount > 0) {
  3756. DXASSERT(templateArgCount == 1 || templateArgCount == 2,
  3757. "otherwise a new case has been added");
  3758. ClassTemplateDecl *typeDecl = recordDecl->getDescribedClassTemplate();
  3759. AddObjectSubscripts(kind, typeDecl, recordDecl,
  3760. g_ArBasicKindsSubscripts[idx]);
  3761. startDepth = 1;
  3762. }
  3763. AddObjectMethods(kind, recordDecl, startDepth);
  3764. // Clear the object.
  3765. m_objectTypeLazyInitMask &= ~bit;
  3766. }
  3767. FunctionDecl* AddHLSLIntrinsicMethod(
  3768. LPCSTR tableName,
  3769. LPCSTR lowering,
  3770. _In_ const HLSL_INTRINSIC* intrinsic,
  3771. _In_ FunctionTemplateDecl *FunctionTemplate,
  3772. ArrayRef<Expr *> Args,
  3773. _In_count_(parameterTypeCount) QualType* parameterTypes,
  3774. size_t parameterTypeCount)
  3775. {
  3776. DXASSERT_NOMSG(intrinsic != nullptr);
  3777. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  3778. DXASSERT_NOMSG(parameterTypes != nullptr);
  3779. DXASSERT(parameterTypeCount >= 1, "otherwise caller didn't initialize - there should be at least a void return type");
  3780. // Create the template arguments.
  3781. SmallVector<TemplateArgument, g_MaxIntrinsicParamCount + 1> templateArgs;
  3782. for (size_t i = 0; i < parameterTypeCount; i++) {
  3783. templateArgs.push_back(TemplateArgument(parameterTypes[i]));
  3784. }
  3785. // Look for an existing specialization.
  3786. void *InsertPos = nullptr;
  3787. FunctionDecl *SpecFunc =
  3788. FunctionTemplate->findSpecialization(templateArgs, InsertPos);
  3789. if (SpecFunc != nullptr) {
  3790. return SpecFunc;
  3791. }
  3792. // Change return type to rvalue reference type for aggregate types
  3793. QualType retTy = parameterTypes[0];
  3794. if (retTy->isAggregateType() && !IsHLSLVecMatType(retTy))
  3795. parameterTypes[0] = m_context->getRValueReferenceType(retTy);
  3796. // Create a new specialization.
  3797. SmallVector<ParameterModifier, g_MaxIntrinsicParamCount> paramMods;
  3798. InitParamMods(intrinsic, paramMods);
  3799. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  3800. // Change out/inout parameter type to rvalue reference type.
  3801. if (paramMods[i - 1].isAnyOut()) {
  3802. parameterTypes[i] = m_context->getLValueReferenceType(parameterTypes[i]);
  3803. }
  3804. }
  3805. IntrinsicOp intrinOp = static_cast<IntrinsicOp>(intrinsic->Op);
  3806. if (intrinOp == IntrinsicOp::MOP_SampleBias) {
  3807. // Remove this when update intrinsic table not affect other things.
  3808. // Change vector<float,1> into float for bias.
  3809. const unsigned biasOperandID = 3; // return type, sampler, coord, bias.
  3810. DXASSERT(parameterTypeCount > biasOperandID,
  3811. "else operation was misrecognized");
  3812. if (const ExtVectorType *VecTy =
  3813. hlsl::ConvertHLSLVecMatTypeToExtVectorType(
  3814. *m_context, parameterTypes[biasOperandID])) {
  3815. if (VecTy->getNumElements() == 1)
  3816. parameterTypes[biasOperandID] = VecTy->getElementType();
  3817. }
  3818. }
  3819. DeclContext *owner = FunctionTemplate->getDeclContext();
  3820. TemplateArgumentList templateArgumentList(
  3821. TemplateArgumentList::OnStackType::OnStack, templateArgs.data(),
  3822. templateArgs.size());
  3823. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  3824. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner,
  3825. mlTemplateArgumentList);
  3826. FunctionProtoType::ExtProtoInfo EmptyEPI;
  3827. QualType functionType = m_context->getFunctionType(
  3828. parameterTypes[0],
  3829. ArrayRef<QualType>(parameterTypes + 1, parameterTypeCount - 1),
  3830. EmptyEPI, paramMods);
  3831. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  3832. FunctionProtoTypeLoc Proto =
  3833. TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  3834. SmallVector<ParmVarDecl*, g_MaxIntrinsicParamCount> Params;
  3835. for (unsigned int i = 1; i < parameterTypeCount; i++) {
  3836. IdentifierInfo* id = &m_context->Idents.get(StringRef(intrinsic->pArgs[i - 1].pName));
  3837. ParmVarDecl *paramDecl = ParmVarDecl::Create(
  3838. *m_context, nullptr, NoLoc, NoLoc, id, parameterTypes[i], nullptr,
  3839. StorageClass::SC_None, nullptr, paramMods[i - 1]);
  3840. Params.push_back(paramDecl);
  3841. }
  3842. QualType T = TInfo->getType();
  3843. DeclarationNameInfo NameInfo(FunctionTemplate->getDeclName(), NoLoc);
  3844. CXXMethodDecl* method = CXXMethodDecl::Create(
  3845. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  3846. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  3847. // Add intrinsic attr
  3848. AddHLSLIntrinsicAttr(method, *m_context, tableName, lowering, intrinsic);
  3849. // Record this function template specialization.
  3850. TemplateArgumentList *argListCopy = TemplateArgumentList::CreateCopy(
  3851. *m_context, templateArgs.data(), templateArgs.size());
  3852. method->setFunctionTemplateSpecialization(FunctionTemplate, argListCopy, 0);
  3853. // Attach the parameters
  3854. for (unsigned P = 0; P < Params.size(); ++P) {
  3855. Params[P]->setOwningFunction(method);
  3856. Proto.setParam(P, Params[P]);
  3857. }
  3858. method->setParams(Params);
  3859. // Adjust access.
  3860. method->setAccess(AccessSpecifier::AS_public);
  3861. FunctionTemplate->setAccess(method->getAccess());
  3862. return method;
  3863. }
  3864. // Overload support.
  3865. UINT64 ScoreCast(QualType leftType, QualType rightType);
  3866. UINT64 ScoreFunction(OverloadCandidateSet::iterator &Cand);
  3867. UINT64 ScoreImplicitConversionSequence(const ImplicitConversionSequence *s);
  3868. unsigned GetNumElements(QualType anyType);
  3869. unsigned GetNumBasicElements(QualType anyType);
  3870. unsigned GetNumConvertCheckElts(QualType leftType, unsigned leftSize, QualType rightType, unsigned rightSize);
  3871. QualType GetNthElementType(QualType type, unsigned index);
  3872. bool IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind);
  3873. bool IsCast(ArBasicKind leftKind, ArBasicKind rightKind);
  3874. bool IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind);
  3875. };
  3876. // Use this class to flatten a type into HLSL primitives and iterate through them.
  3877. class FlattenedTypeIterator
  3878. {
  3879. private:
  3880. enum FlattenedIterKind {
  3881. FK_Simple,
  3882. FK_Fields,
  3883. FK_Expressions,
  3884. FK_IncompleteArray,
  3885. FK_Bases,
  3886. };
  3887. // Use this struct to represent a specific point in the tracked tree.
  3888. struct FlattenedTypeTracker {
  3889. QualType Type; // Type at this position in the tree.
  3890. unsigned int Count; // Count of consecutive types
  3891. CXXRecordDecl::base_class_iterator CurrentBase; // Current base for a structure type.
  3892. CXXRecordDecl::base_class_iterator EndBase; // STL-style end of bases.
  3893. RecordDecl::field_iterator CurrentField; // Current field in for a structure type.
  3894. RecordDecl::field_iterator EndField; // STL-style end of fields.
  3895. MultiExprArg::iterator CurrentExpr; // Current expression (advanceable for a list of expressions).
  3896. MultiExprArg::iterator EndExpr; // STL-style end of expressions.
  3897. FlattenedIterKind IterKind; // Kind of tracker.
  3898. bool IsConsidered; // If a FlattenedTypeTracker already been considered.
  3899. FlattenedTypeTracker(QualType type)
  3900. : Type(type), Count(0), CurrentExpr(nullptr),
  3901. IterKind(FK_IncompleteArray), IsConsidered(false) {}
  3902. FlattenedTypeTracker(QualType type, unsigned int count,
  3903. MultiExprArg::iterator expression)
  3904. : Type(type), Count(count), CurrentExpr(expression),
  3905. IterKind(FK_Simple), IsConsidered(false) {}
  3906. FlattenedTypeTracker(QualType type, RecordDecl::field_iterator current,
  3907. RecordDecl::field_iterator end)
  3908. : Type(type), Count(0), CurrentField(current), EndField(end),
  3909. CurrentExpr(nullptr), IterKind(FK_Fields), IsConsidered(false) {}
  3910. FlattenedTypeTracker(MultiExprArg::iterator current,
  3911. MultiExprArg::iterator end)
  3912. : Count(0), CurrentExpr(current), EndExpr(end),
  3913. IterKind(FK_Expressions), IsConsidered(false) {}
  3914. FlattenedTypeTracker(QualType type,
  3915. CXXRecordDecl::base_class_iterator current,
  3916. CXXRecordDecl::base_class_iterator end)
  3917. : Count(0), CurrentBase(current), EndBase(end), CurrentExpr(nullptr),
  3918. IterKind(FK_Bases), IsConsidered(false) {}
  3919. /// <summary>Gets the current expression if one is available.</summary>
  3920. Expr* getExprOrNull() const { return CurrentExpr ? *CurrentExpr : nullptr; }
  3921. /// <summary>Replaces the current expression.</summary>
  3922. void replaceExpr(Expr* e) { *CurrentExpr = e; }
  3923. };
  3924. HLSLExternalSource& m_source; // Source driving the iteration.
  3925. SmallVector<FlattenedTypeTracker, 4> m_typeTrackers; // Active stack of trackers.
  3926. bool m_draining; // Whether the iterator is meant to drain (will not generate new elements in incomplete arrays).
  3927. bool m_springLoaded; // Whether the current element has been set up by an incomplete array but hasn't been used yet.
  3928. unsigned int m_incompleteCount; // The number of elements in an incomplete array.
  3929. size_t m_typeDepth; // Depth of type analysis, to avoid stack overflows.
  3930. QualType m_firstType; // Name of first type found, used for diagnostics.
  3931. SourceLocation m_loc; // Location used for diagnostics.
  3932. static const size_t MaxTypeDepth = 100;
  3933. void advanceLeafTracker();
  3934. /// <summary>Consumes leaves.</summary>
  3935. void consumeLeaf();
  3936. /// <summary>Considers whether the leaf has a usable expression without consuming anything.</summary>
  3937. bool considerLeaf();
  3938. /// <summary>Pushes a tracker for the specified expression; returns true if there is something to evaluate.</summary>
  3939. bool pushTrackerForExpression(MultiExprArg::iterator expression);
  3940. /// <summary>Pushes a tracker for the specified type; returns true if there is something to evaluate.</summary>
  3941. bool pushTrackerForType(QualType type, _In_opt_ MultiExprArg::iterator expression);
  3942. public:
  3943. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  3944. FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source);
  3945. /// <summary>Constructs a FlattenedTypeIterator for the specified arguments.</summary>
  3946. FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source);
  3947. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  3948. QualType getCurrentElement() const;
  3949. /// <summary>Get the number of repeated current elements.</summary>
  3950. unsigned int getCurrentElementSize() const;
  3951. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  3952. bool hasCurrentElement() const;
  3953. /// <summary>Consumes count elements on this iterator.</summary>
  3954. void advanceCurrentElement(unsigned int count);
  3955. /// <summary>Counts the remaining elements in this iterator (consuming all elements).</summary>
  3956. unsigned int countRemaining();
  3957. /// <summary>Gets the current expression if one is available.</summary>
  3958. Expr* getExprOrNull() const { return m_typeTrackers.back().getExprOrNull(); }
  3959. /// <summary>Replaces the current expression.</summary>
  3960. void replaceExpr(Expr* e) { m_typeTrackers.back().replaceExpr(e); }
  3961. struct ComparisonResult
  3962. {
  3963. unsigned int LeftCount;
  3964. unsigned int RightCount;
  3965. /// <summary>Whether elements from right sequence are identical into left sequence elements.</summary>
  3966. bool AreElementsEqual;
  3967. /// <summary>Whether elements from right sequence can be converted into left sequence elements.</summary>
  3968. bool CanConvertElements;
  3969. /// <summary>Whether the elements can be converted and the sequences have the same length.</summary>
  3970. bool IsConvertibleAndEqualLength() const {
  3971. return LeftCount == RightCount;
  3972. }
  3973. /// <summary>Whether the elements can be converted but the left-hand sequence is longer.</summary>
  3974. bool IsConvertibleAndLeftLonger() const {
  3975. return CanConvertElements && LeftCount > RightCount;
  3976. }
  3977. bool IsRightLonger() const {
  3978. return RightCount > LeftCount;
  3979. }
  3980. };
  3981. static ComparisonResult CompareIterators(
  3982. HLSLExternalSource& source, SourceLocation loc,
  3983. FlattenedTypeIterator& leftIter, FlattenedTypeIterator& rightIter);
  3984. static ComparisonResult CompareTypes(
  3985. HLSLExternalSource& source,
  3986. SourceLocation leftLoc, SourceLocation rightLoc,
  3987. QualType left, QualType right);
  3988. // Compares the arguments to initialize the left type, modifying them if necessary.
  3989. static ComparisonResult CompareTypesForInit(
  3990. HLSLExternalSource& source, QualType left, MultiExprArg args,
  3991. SourceLocation leftLoc, SourceLocation rightLoc);
  3992. };
  3993. static
  3994. QualType GetFirstElementTypeFromDecl(const Decl* decl)
  3995. {
  3996. const ClassTemplateSpecializationDecl* specialization = dyn_cast<ClassTemplateSpecializationDecl>(decl);
  3997. if (specialization) {
  3998. const TemplateArgumentList& list = specialization->getTemplateArgs();
  3999. if (list.size()) {
  4000. return list[0].getAsType();
  4001. }
  4002. }
  4003. return QualType();
  4004. }
  4005. static
  4006. QualType GetFirstElementType(QualType type)
  4007. {
  4008. if (!type.isNull()) {
  4009. const RecordType* record = type->getAs<RecordType>();
  4010. if (record) {
  4011. return GetFirstElementTypeFromDecl(record->getDecl());
  4012. }
  4013. }
  4014. return QualType();
  4015. }
  4016. void HLSLExternalSource::AddBaseTypes()
  4017. {
  4018. DXASSERT(m_baseTypes[HLSLScalarType_unknown].isNull(), "otherwise unknown was initialized to an actual type");
  4019. m_baseTypes[HLSLScalarType_bool] = m_context->BoolTy;
  4020. m_baseTypes[HLSLScalarType_int] = m_context->IntTy;
  4021. m_baseTypes[HLSLScalarType_uint] = m_context->UnsignedIntTy;
  4022. m_baseTypes[HLSLScalarType_dword] = m_context->UnsignedIntTy;
  4023. m_baseTypes[HLSLScalarType_half] = m_context->getLangOpts().UseMinPrecision ? m_context->FloatTy : m_context->HalfTy;
  4024. m_baseTypes[HLSLScalarType_float] = m_context->FloatTy;
  4025. m_baseTypes[HLSLScalarType_double] = m_context->DoubleTy;
  4026. m_baseTypes[HLSLScalarType_float_min10] = m_context->HalfTy;
  4027. m_baseTypes[HLSLScalarType_float_min16] = m_context->HalfTy;
  4028. m_baseTypes[HLSLScalarType_int_min12] = m_context->ShortTy;
  4029. m_baseTypes[HLSLScalarType_int_min16] = m_context->ShortTy;
  4030. m_baseTypes[HLSLScalarType_uint_min16] = m_context->UnsignedShortTy;
  4031. m_baseTypes[HLSLScalarType_float_lit] = m_context->LitFloatTy;
  4032. m_baseTypes[HLSLScalarType_int_lit] = m_context->LitIntTy;
  4033. m_baseTypes[HLSLScalarType_int16] = m_context->ShortTy;
  4034. m_baseTypes[HLSLScalarType_int32] = m_context->IntTy;
  4035. m_baseTypes[HLSLScalarType_int64] = m_context->LongLongTy;
  4036. m_baseTypes[HLSLScalarType_uint16] = m_context->UnsignedShortTy;
  4037. m_baseTypes[HLSLScalarType_uint32] = m_context->UnsignedIntTy;
  4038. m_baseTypes[HLSLScalarType_uint64] = m_context->UnsignedLongLongTy;
  4039. m_baseTypes[HLSLScalarType_float16] = m_context->HalfTy;
  4040. m_baseTypes[HLSLScalarType_float32] = m_context->FloatTy;
  4041. m_baseTypes[HLSLScalarType_float64] = m_context->DoubleTy;
  4042. }
  4043. void HLSLExternalSource::AddHLSLScalarTypes()
  4044. {
  4045. DXASSERT(m_scalarTypes[HLSLScalarType_unknown].isNull(), "otherwise unknown was initialized to an actual type");
  4046. m_scalarTypes[HLSLScalarType_bool] = m_baseTypes[HLSLScalarType_bool];
  4047. m_scalarTypes[HLSLScalarType_int] = m_baseTypes[HLSLScalarType_int];
  4048. m_scalarTypes[HLSLScalarType_float] = m_baseTypes[HLSLScalarType_float];
  4049. m_scalarTypes[HLSLScalarType_double] = m_baseTypes[HLSLScalarType_double];
  4050. m_scalarTypes[HLSLScalarType_float_lit] = m_baseTypes[HLSLScalarType_float_lit];
  4051. m_scalarTypes[HLSLScalarType_int_lit] = m_baseTypes[HLSLScalarType_int_lit];
  4052. }
  4053. FunctionDecl* HLSLExternalSource::AddSubscriptSpecialization(
  4054. _In_ FunctionTemplateDecl* functionTemplate,
  4055. QualType objectElement,
  4056. const FindStructBasicTypeResult& findResult)
  4057. {
  4058. DXASSERT_NOMSG(functionTemplate != nullptr);
  4059. DXASSERT_NOMSG(!objectElement.isNull());
  4060. DXASSERT_NOMSG(findResult.Found());
  4061. DXASSERT(
  4062. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality > 0,
  4063. "otherwise the template shouldn't have an operator[] that the caller is trying to specialize");
  4064. // Subscript is templated only on its return type.
  4065. // Create the template argument.
  4066. bool isReadWrite = GetBasicKindProps(findResult.Kind) & BPROP_RWBUFFER;
  4067. QualType resultType = objectElement;
  4068. if (isReadWrite)
  4069. resultType = m_context->getLValueReferenceType(resultType, false);
  4070. else {
  4071. // Add const to avoid write.
  4072. resultType = m_context->getConstType(resultType);
  4073. resultType = m_context->getLValueReferenceType(resultType);
  4074. }
  4075. TemplateArgument templateArgument(resultType);
  4076. unsigned subscriptCardinality =
  4077. g_ArBasicKindsSubscripts[findResult.BasicKindsAsTypeIndex].SubscriptCardinality;
  4078. QualType subscriptIndexType =
  4079. subscriptCardinality == 1
  4080. ? m_context->UnsignedIntTy
  4081. : NewSimpleAggregateType(AR_TOBJ_VECTOR, AR_BASIC_UINT32, 0, 1,
  4082. subscriptCardinality);
  4083. // Look for an existing specialization.
  4084. void* InsertPos = nullptr;
  4085. FunctionDecl *SpecFunc = functionTemplate->findSpecialization(ArrayRef<TemplateArgument>(&templateArgument, 1), InsertPos);
  4086. if (SpecFunc != nullptr) {
  4087. return SpecFunc;
  4088. }
  4089. // Create a new specialization.
  4090. DeclContext* owner = functionTemplate->getDeclContext();
  4091. TemplateArgumentList templateArgumentList(
  4092. TemplateArgumentList::OnStackType::OnStack, &templateArgument, 1);
  4093. MultiLevelTemplateArgumentList mlTemplateArgumentList(templateArgumentList);
  4094. TemplateDeclInstantiator declInstantiator(*this->m_sema, owner, mlTemplateArgumentList);
  4095. const FunctionType *templateFnType = functionTemplate->getTemplatedDecl()->getType()->getAs<FunctionType>();
  4096. const FunctionProtoType *protoType = dyn_cast<FunctionProtoType>(templateFnType);
  4097. FunctionProtoType::ExtProtoInfo templateEPI = protoType->getExtProtoInfo();
  4098. QualType functionType = m_context->getFunctionType(
  4099. resultType, subscriptIndexType, templateEPI, None);
  4100. TypeSourceInfo *TInfo = m_context->CreateTypeSourceInfo(functionType, 0);
  4101. FunctionProtoTypeLoc Proto = TInfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  4102. IdentifierInfo* id = &m_context->Idents.get(StringRef("index"));
  4103. ParmVarDecl* indexerParam = ParmVarDecl::Create(
  4104. *m_context, nullptr, NoLoc, NoLoc, id, subscriptIndexType, nullptr, StorageClass::SC_None, nullptr);
  4105. QualType T = TInfo->getType();
  4106. DeclarationNameInfo NameInfo(functionTemplate->getDeclName(), NoLoc);
  4107. CXXMethodDecl* method = CXXMethodDecl::Create(
  4108. *m_context, dyn_cast<CXXRecordDecl>(owner), NoLoc, NameInfo, T, TInfo,
  4109. SC_Extern, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  4110. // Add subscript attribute
  4111. AddHLSLSubscriptAttr(method, *m_context, HLSubscriptOpcode::DefaultSubscript);
  4112. // Record this function template specialization.
  4113. method->setFunctionTemplateSpecialization(functionTemplate,
  4114. TemplateArgumentList::CreateCopy(*m_context, &templateArgument, 1), 0);
  4115. // Attach the parameters
  4116. indexerParam->setOwningFunction(method);
  4117. Proto.setParam(0, indexerParam);
  4118. method->setParams(ArrayRef<ParmVarDecl*>(indexerParam));
  4119. // Adjust access.
  4120. method->setAccess(AccessSpecifier::AS_public);
  4121. functionTemplate->setAccess(method->getAccess());
  4122. return method;
  4123. }
  4124. /// <summary>
  4125. /// This routine combines Source into Target. If you have a symmetric operation
  4126. /// and want to treat either side equally you should call it twice, swapping the
  4127. /// parameter order.
  4128. /// </summary>
  4129. static bool CombineObjectTypes(ArBasicKind Target, _In_ ArBasicKind Source,
  4130. _Out_opt_ ArBasicKind *pCombined) {
  4131. if (Target == Source) {
  4132. AssignOpt(Target, pCombined);
  4133. return true;
  4134. }
  4135. if (Source == AR_OBJECT_NULL) {
  4136. // NULL is valid for any object type.
  4137. AssignOpt(Target, pCombined);
  4138. return true;
  4139. }
  4140. switch (Target) {
  4141. AR_BASIC_ROBJECT_CASES:
  4142. if (Source == AR_OBJECT_STATEBLOCK) {
  4143. AssignOpt(Target, pCombined);
  4144. return true;
  4145. }
  4146. break;
  4147. AR_BASIC_TEXTURE_CASES:
  4148. AR_BASIC_NON_CMP_SAMPLER_CASES:
  4149. if (Source == AR_OBJECT_SAMPLER || Source == AR_OBJECT_STATEBLOCK) {
  4150. AssignOpt(Target, pCombined);
  4151. return true;
  4152. }
  4153. break;
  4154. case AR_OBJECT_SAMPLERCOMPARISON:
  4155. if (Source == AR_OBJECT_STATEBLOCK) {
  4156. AssignOpt(Target, pCombined);
  4157. return true;
  4158. }
  4159. break;
  4160. }
  4161. AssignOpt(AR_BASIC_UNKNOWN, pCombined);
  4162. return false;
  4163. }
  4164. static ArBasicKind LiteralToConcrete(Expr *litExpr,
  4165. HLSLExternalSource *pHLSLExternalSource) {
  4166. if (IntegerLiteral *intLit = dyn_cast<IntegerLiteral>(litExpr)) {
  4167. llvm::APInt val = intLit->getValue();
  4168. unsigned width = val.getActiveBits();
  4169. bool isNeg = val.isNegative();
  4170. if (isNeg) {
  4171. // Signed.
  4172. if (width <= 32)
  4173. return ArBasicKind::AR_BASIC_INT32;
  4174. else
  4175. return ArBasicKind::AR_BASIC_INT64;
  4176. } else {
  4177. // Unsigned.
  4178. if (width <= 32)
  4179. return ArBasicKind::AR_BASIC_UINT32;
  4180. else
  4181. return ArBasicKind::AR_BASIC_UINT64;
  4182. }
  4183. } else if (FloatingLiteral *floatLit = dyn_cast<FloatingLiteral>(litExpr)) {
  4184. llvm::APFloat val = floatLit->getValue();
  4185. unsigned width = val.getSizeInBits(val.getSemantics());
  4186. if (width <= 16)
  4187. return ArBasicKind::AR_BASIC_FLOAT16;
  4188. else if (width <= 32)
  4189. return ArBasicKind::AR_BASIC_FLOAT32;
  4190. else
  4191. return AR_BASIC_FLOAT64;
  4192. } else if (UnaryOperator *UO = dyn_cast<UnaryOperator>(litExpr)) {
  4193. ArBasicKind kind = LiteralToConcrete(UO->getSubExpr(), pHLSLExternalSource);
  4194. if (UO->getOpcode() == UnaryOperator::Opcode::UO_Minus) {
  4195. if (kind == ArBasicKind::AR_BASIC_UINT32)
  4196. kind = ArBasicKind::AR_BASIC_INT32;
  4197. else if (kind == ArBasicKind::AR_BASIC_UINT64)
  4198. kind = ArBasicKind::AR_BASIC_INT64;
  4199. }
  4200. return kind;
  4201. } else if (BinaryOperator *BO = dyn_cast<BinaryOperator>(litExpr)) {
  4202. ArBasicKind kind = LiteralToConcrete(BO->getLHS(), pHLSLExternalSource);
  4203. ArBasicKind kind1 = LiteralToConcrete(BO->getRHS(), pHLSLExternalSource);
  4204. CombineBasicTypes(kind, kind1, &kind);
  4205. return kind;
  4206. } else if (ParenExpr *PE = dyn_cast<ParenExpr>(litExpr)) {
  4207. ArBasicKind kind = LiteralToConcrete(PE->getSubExpr(), pHLSLExternalSource);
  4208. return kind;
  4209. } else if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(litExpr)) {
  4210. ArBasicKind kind = LiteralToConcrete(CO->getLHS(), pHLSLExternalSource);
  4211. ArBasicKind kind1 = LiteralToConcrete(CO->getRHS(), pHLSLExternalSource);
  4212. CombineBasicTypes(kind, kind1, &kind);
  4213. return kind;
  4214. } else if (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(litExpr)) {
  4215. // Use target Type for cast.
  4216. ArBasicKind kind = pHLSLExternalSource->GetTypeElementKind(IC->getType());
  4217. return kind;
  4218. } else {
  4219. // Could only be function call.
  4220. CallExpr *CE = cast<CallExpr>(litExpr);
  4221. // TODO: calculate the function call result.
  4222. if (CE->getNumArgs() == 1)
  4223. return LiteralToConcrete(CE->getArg(0), pHLSLExternalSource);
  4224. else {
  4225. ArBasicKind kind = LiteralToConcrete(CE->getArg(0), pHLSLExternalSource);
  4226. for (unsigned i = 1; i < CE->getNumArgs(); i++) {
  4227. ArBasicKind kindI = LiteralToConcrete(CE->getArg(i), pHLSLExternalSource);
  4228. CombineBasicTypes(kind, kindI, &kind);
  4229. }
  4230. return kind;
  4231. }
  4232. }
  4233. }
  4234. static bool SearchTypeInTable(ArBasicKind kind, const ArBasicKind *pCT) {
  4235. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4236. if (kind == *pCT)
  4237. return true;
  4238. pCT++;
  4239. }
  4240. return false;
  4241. }
  4242. static ArBasicKind
  4243. ConcreteLiteralType(Expr *litExpr, ArBasicKind kind,
  4244. unsigned uLegalComponentTypes,
  4245. HLSLExternalSource *pHLSLExternalSource) {
  4246. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[uLegalComponentTypes];
  4247. ArBasicKind defaultKind = *pCT;
  4248. // Use first none literal kind as defaultKind.
  4249. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4250. ArBasicKind kind = *pCT;
  4251. pCT++;
  4252. // Skip literal type.
  4253. if (kind == AR_BASIC_LITERAL_INT || kind == AR_BASIC_LITERAL_FLOAT)
  4254. continue;
  4255. defaultKind = kind;
  4256. break;
  4257. }
  4258. ArBasicKind litKind = LiteralToConcrete(litExpr, pHLSLExternalSource);
  4259. if (kind == AR_BASIC_LITERAL_INT) {
  4260. // Search for match first.
  4261. // For literal arg which don't affect return type, the search should always success.
  4262. // Unless use literal int on a float parameter.
  4263. if (SearchTypeInTable(litKind, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4264. return litKind;
  4265. // Return the default.
  4266. return defaultKind;
  4267. }
  4268. else {
  4269. // Search for float32 first.
  4270. if (SearchTypeInTable(AR_BASIC_FLOAT32, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4271. return AR_BASIC_FLOAT32;
  4272. // Search for float64.
  4273. if (SearchTypeInTable(AR_BASIC_FLOAT64, g_LegalIntrinsicCompTypes[uLegalComponentTypes]))
  4274. return AR_BASIC_FLOAT64;
  4275. // return default.
  4276. return defaultKind;
  4277. }
  4278. }
  4279. _Use_decl_annotations_ bool
  4280. HLSLExternalSource::IsValidateObjectElement(const HLSL_INTRINSIC *pIntrinsic,
  4281. QualType objectElement) {
  4282. IntrinsicOp op = static_cast<IntrinsicOp>(pIntrinsic->Op);
  4283. switch (op) {
  4284. case IntrinsicOp::MOP_Sample:
  4285. case IntrinsicOp::MOP_SampleBias:
  4286. case IntrinsicOp::MOP_SampleCmp:
  4287. case IntrinsicOp::MOP_SampleCmpLevelZero:
  4288. case IntrinsicOp::MOP_SampleGrad:
  4289. case IntrinsicOp::MOP_SampleLevel: {
  4290. ArBasicKind kind = GetTypeElementKind(objectElement);
  4291. UINT uBits = GET_BPROP_BITS(kind);
  4292. return IS_BASIC_FLOAT(kind) && uBits != BPROP_BITS64;
  4293. } break;
  4294. default:
  4295. return true;
  4296. }
  4297. }
  4298. _Use_decl_annotations_
  4299. bool HLSLExternalSource::MatchArguments(
  4300. const HLSL_INTRINSIC* pIntrinsic,
  4301. QualType objectElement,
  4302. ArrayRef<Expr *> Args,
  4303. QualType(&argTypes)[g_MaxIntrinsicParamCount + 1],
  4304. size_t* argCount)
  4305. {
  4306. DXASSERT_NOMSG(pIntrinsic != nullptr);
  4307. DXASSERT_NOMSG(argCount != nullptr);
  4308. static const UINT UnusedSize = 0xFF;
  4309. static const BYTE MaxIntrinsicArgs = g_MaxIntrinsicParamCount + 1;
  4310. #define CAB(_) { if (!(_)) return false; }
  4311. *argCount = 0;
  4312. ArTypeObjectKind Template[MaxIntrinsicArgs]; // Template type for each argument, AR_TOBJ_UNKNOWN if unspecified.
  4313. ArBasicKind ComponentType[MaxIntrinsicArgs]; // Component type for each argument, AR_BASIC_UNKNOWN if unspecified.
  4314. UINT uSpecialSize[IA_SPECIAL_SLOTS]; // row/col matching types, UNUSED_INDEX32 if unspecified.
  4315. // Reset infos
  4316. std::fill(Template, Template + _countof(Template), AR_TOBJ_UNKNOWN);
  4317. std::fill(ComponentType, ComponentType + _countof(ComponentType), AR_BASIC_UNKNOWN);
  4318. std::fill(uSpecialSize, uSpecialSize + _countof(uSpecialSize), UnusedSize);
  4319. const unsigned retArgIdx = 0;
  4320. unsigned retTypeIdx = pIntrinsic->pArgs[retArgIdx].uComponentTypeId;
  4321. // Populate the template for each argument.
  4322. ArrayRef<Expr*>::iterator iterArg = Args.begin();
  4323. ArrayRef<Expr*>::iterator end = Args.end();
  4324. unsigned int iArg = 1;
  4325. for (; iterArg != end; ++iterArg) {
  4326. Expr* pCallArg = *iterArg;
  4327. // No vararg support.
  4328. if (iArg >= _countof(Template) || iArg > pIntrinsic->uNumArgs) {
  4329. return false;
  4330. }
  4331. const HLSL_INTRINSIC_ARGUMENT *pIntrinsicArg;
  4332. pIntrinsicArg = &pIntrinsic->pArgs[iArg];
  4333. DXASSERT(pIntrinsicArg->uTemplateId != INTRIN_TEMPLATE_VARARGS, "no vararg support");
  4334. // If we are a type and templateID requires one, this isn't a match.
  4335. if (pIntrinsicArg->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  4336. ++iArg;
  4337. continue;
  4338. }
  4339. QualType pType = pCallArg->getType();
  4340. ArTypeObjectKind TypeInfoShapeKind = GetTypeObjectKind(pType);
  4341. ArBasicKind TypeInfoEltKind = GetTypeElementKind(pType);
  4342. if (TypeInfoEltKind == AR_BASIC_LITERAL_INT ||
  4343. TypeInfoEltKind == AR_BASIC_LITERAL_FLOAT) {
  4344. bool affectRetType =
  4345. (iArg != retArgIdx && retTypeIdx == pIntrinsicArg->uComponentTypeId);
  4346. // For literal arg which don't affect return type, find concrete type.
  4347. // For literal arg affect return type,
  4348. // TryEvalIntrinsic in CGHLSLMS.cpp will take care of cases
  4349. // where all argumentss are literal.
  4350. // CombineBasicTypes will cover the rest cases.
  4351. if (!affectRetType) {
  4352. TypeInfoEltKind = ConcreteLiteralType(
  4353. pCallArg, TypeInfoEltKind, pIntrinsicArg->uLegalComponentTypes, this);
  4354. }
  4355. }
  4356. UINT TypeInfoCols = 1;
  4357. UINT TypeInfoRows = 1;
  4358. switch (TypeInfoShapeKind) {
  4359. case AR_TOBJ_MATRIX:
  4360. GetRowsAndCols(pType, TypeInfoRows, TypeInfoCols);
  4361. break;
  4362. case AR_TOBJ_VECTOR:
  4363. TypeInfoCols = GetHLSLVecSize(pType);
  4364. break;
  4365. case AR_TOBJ_BASIC:
  4366. case AR_TOBJ_OBJECT:
  4367. break;
  4368. default:
  4369. return false; // no struct, arrays or void
  4370. }
  4371. DXASSERT(
  4372. pIntrinsicArg->uTemplateId < MaxIntrinsicArgs,
  4373. "otherwise intrinsic table was modified and g_MaxIntrinsicParamCount was not updated (or uTemplateId is out of bounds)");
  4374. // Compare template
  4375. if ((AR_TOBJ_UNKNOWN == Template[pIntrinsicArg->uTemplateId]) ||
  4376. (AR_TOBJ_SCALAR == Template[pIntrinsicArg->uTemplateId]) &&
  4377. (AR_TOBJ_VECTOR == TypeInfoShapeKind || AR_TOBJ_MATRIX == TypeInfoShapeKind)) {
  4378. Template[pIntrinsicArg->uTemplateId] = TypeInfoShapeKind;
  4379. }
  4380. else if (AR_TOBJ_SCALAR == TypeInfoShapeKind) {
  4381. if (AR_TOBJ_SCALAR != Template[pIntrinsicArg->uTemplateId] &&
  4382. AR_TOBJ_VECTOR != Template[pIntrinsicArg->uTemplateId] &&
  4383. AR_TOBJ_MATRIX != Template[pIntrinsicArg->uTemplateId]) {
  4384. return false;
  4385. }
  4386. }
  4387. else {
  4388. if (TypeInfoShapeKind != Template[pIntrinsicArg->uTemplateId]) {
  4389. return false;
  4390. }
  4391. }
  4392. DXASSERT(
  4393. pIntrinsicArg->uComponentTypeId < MaxIntrinsicArgs,
  4394. "otherwise intrinsic table was modified and MaxIntrinsicArgs was not updated (or uComponentTypeId is out of bounds)");
  4395. // Merge ComponentTypes
  4396. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsicArg->uComponentTypeId]) {
  4397. ComponentType[pIntrinsicArg->uComponentTypeId] = TypeInfoEltKind;
  4398. }
  4399. else {
  4400. if (!CombineBasicTypes(
  4401. ComponentType[pIntrinsicArg->uComponentTypeId],
  4402. TypeInfoEltKind,
  4403. &ComponentType[pIntrinsicArg->uComponentTypeId])) {
  4404. return false;
  4405. }
  4406. }
  4407. // Rows
  4408. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  4409. if (pIntrinsicArg->uRows >= IA_SPECIAL_BASE) {
  4410. UINT uSpecialId = pIntrinsicArg->uRows - IA_SPECIAL_BASE;
  4411. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4412. if (uSpecialSize[uSpecialId] > TypeInfoRows) {
  4413. uSpecialSize[uSpecialId] = TypeInfoRows;
  4414. }
  4415. }
  4416. else {
  4417. if (TypeInfoRows < pIntrinsicArg->uRows) {
  4418. return false;
  4419. }
  4420. }
  4421. }
  4422. // Columns
  4423. if (AR_TOBJ_SCALAR != TypeInfoShapeKind) {
  4424. if (pIntrinsicArg->uCols >= IA_SPECIAL_BASE) {
  4425. UINT uSpecialId = pIntrinsicArg->uCols - IA_SPECIAL_BASE;
  4426. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4427. if (uSpecialSize[uSpecialId] > TypeInfoCols) {
  4428. uSpecialSize[uSpecialId] = TypeInfoCols;
  4429. }
  4430. }
  4431. else {
  4432. if (TypeInfoCols < pIntrinsicArg->uCols) {
  4433. return false;
  4434. }
  4435. }
  4436. }
  4437. // Usage
  4438. if (pIntrinsicArg->qwUsage & AR_QUAL_OUT) {
  4439. if (pCallArg->getType().isConstQualified()) {
  4440. // Can't use a const type in an out or inout parameter.
  4441. return false;
  4442. }
  4443. }
  4444. iArg++;
  4445. }
  4446. DXASSERT(iterArg == end, "otherwise the argument list wasn't fully processed");
  4447. // Default template and component type for return value
  4448. if (pIntrinsic->pArgs[0].qwUsage && pIntrinsic->pArgs[0].uTemplateId != INTRIN_TEMPLATE_FROM_TYPE) {
  4449. CAB(pIntrinsic->pArgs[0].uTemplateId < MaxIntrinsicArgs);
  4450. if (AR_TOBJ_UNKNOWN == Template[pIntrinsic->pArgs[0].uTemplateId]) {
  4451. Template[pIntrinsic->pArgs[0].uTemplateId] =
  4452. g_LegalIntrinsicTemplates[pIntrinsic->pArgs[0].uLegalTemplates][0];
  4453. if (pIntrinsic->pArgs[0].uComponentTypeId != INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  4454. DXASSERT_NOMSG(pIntrinsic->pArgs[0].uComponentTypeId < MaxIntrinsicArgs);
  4455. if (AR_BASIC_UNKNOWN == ComponentType[pIntrinsic->pArgs[0].uComponentTypeId]) {
  4456. // half return type should map to float for min precision
  4457. if (pIntrinsic->pArgs[0].uLegalComponentTypes ==
  4458. LEGAL_INTRINSIC_COMPTYPES::LICOMPTYPE_FLOAT16 &&
  4459. getSema()->getLangOpts().UseMinPrecision) {
  4460. ComponentType[pIntrinsic->pArgs[0].uComponentTypeId] =
  4461. ArBasicKind::AR_BASIC_FLOAT32;
  4462. }
  4463. else {
  4464. ComponentType[pIntrinsic->pArgs[0].uComponentTypeId] =
  4465. g_LegalIntrinsicCompTypes[pIntrinsic->pArgs[0].uLegalComponentTypes][0];
  4466. }
  4467. }
  4468. }
  4469. }
  4470. }
  4471. // Make sure all template, component type, and texture type selections are valid.
  4472. for (size_t i = 0; i < Args.size() + 1; i++) {
  4473. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  4474. // Check template.
  4475. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  4476. continue; // Already verified that this is available.
  4477. }
  4478. const ArTypeObjectKind *pTT = g_LegalIntrinsicTemplates[pArgument->uLegalTemplates];
  4479. if (AR_TOBJ_UNKNOWN != Template[i]) {
  4480. if ((AR_TOBJ_SCALAR == Template[i]) && (AR_TOBJ_VECTOR == *pTT || AR_TOBJ_MATRIX == *pTT)) {
  4481. Template[i] = *pTT;
  4482. }
  4483. else {
  4484. while (AR_TOBJ_UNKNOWN != *pTT) {
  4485. if (Template[i] == *pTT)
  4486. break;
  4487. pTT++;
  4488. }
  4489. }
  4490. if (AR_TOBJ_UNKNOWN == *pTT)
  4491. return false;
  4492. }
  4493. else if (pTT) {
  4494. Template[i] = *pTT;
  4495. }
  4496. // Check component type.
  4497. const ArBasicKind *pCT = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes];
  4498. if (AR_BASIC_UNKNOWN != ComponentType[i]) {
  4499. while (AR_BASIC_UNKNOWN != *pCT && AR_BASIC_NOCAST != *pCT) {
  4500. if (ComponentType[i] == *pCT)
  4501. break;
  4502. pCT++;
  4503. }
  4504. // has to be a strict match
  4505. if (*pCT == AR_BASIC_NOCAST)
  4506. return false;
  4507. // If it is an object, see if it can be cast to the first thing in the
  4508. // list, otherwise move on to next intrinsic.
  4509. if (AR_TOBJ_OBJECT == Template[i] && AR_BASIC_UNKNOWN == *pCT) {
  4510. if (!CombineObjectTypes(g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0], ComponentType[i], nullptr)) {
  4511. return false;
  4512. }
  4513. }
  4514. if (AR_BASIC_UNKNOWN == *pCT) {
  4515. ComponentType[i] = g_LegalIntrinsicCompTypes[pArgument->uLegalComponentTypes][0];
  4516. }
  4517. }
  4518. else if (pCT) {
  4519. ComponentType[i] = *pCT;
  4520. }
  4521. }
  4522. // Default to a void return type.
  4523. argTypes[0] = m_context->VoidTy;
  4524. // Default specials sizes.
  4525. for (UINT i = 0; i < IA_SPECIAL_SLOTS; i++) {
  4526. if (UnusedSize == uSpecialSize[i]) {
  4527. uSpecialSize[i] = 1;
  4528. }
  4529. }
  4530. // Populate argTypes.
  4531. for (size_t i = 0; i <= Args.size(); i++) {
  4532. const HLSL_INTRINSIC_ARGUMENT *pArgument = &pIntrinsic->pArgs[i];
  4533. if (!pArgument->qwUsage)
  4534. continue;
  4535. QualType pNewType;
  4536. unsigned int quals = 0; // qualifications for this argument
  4537. // If we have no type, set it to our input type (templatized)
  4538. if (pArgument->uTemplateId == INTRIN_TEMPLATE_FROM_TYPE) {
  4539. // Use the templated input type, but resize it if the
  4540. // intrinsic's rows/cols isn't 0
  4541. if (pArgument->uRows && pArgument->uCols) {
  4542. UINT uRows, uCols;
  4543. // if type is overriden, use new type size, for
  4544. // now it only supports scalars
  4545. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  4546. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  4547. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4548. uRows = uSpecialSize[uSpecialId];
  4549. }
  4550. else if (pArgument->uRows > 0) {
  4551. uRows = pArgument->uRows;
  4552. }
  4553. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  4554. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  4555. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4556. uCols = uSpecialSize[uSpecialId];
  4557. }
  4558. else if (pArgument->uCols > 0) {
  4559. uCols = pArgument->uCols;
  4560. }
  4561. // 1x1 numeric outputs are always scalar.. since these
  4562. // are most flexible
  4563. if ((1 == uCols) && (1 == uRows)) {
  4564. pNewType = objectElement;
  4565. if (pNewType.isNull()) {
  4566. return false;
  4567. }
  4568. }
  4569. else {
  4570. // non-scalars unsupported right now since nothing
  4571. // uses it, would have to create either a type
  4572. // list for sub-structures or just resize the
  4573. // given type
  4574. // VH(E_NOTIMPL);
  4575. return false;
  4576. }
  4577. }
  4578. else {
  4579. DXASSERT_NOMSG(!pArgument->uRows && !pArgument->uCols);
  4580. if (objectElement.isNull()) {
  4581. return false;
  4582. }
  4583. pNewType = objectElement;
  4584. }
  4585. }
  4586. else {
  4587. ArBasicKind pEltType;
  4588. // ComponentType, if the Id is special then it gets the
  4589. // component type from the first component of the type, if
  4590. // we need more (for the second component, e.g.), then we
  4591. // can use more specials, etc.
  4592. if (pArgument->uComponentTypeId == INTRIN_COMPTYPE_FROM_TYPE_ELT0) {
  4593. if (objectElement.isNull()) {
  4594. return false;
  4595. }
  4596. pEltType = GetTypeElementKind(objectElement);
  4597. DXASSERT_VALIDBASICKIND(pEltType);
  4598. }
  4599. else {
  4600. pEltType = ComponentType[pArgument->uComponentTypeId];
  4601. DXASSERT_VALIDBASICKIND(pEltType);
  4602. }
  4603. UINT uRows, uCols;
  4604. // Rows
  4605. if (pArgument->uRows >= IA_SPECIAL_BASE) {
  4606. UINT uSpecialId = pArgument->uRows - IA_SPECIAL_BASE;
  4607. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4608. uRows = uSpecialSize[uSpecialId];
  4609. }
  4610. else {
  4611. uRows = pArgument->uRows;
  4612. }
  4613. // Cols
  4614. if (pArgument->uCols >= IA_SPECIAL_BASE) {
  4615. UINT uSpecialId = pArgument->uCols - IA_SPECIAL_BASE;
  4616. CAB(uSpecialId < IA_SPECIAL_SLOTS);
  4617. uCols = uSpecialSize[uSpecialId];
  4618. }
  4619. else {
  4620. uCols = pArgument->uCols;
  4621. }
  4622. // Verify that the final results are in bounds.
  4623. CAB(uCols > 0 && uCols <= MaxVectorSize && uRows > 0 && uRows <= MaxVectorSize);
  4624. // Const
  4625. UINT64 qwQual = pArgument->qwUsage & (AR_QUAL_ROWMAJOR | AR_QUAL_COLMAJOR);
  4626. if ((0 == i) || !(pArgument->qwUsage & AR_QUAL_OUT))
  4627. qwQual |= AR_QUAL_CONST;
  4628. DXASSERT_VALIDBASICKIND(pEltType);
  4629. pNewType = NewSimpleAggregateType(Template[pArgument->uTemplateId], pEltType, qwQual, uRows, uCols);
  4630. }
  4631. DXASSERT(!pNewType.isNull(), "otherwise there's a branch in this function that fails to assign this");
  4632. argTypes[i] = QualType(pNewType.getTypePtr(), quals);
  4633. // TODO: support out modifier
  4634. //if (pArgument->qwUsage & AR_QUAL_OUT) {
  4635. // argTypes[i] = m_context->getLValueReferenceType(argTypes[i].withConst());
  4636. //}
  4637. }
  4638. *argCount = iArg;
  4639. DXASSERT(
  4640. *argCount == pIntrinsic->uNumArgs,
  4641. "In the absence of varargs, a successful match would indicate we have as many arguments and types as the intrinsic template");
  4642. return true;
  4643. #undef CAB
  4644. }
  4645. _Use_decl_annotations_
  4646. HLSLExternalSource::FindStructBasicTypeResult
  4647. HLSLExternalSource::FindStructBasicType(DeclContext* functionDeclContext)
  4648. {
  4649. DXASSERT_NOMSG(functionDeclContext != nullptr);
  4650. // functionDeclContext may be a specialization of a template, such as AppendBuffer<MY_STRUCT>, or it
  4651. // may be a simple class, such as RWByteAddressBuffer.
  4652. const CXXRecordDecl* recordDecl = GetRecordDeclForBuiltInOrStruct(functionDeclContext);
  4653. // We save the caller from filtering out other types of context (like the translation unit itself).
  4654. if (recordDecl != nullptr)
  4655. {
  4656. int index = FindObjectBasicKindIndex(recordDecl);
  4657. if (index != -1) {
  4658. ArBasicKind kind = g_ArBasicKindsAsTypes[index];
  4659. return HLSLExternalSource::FindStructBasicTypeResult(kind, index);
  4660. }
  4661. }
  4662. return HLSLExternalSource::FindStructBasicTypeResult(AR_BASIC_UNKNOWN, 0);
  4663. }
  4664. _Use_decl_annotations_
  4665. void HLSLExternalSource::FindIntrinsicTable(DeclContext* functionDeclContext, const char** name, const HLSL_INTRINSIC** intrinsics, size_t* intrinsicCount)
  4666. {
  4667. DXASSERT_NOMSG(functionDeclContext != nullptr);
  4668. DXASSERT_NOMSG(name != nullptr);
  4669. DXASSERT_NOMSG(intrinsics != nullptr);
  4670. DXASSERT_NOMSG(intrinsicCount != nullptr);
  4671. *intrinsics = nullptr;
  4672. *intrinsicCount = 0;
  4673. *name = nullptr;
  4674. HLSLExternalSource::FindStructBasicTypeResult lookup = FindStructBasicType(functionDeclContext);
  4675. if (lookup.Found()) {
  4676. GetIntrinsicMethods(lookup.Kind, intrinsics, intrinsicCount);
  4677. *name = g_ArBasicTypeNames[lookup.Kind];
  4678. }
  4679. }
  4680. static bool BinaryOperatorKindIsArithmetic(BinaryOperatorKind Opc)
  4681. {
  4682. return
  4683. // Arithmetic operators.
  4684. Opc == BinaryOperatorKind::BO_Add ||
  4685. Opc == BinaryOperatorKind::BO_AddAssign ||
  4686. Opc == BinaryOperatorKind::BO_Sub ||
  4687. Opc == BinaryOperatorKind::BO_SubAssign ||
  4688. Opc == BinaryOperatorKind::BO_Rem ||
  4689. Opc == BinaryOperatorKind::BO_RemAssign ||
  4690. Opc == BinaryOperatorKind::BO_Div ||
  4691. Opc == BinaryOperatorKind::BO_DivAssign ||
  4692. Opc == BinaryOperatorKind::BO_Mul ||
  4693. Opc == BinaryOperatorKind::BO_MulAssign;
  4694. }
  4695. static bool BinaryOperatorKindIsCompoundAssignment(BinaryOperatorKind Opc)
  4696. {
  4697. return
  4698. // Arithmetic-and-assignment operators.
  4699. Opc == BinaryOperatorKind::BO_AddAssign ||
  4700. Opc == BinaryOperatorKind::BO_SubAssign ||
  4701. Opc == BinaryOperatorKind::BO_RemAssign ||
  4702. Opc == BinaryOperatorKind::BO_DivAssign ||
  4703. Opc == BinaryOperatorKind::BO_MulAssign ||
  4704. // Bitwise-and-assignment operators.
  4705. Opc == BinaryOperatorKind::BO_ShlAssign ||
  4706. Opc == BinaryOperatorKind::BO_ShrAssign ||
  4707. Opc == BinaryOperatorKind::BO_AndAssign ||
  4708. Opc == BinaryOperatorKind::BO_OrAssign ||
  4709. Opc == BinaryOperatorKind::BO_XorAssign;
  4710. }
  4711. static bool BinaryOperatorKindIsCompoundAssignmentForBool(BinaryOperatorKind Opc)
  4712. {
  4713. return
  4714. Opc == BinaryOperatorKind::BO_AndAssign ||
  4715. Opc == BinaryOperatorKind::BO_OrAssign ||
  4716. Opc == BinaryOperatorKind::BO_XorAssign;
  4717. }
  4718. static bool BinaryOperatorKindIsBitwise(BinaryOperatorKind Opc)
  4719. {
  4720. return
  4721. Opc == BinaryOperatorKind::BO_Shl ||
  4722. Opc == BinaryOperatorKind::BO_ShlAssign ||
  4723. Opc == BinaryOperatorKind::BO_Shr ||
  4724. Opc == BinaryOperatorKind::BO_ShrAssign ||
  4725. Opc == BinaryOperatorKind::BO_And ||
  4726. Opc == BinaryOperatorKind::BO_AndAssign ||
  4727. Opc == BinaryOperatorKind::BO_Or ||
  4728. Opc == BinaryOperatorKind::BO_OrAssign ||
  4729. Opc == BinaryOperatorKind::BO_Xor ||
  4730. Opc == BinaryOperatorKind::BO_XorAssign;
  4731. }
  4732. static bool BinaryOperatorKindIsBitwiseShift(BinaryOperatorKind Opc)
  4733. {
  4734. return
  4735. Opc == BinaryOperatorKind::BO_Shl ||
  4736. Opc == BinaryOperatorKind::BO_ShlAssign ||
  4737. Opc == BinaryOperatorKind::BO_Shr ||
  4738. Opc == BinaryOperatorKind::BO_ShrAssign;
  4739. }
  4740. static bool BinaryOperatorKindIsEqualComparison(BinaryOperatorKind Opc)
  4741. {
  4742. return
  4743. Opc == BinaryOperatorKind::BO_EQ ||
  4744. Opc == BinaryOperatorKind::BO_NE;
  4745. }
  4746. static bool BinaryOperatorKindIsOrderComparison(BinaryOperatorKind Opc)
  4747. {
  4748. return
  4749. Opc == BinaryOperatorKind::BO_LT ||
  4750. Opc == BinaryOperatorKind::BO_GT ||
  4751. Opc == BinaryOperatorKind::BO_LE ||
  4752. Opc == BinaryOperatorKind::BO_GE;
  4753. }
  4754. static bool BinaryOperatorKindIsComparison(BinaryOperatorKind Opc)
  4755. {
  4756. return BinaryOperatorKindIsEqualComparison(Opc) || BinaryOperatorKindIsOrderComparison(Opc);
  4757. }
  4758. static bool BinaryOperatorKindIsLogical(BinaryOperatorKind Opc)
  4759. {
  4760. return
  4761. Opc == BinaryOperatorKind::BO_LAnd ||
  4762. Opc == BinaryOperatorKind::BO_LOr;
  4763. }
  4764. static bool BinaryOperatorKindRequiresNumeric(BinaryOperatorKind Opc)
  4765. {
  4766. return
  4767. BinaryOperatorKindIsArithmetic(Opc) ||
  4768. BinaryOperatorKindIsOrderComparison(Opc) ||
  4769. BinaryOperatorKindIsLogical(Opc);
  4770. }
  4771. static bool BinaryOperatorKindRequiresIntegrals(BinaryOperatorKind Opc)
  4772. {
  4773. return BinaryOperatorKindIsBitwise(Opc);
  4774. }
  4775. static bool BinaryOperatorKindRequiresBoolAsNumeric(BinaryOperatorKind Opc)
  4776. {
  4777. return
  4778. BinaryOperatorKindIsBitwise(Opc) ||
  4779. BinaryOperatorKindIsArithmetic(Opc);
  4780. }
  4781. static bool UnaryOperatorKindRequiresIntegrals(UnaryOperatorKind Opc)
  4782. {
  4783. return Opc == UnaryOperatorKind::UO_Not;
  4784. }
  4785. static bool UnaryOperatorKindRequiresNumerics(UnaryOperatorKind Opc)
  4786. {
  4787. return
  4788. Opc == UnaryOperatorKind::UO_LNot ||
  4789. Opc == UnaryOperatorKind::UO_Plus ||
  4790. Opc == UnaryOperatorKind::UO_Minus ||
  4791. // The omission in fxc caused objects and structs to accept this.
  4792. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  4793. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  4794. }
  4795. static bool UnaryOperatorKindRequiresModifiableValue(UnaryOperatorKind Opc)
  4796. {
  4797. return
  4798. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  4799. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  4800. }
  4801. static bool UnaryOperatorKindRequiresBoolAsNumeric(UnaryOperatorKind Opc)
  4802. {
  4803. return
  4804. Opc == UnaryOperatorKind::UO_Not ||
  4805. Opc == UnaryOperatorKind::UO_Plus ||
  4806. Opc == UnaryOperatorKind::UO_Minus;
  4807. }
  4808. static bool UnaryOperatorKindDisallowsBool(UnaryOperatorKind Opc)
  4809. {
  4810. return
  4811. Opc == UnaryOperatorKind::UO_PreDec || Opc == UnaryOperatorKind::UO_PreInc ||
  4812. Opc == UnaryOperatorKind::UO_PostDec || Opc == UnaryOperatorKind::UO_PostInc;
  4813. }
  4814. static bool IsIncrementOp(UnaryOperatorKind Opc) {
  4815. return Opc == UnaryOperatorKind::UO_PreInc || Opc == UnaryOperatorKind::UO_PostInc;
  4816. }
  4817. /// <summary>
  4818. /// Checks whether the specified AR_TOBJ* value is a primitive or aggregate of primitive elements
  4819. /// (as opposed to a built-in object like a sampler or texture, or a void type).
  4820. /// </summary>
  4821. static bool IsObjectKindPrimitiveAggregate(ArTypeObjectKind value)
  4822. {
  4823. return
  4824. value == AR_TOBJ_BASIC ||
  4825. value == AR_TOBJ_MATRIX ||
  4826. value == AR_TOBJ_VECTOR;
  4827. }
  4828. static bool IsBasicKindIntegral(ArBasicKind value)
  4829. {
  4830. return IS_BASIC_AINT(value) || IS_BASIC_BOOL(value);
  4831. }
  4832. static bool IsBasicKindIntMinPrecision(ArBasicKind kind)
  4833. {
  4834. return IS_BASIC_SINT(kind) && IS_BASIC_MIN_PRECISION(kind);
  4835. }
  4836. static bool IsBasicKindNumeric(ArBasicKind value)
  4837. {
  4838. return GetBasicKindProps(value) & BPROP_NUMERIC;
  4839. }
  4840. ExprResult HLSLExternalSource::PromoteToIntIfBool(ExprResult& E)
  4841. {
  4842. // An invalid expression is pass-through at this point.
  4843. if (E.isInvalid())
  4844. {
  4845. return E;
  4846. }
  4847. QualType qt = E.get()->getType();
  4848. ArBasicKind elementKind = this->GetTypeElementKind(qt);
  4849. if (elementKind != AR_BASIC_BOOL)
  4850. {
  4851. return E;
  4852. }
  4853. // Construct a scalar/vector/matrix type with the same shape as E.
  4854. ArTypeObjectKind objectKind = this->GetTypeObjectKind(qt);
  4855. QualType targetType;
  4856. UINT colCount, rowCount;
  4857. GetRowsAndColsForAny(qt, rowCount, colCount);
  4858. targetType = NewSimpleAggregateType(objectKind, AR_BASIC_INT32, 0, rowCount, colCount)->getCanonicalTypeInternal();
  4859. if (E.get()->isLValue()) {
  4860. E = m_sema->DefaultLvalueConversion(E.get()).get();
  4861. }
  4862. switch (objectKind)
  4863. {
  4864. case AR_TOBJ_SCALAR:
  4865. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  4866. case AR_TOBJ_ARRAY:
  4867. case AR_TOBJ_VECTOR:
  4868. case AR_TOBJ_MATRIX:
  4869. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLCC_IntegralCast, E.get(), nullptr, ExprValueKind::VK_RValue);
  4870. default:
  4871. DXASSERT(false, "unsupported objectKind for PromoteToIntIfBool");
  4872. }
  4873. return E;
  4874. }
  4875. _Use_decl_annotations_
  4876. void HLSLExternalSource::CollectInfo(QualType type, ArTypeInfo* pTypeInfo)
  4877. {
  4878. DXASSERT_NOMSG(pTypeInfo != nullptr);
  4879. DXASSERT_NOMSG(!type.isNull());
  4880. memset(pTypeInfo, 0, sizeof(*pTypeInfo));
  4881. pTypeInfo->ObjKind = GetTypeElementKind(type);
  4882. pTypeInfo->EltKind = pTypeInfo->ObjKind;
  4883. pTypeInfo->ShapeKind = GetTypeObjectKind(type);
  4884. GetRowsAndColsForAny(type, pTypeInfo->uRows, pTypeInfo->uCols);
  4885. pTypeInfo->uTotalElts = pTypeInfo->uRows * pTypeInfo->uCols;
  4886. }
  4887. // Highest possible score (i.e., worst possible score).
  4888. static const UINT64 SCORE_MAX = 0xFFFFFFFFFFFFFFFF;
  4889. // Leave the first two score bits to handle higher-level
  4890. // variations like target type.
  4891. #define SCORE_MIN_SHIFT 2
  4892. // Space out scores to allow up to 128 parameters to
  4893. // vary between score sets spill into each other.
  4894. #define SCORE_PARAM_SHIFT 7
  4895. unsigned HLSLExternalSource::GetNumElements(QualType anyType) {
  4896. if (anyType.isNull()) {
  4897. return 0;
  4898. }
  4899. anyType = GetStructuralForm(anyType);
  4900. ArTypeObjectKind kind = GetTypeObjectKind(anyType);
  4901. switch (kind) {
  4902. case AR_TOBJ_BASIC:
  4903. case AR_TOBJ_OBJECT:
  4904. return 1;
  4905. case AR_TOBJ_COMPOUND: {
  4906. // TODO: consider caching this value for perf
  4907. unsigned total = 0;
  4908. const RecordType *recordType = anyType->getAs<RecordType>();
  4909. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  4910. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  4911. while (fi != fend) {
  4912. total += GetNumElements(fi->getType());
  4913. ++fi;
  4914. }
  4915. return total;
  4916. }
  4917. case AR_TOBJ_ARRAY:
  4918. case AR_TOBJ_MATRIX:
  4919. case AR_TOBJ_VECTOR:
  4920. return GetElementCount(anyType);
  4921. default:
  4922. DXASSERT(kind == AR_TOBJ_VOID,
  4923. "otherwise the type cannot be classified or is not supported");
  4924. return 0;
  4925. }
  4926. }
  4927. unsigned HLSLExternalSource::GetNumBasicElements(QualType anyType) {
  4928. if (anyType.isNull()) {
  4929. return 0;
  4930. }
  4931. anyType = GetStructuralForm(anyType);
  4932. ArTypeObjectKind kind = GetTypeObjectKind(anyType);
  4933. switch (kind) {
  4934. case AR_TOBJ_BASIC:
  4935. case AR_TOBJ_OBJECT:
  4936. return 1;
  4937. case AR_TOBJ_COMPOUND: {
  4938. // TODO: consider caching this value for perf
  4939. unsigned total = 0;
  4940. const RecordType *recordType = anyType->getAs<RecordType>();
  4941. RecordDecl * RD = recordType->getDecl();
  4942. // Take care base.
  4943. if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  4944. if (CXXRD->getNumBases()) {
  4945. for (const auto &I : CXXRD->bases()) {
  4946. const CXXRecordDecl *BaseDecl =
  4947. cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
  4948. if (BaseDecl->field_empty())
  4949. continue;
  4950. QualType parentTy = QualType(BaseDecl->getTypeForDecl(), 0);
  4951. total += GetNumBasicElements(parentTy);
  4952. }
  4953. }
  4954. }
  4955. RecordDecl::field_iterator fi = RD->field_begin();
  4956. RecordDecl::field_iterator fend = RD->field_end();
  4957. while (fi != fend) {
  4958. total += GetNumBasicElements(fi->getType());
  4959. ++fi;
  4960. }
  4961. return total;
  4962. }
  4963. case AR_TOBJ_ARRAY: {
  4964. unsigned arraySize = GetElementCount(anyType);
  4965. unsigned eltSize = GetNumBasicElements(
  4966. QualType(anyType->getArrayElementTypeNoTypeQual(), 0));
  4967. return arraySize * eltSize;
  4968. }
  4969. case AR_TOBJ_MATRIX:
  4970. case AR_TOBJ_VECTOR:
  4971. return GetElementCount(anyType);
  4972. default:
  4973. DXASSERT(kind == AR_TOBJ_VOID,
  4974. "otherwise the type cannot be classified or is not supported");
  4975. return 0;
  4976. }
  4977. }
  4978. unsigned HLSLExternalSource::GetNumConvertCheckElts(QualType leftType,
  4979. unsigned leftSize,
  4980. QualType rightType,
  4981. unsigned rightSize) {
  4982. // We can convert from a larger type to a smaller
  4983. // but not a smaller type to a larger so default
  4984. // to just comparing the destination size.
  4985. unsigned uElts = leftSize;
  4986. leftType = GetStructuralForm(leftType);
  4987. rightType = GetStructuralForm(rightType);
  4988. if (leftType->isArrayType() && rightType->isArrayType()) {
  4989. //
  4990. // If we're comparing arrays we don't
  4991. // need to compare every element of
  4992. // the arrays since all elements
  4993. // will have the same type.
  4994. // We only need to compare enough
  4995. // elements that we've tried every
  4996. // possible mix of dst and src elements.
  4997. //
  4998. // TODO: handle multidimensional arrays and arrays of arrays
  4999. QualType pDstElt = leftType->getAsArrayTypeUnsafe()->getElementType();
  5000. unsigned uDstEltSize = GetNumElements(pDstElt);
  5001. QualType pSrcElt = rightType->getAsArrayTypeUnsafe()->getElementType();
  5002. unsigned uSrcEltSize = GetNumElements(pSrcElt);
  5003. if (uDstEltSize == uSrcEltSize) {
  5004. uElts = uDstEltSize;
  5005. } else if (uDstEltSize > uSrcEltSize) {
  5006. // If one size is not an even multiple of the other we need to let the
  5007. // full compare run in order to try all alignments.
  5008. if (uSrcEltSize && (uDstEltSize % uSrcEltSize) == 0) {
  5009. uElts = uDstEltSize;
  5010. }
  5011. } else if (uDstEltSize && (uSrcEltSize % uDstEltSize) == 0) {
  5012. uElts = uSrcEltSize;
  5013. }
  5014. }
  5015. return uElts;
  5016. }
  5017. QualType HLSLExternalSource::GetNthElementType(QualType type, unsigned index) {
  5018. if (type.isNull()) {
  5019. return type;
  5020. }
  5021. ArTypeObjectKind kind = GetTypeObjectKind(type);
  5022. switch (kind) {
  5023. case AR_TOBJ_BASIC:
  5024. case AR_TOBJ_OBJECT:
  5025. return (index == 0) ? type : QualType();
  5026. case AR_TOBJ_COMPOUND: {
  5027. // TODO: consider caching this value for perf
  5028. const RecordType *recordType = type->getAsStructureType();
  5029. RecordDecl::field_iterator fi = recordType->getDecl()->field_begin();
  5030. RecordDecl::field_iterator fend = recordType->getDecl()->field_end();
  5031. while (fi != fend) {
  5032. if (!fi->getType().isNull()) {
  5033. unsigned subElements = GetNumElements(fi->getType());
  5034. if (index < subElements) {
  5035. return GetNthElementType(fi->getType(), index);
  5036. } else {
  5037. index -= subElements;
  5038. }
  5039. }
  5040. ++fi;
  5041. }
  5042. return QualType();
  5043. }
  5044. case AR_TOBJ_ARRAY: {
  5045. unsigned arraySize;
  5046. QualType elementType;
  5047. unsigned elementCount;
  5048. elementType = type.getNonReferenceType()->getAsArrayTypeUnsafe()->getElementType();
  5049. elementCount = GetElementCount(elementType);
  5050. if (index < elementCount) {
  5051. return GetNthElementType(elementType, index);
  5052. }
  5053. arraySize = GetArraySize(type);
  5054. if (index >= arraySize * elementCount) {
  5055. return QualType();
  5056. }
  5057. return GetNthElementType(elementType, index % elementCount);
  5058. }
  5059. case AR_TOBJ_MATRIX:
  5060. case AR_TOBJ_VECTOR:
  5061. return (index < GetElementCount(type)) ? GetMatrixOrVectorElementType(type)
  5062. : QualType();
  5063. default:
  5064. DXASSERT(kind == AR_TOBJ_VOID,
  5065. "otherwise the type cannot be classified or is not supported");
  5066. return QualType();
  5067. }
  5068. }
  5069. bool HLSLExternalSource::IsPromotion(ArBasicKind leftKind, ArBasicKind rightKind) {
  5070. // Eliminate exact matches first, then check for promotions.
  5071. if (leftKind == rightKind) {
  5072. return false;
  5073. }
  5074. switch (rightKind) {
  5075. case AR_BASIC_FLOAT16:
  5076. switch (leftKind) {
  5077. case AR_BASIC_FLOAT32:
  5078. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5079. case AR_BASIC_FLOAT64:
  5080. return true;
  5081. }
  5082. break;
  5083. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5084. switch (leftKind) {
  5085. case AR_BASIC_FLOAT32:
  5086. case AR_BASIC_FLOAT64:
  5087. return true;
  5088. }
  5089. break;
  5090. case AR_BASIC_FLOAT32:
  5091. switch (leftKind) {
  5092. case AR_BASIC_FLOAT64:
  5093. return true;
  5094. }
  5095. break;
  5096. case AR_BASIC_MIN10FLOAT:
  5097. switch (leftKind) {
  5098. case AR_BASIC_MIN16FLOAT:
  5099. case AR_BASIC_FLOAT16:
  5100. case AR_BASIC_FLOAT32:
  5101. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5102. case AR_BASIC_FLOAT64:
  5103. return true;
  5104. }
  5105. break;
  5106. case AR_BASIC_MIN16FLOAT:
  5107. switch (leftKind) {
  5108. case AR_BASIC_FLOAT16:
  5109. case AR_BASIC_FLOAT32:
  5110. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5111. case AR_BASIC_FLOAT64:
  5112. return true;
  5113. }
  5114. break;
  5115. case AR_BASIC_INT8:
  5116. case AR_BASIC_UINT8:
  5117. // For backwards compat we consider signed/unsigned the same.
  5118. switch (leftKind) {
  5119. case AR_BASIC_INT16:
  5120. case AR_BASIC_INT32:
  5121. case AR_BASIC_INT64:
  5122. case AR_BASIC_UINT16:
  5123. case AR_BASIC_UINT32:
  5124. case AR_BASIC_UINT64:
  5125. return true;
  5126. }
  5127. break;
  5128. case AR_BASIC_INT16:
  5129. case AR_BASIC_UINT16:
  5130. // For backwards compat we consider signed/unsigned the same.
  5131. switch (leftKind) {
  5132. case AR_BASIC_INT32:
  5133. case AR_BASIC_INT64:
  5134. case AR_BASIC_UINT32:
  5135. case AR_BASIC_UINT64:
  5136. return true;
  5137. }
  5138. break;
  5139. case AR_BASIC_INT32:
  5140. case AR_BASIC_UINT32:
  5141. // For backwards compat we consider signed/unsigned the same.
  5142. switch (leftKind) {
  5143. case AR_BASIC_INT64:
  5144. case AR_BASIC_UINT64:
  5145. return true;
  5146. }
  5147. break;
  5148. case AR_BASIC_MIN12INT:
  5149. switch (leftKind) {
  5150. case AR_BASIC_MIN16INT:
  5151. case AR_BASIC_INT32:
  5152. case AR_BASIC_INT64:
  5153. return true;
  5154. }
  5155. break;
  5156. case AR_BASIC_MIN16INT:
  5157. switch (leftKind) {
  5158. case AR_BASIC_INT32:
  5159. case AR_BASIC_INT64:
  5160. return true;
  5161. }
  5162. break;
  5163. case AR_BASIC_MIN16UINT:
  5164. switch (leftKind) {
  5165. case AR_BASIC_UINT32:
  5166. case AR_BASIC_UINT64:
  5167. return true;
  5168. }
  5169. break;
  5170. }
  5171. return false;
  5172. }
  5173. bool HLSLExternalSource::IsCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  5174. // Eliminate exact matches first, then check for casts.
  5175. if (leftKind == rightKind) {
  5176. return false;
  5177. }
  5178. //
  5179. // All minimum-bits types are only considered matches of themselves
  5180. // and thus are not in this table.
  5181. //
  5182. switch (leftKind) {
  5183. case AR_BASIC_LITERAL_INT:
  5184. switch (rightKind) {
  5185. case AR_BASIC_INT8:
  5186. case AR_BASIC_INT16:
  5187. case AR_BASIC_INT32:
  5188. case AR_BASIC_INT64:
  5189. case AR_BASIC_UINT8:
  5190. case AR_BASIC_UINT16:
  5191. case AR_BASIC_UINT32:
  5192. case AR_BASIC_UINT64:
  5193. return false;
  5194. }
  5195. break;
  5196. case AR_BASIC_INT8:
  5197. switch (rightKind) {
  5198. // For backwards compat we consider signed/unsigned the same.
  5199. case AR_BASIC_LITERAL_INT:
  5200. case AR_BASIC_UINT8:
  5201. return false;
  5202. }
  5203. break;
  5204. case AR_BASIC_INT16:
  5205. switch (rightKind) {
  5206. // For backwards compat we consider signed/unsigned the same.
  5207. case AR_BASIC_LITERAL_INT:
  5208. case AR_BASIC_UINT16:
  5209. return false;
  5210. }
  5211. break;
  5212. case AR_BASIC_INT32:
  5213. switch (rightKind) {
  5214. // For backwards compat we consider signed/unsigned the same.
  5215. case AR_BASIC_LITERAL_INT:
  5216. case AR_BASIC_UINT32:
  5217. return false;
  5218. }
  5219. break;
  5220. case AR_BASIC_INT64:
  5221. switch (rightKind) {
  5222. // For backwards compat we consider signed/unsigned the same.
  5223. case AR_BASIC_LITERAL_INT:
  5224. case AR_BASIC_UINT64:
  5225. return false;
  5226. }
  5227. break;
  5228. case AR_BASIC_UINT8:
  5229. switch (rightKind) {
  5230. // For backwards compat we consider signed/unsigned the same.
  5231. case AR_BASIC_LITERAL_INT:
  5232. case AR_BASIC_INT8:
  5233. return false;
  5234. }
  5235. break;
  5236. case AR_BASIC_UINT16:
  5237. switch (rightKind) {
  5238. // For backwards compat we consider signed/unsigned the same.
  5239. case AR_BASIC_LITERAL_INT:
  5240. case AR_BASIC_INT16:
  5241. return false;
  5242. }
  5243. break;
  5244. case AR_BASIC_UINT32:
  5245. switch (rightKind) {
  5246. // For backwards compat we consider signed/unsigned the same.
  5247. case AR_BASIC_LITERAL_INT:
  5248. case AR_BASIC_INT32:
  5249. return false;
  5250. }
  5251. break;
  5252. case AR_BASIC_UINT64:
  5253. switch (rightKind) {
  5254. // For backwards compat we consider signed/unsigned the same.
  5255. case AR_BASIC_LITERAL_INT:
  5256. case AR_BASIC_INT64:
  5257. return false;
  5258. }
  5259. break;
  5260. case AR_BASIC_LITERAL_FLOAT:
  5261. switch (rightKind) {
  5262. case AR_BASIC_LITERAL_FLOAT:
  5263. case AR_BASIC_FLOAT16:
  5264. case AR_BASIC_FLOAT32:
  5265. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5266. case AR_BASIC_FLOAT64:
  5267. return false;
  5268. }
  5269. break;
  5270. case AR_BASIC_FLOAT16:
  5271. switch (rightKind) {
  5272. case AR_BASIC_LITERAL_FLOAT:
  5273. return false;
  5274. }
  5275. break;
  5276. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5277. switch (rightKind) {
  5278. case AR_BASIC_LITERAL_FLOAT:
  5279. return false;
  5280. }
  5281. break;
  5282. case AR_BASIC_FLOAT32:
  5283. switch (rightKind) {
  5284. case AR_BASIC_LITERAL_FLOAT:
  5285. return false;
  5286. }
  5287. break;
  5288. case AR_BASIC_FLOAT64:
  5289. switch (rightKind) {
  5290. case AR_BASIC_LITERAL_FLOAT:
  5291. return false;
  5292. }
  5293. break;
  5294. }
  5295. return true;
  5296. }
  5297. bool HLSLExternalSource::IsIntCast(ArBasicKind leftKind, ArBasicKind rightKind) {
  5298. // Eliminate exact matches first, then check for casts.
  5299. if (leftKind == rightKind) {
  5300. return false;
  5301. }
  5302. //
  5303. // All minimum-bits types are only considered matches of themselves
  5304. // and thus are not in this table.
  5305. //
  5306. switch (leftKind) {
  5307. case AR_BASIC_LITERAL_INT:
  5308. switch (rightKind) {
  5309. case AR_BASIC_INT8:
  5310. case AR_BASIC_INT16:
  5311. case AR_BASIC_INT32:
  5312. case AR_BASIC_INT64:
  5313. case AR_BASIC_UINT8:
  5314. case AR_BASIC_UINT16:
  5315. case AR_BASIC_UINT32:
  5316. case AR_BASIC_UINT64:
  5317. return false;
  5318. }
  5319. break;
  5320. case AR_BASIC_INT8:
  5321. case AR_BASIC_INT16:
  5322. case AR_BASIC_INT32:
  5323. case AR_BASIC_INT64:
  5324. case AR_BASIC_UINT8:
  5325. case AR_BASIC_UINT16:
  5326. case AR_BASIC_UINT32:
  5327. case AR_BASIC_UINT64:
  5328. switch (rightKind) {
  5329. case AR_BASIC_LITERAL_INT:
  5330. return false;
  5331. }
  5332. break;
  5333. case AR_BASIC_LITERAL_FLOAT:
  5334. switch (rightKind) {
  5335. case AR_BASIC_LITERAL_FLOAT:
  5336. case AR_BASIC_FLOAT16:
  5337. case AR_BASIC_FLOAT32:
  5338. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5339. case AR_BASIC_FLOAT64:
  5340. return false;
  5341. }
  5342. break;
  5343. case AR_BASIC_FLOAT16:
  5344. case AR_BASIC_FLOAT32:
  5345. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  5346. case AR_BASIC_FLOAT64:
  5347. switch (rightKind) {
  5348. case AR_BASIC_LITERAL_FLOAT:
  5349. return false;
  5350. }
  5351. break;
  5352. }
  5353. return true;
  5354. }
  5355. UINT64 HLSLExternalSource::ScoreCast(QualType pLType, QualType pRType)
  5356. {
  5357. if (pLType.getCanonicalType() == pRType.getCanonicalType()) {
  5358. return 0;
  5359. }
  5360. UINT64 uScore = 0;
  5361. UINT uLSize = GetNumElements(pLType);
  5362. UINT uRSize = GetNumElements(pRType);
  5363. UINT uCompareSize;
  5364. bool bLCast = false;
  5365. bool bRCast = false;
  5366. bool bLIntCast = false;
  5367. bool bRIntCast = false;
  5368. bool bLPromo = false;
  5369. bool bRPromo = false;
  5370. uCompareSize = GetNumConvertCheckElts(pLType, uLSize, pRType, uRSize);
  5371. if (uCompareSize > uRSize) {
  5372. uCompareSize = uRSize;
  5373. }
  5374. for (UINT i = 0; i < uCompareSize; i++) {
  5375. ArBasicKind LeftElementKind, RightElementKind;
  5376. ArBasicKind CombinedKind = AR_BASIC_BOOL;
  5377. QualType leftSub = GetNthElementType(pLType, i);
  5378. QualType rightSub = GetNthElementType(pRType, i);
  5379. ArTypeObjectKind leftKind = GetTypeObjectKind(leftSub);
  5380. ArTypeObjectKind rightKind = GetTypeObjectKind(rightSub);
  5381. LeftElementKind = GetTypeElementKind(leftSub);
  5382. RightElementKind = GetTypeElementKind(rightSub);
  5383. // CollectInfo is called with AR_TINFO_ALLOW_OBJECTS, and the resulting
  5384. // information needed is the ShapeKind, EltKind and ObjKind.
  5385. if (!leftSub.isNull() && !rightSub.isNull() && leftKind != AR_TOBJ_INVALID && rightKind != AR_TOBJ_INVALID) {
  5386. bool bCombine;
  5387. if (leftKind == AR_TOBJ_OBJECT || rightKind == AR_TOBJ_OBJECT) {
  5388. DXASSERT(rightKind == AR_TOBJ_OBJECT, "otherwise prior check is incorrect");
  5389. ArBasicKind LeftObjKind = LeftElementKind; // actually LeftElementKind would have been the element
  5390. ArBasicKind RightObjKind = RightElementKind;
  5391. LeftElementKind = LeftObjKind;
  5392. RightElementKind = RightObjKind;
  5393. if (leftKind != rightKind) {
  5394. bCombine = false;
  5395. }
  5396. else if (!(bCombine = CombineObjectTypes(LeftObjKind, RightObjKind, &CombinedKind))) {
  5397. bCombine = CombineObjectTypes(RightObjKind, LeftObjKind, &CombinedKind);
  5398. }
  5399. }
  5400. else {
  5401. bCombine = CombineBasicTypes(LeftElementKind, RightElementKind, &CombinedKind);
  5402. }
  5403. if (bCombine && IsPromotion(LeftElementKind, CombinedKind)) {
  5404. bLPromo = true;
  5405. }
  5406. else if (!bCombine || IsCast(LeftElementKind, CombinedKind)) {
  5407. bLCast = true;
  5408. }
  5409. else if (IsIntCast(LeftElementKind, CombinedKind)) {
  5410. bLIntCast = true;
  5411. }
  5412. if (bCombine && IsPromotion(CombinedKind, RightElementKind)) {
  5413. bRPromo = true;
  5414. } else if (!bCombine || IsCast(CombinedKind, RightElementKind)) {
  5415. bRCast = true;
  5416. } else if (IsIntCast(CombinedKind, RightElementKind)) {
  5417. bRIntCast = true;
  5418. }
  5419. } else {
  5420. bLCast = true;
  5421. bRCast = true;
  5422. }
  5423. }
  5424. #define SCORE_COND(shift, cond) { \
  5425. if (cond) uScore += 1UI64 << (SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * shift); }
  5426. SCORE_COND(0, uRSize < uLSize);
  5427. SCORE_COND(1, bLPromo);
  5428. SCORE_COND(2, bRPromo);
  5429. SCORE_COND(3, bLIntCast);
  5430. SCORE_COND(4, bRIntCast);
  5431. SCORE_COND(5, bLCast);
  5432. SCORE_COND(6, bRCast);
  5433. SCORE_COND(7, uLSize < uRSize);
  5434. #undef SCORE_COND
  5435. // Make sure our scores fit in a UINT64.
  5436. C_ASSERT(SCORE_MIN_SHIFT + SCORE_PARAM_SHIFT * 8 <= 64);
  5437. return uScore;
  5438. }
  5439. UINT64 HLSLExternalSource::ScoreImplicitConversionSequence(const ImplicitConversionSequence *ics) {
  5440. DXASSERT(ics, "otherwise conversion has not been initialized");
  5441. if (!ics->isInitialized()) {
  5442. return 0;
  5443. }
  5444. if (!ics->isStandard()) {
  5445. return SCORE_MAX;
  5446. }
  5447. QualType fromType = ics->Standard.getFromType();
  5448. QualType toType = ics->Standard.getToType(2); // final type
  5449. return ScoreCast(toType, fromType);
  5450. }
  5451. UINT64 HLSLExternalSource::ScoreFunction(OverloadCandidateSet::iterator &Cand) {
  5452. // Ignore target version mismatches.
  5453. // in/out considerations have been taken care of by viability.
  5454. // 'this' considerations don't matter without inheritance, other
  5455. // than lookup and viability.
  5456. UINT64 result = 0;
  5457. for (unsigned convIdx = 0; convIdx < Cand->NumConversions; ++convIdx) {
  5458. UINT64 score;
  5459. score = ScoreImplicitConversionSequence(Cand->Conversions + convIdx);
  5460. if (score == SCORE_MAX) {
  5461. return SCORE_MAX;
  5462. }
  5463. result += score;
  5464. score = ScoreImplicitConversionSequence(Cand->OutConversions + convIdx);
  5465. if (score == SCORE_MAX) {
  5466. return SCORE_MAX;
  5467. }
  5468. result += score;
  5469. }
  5470. return result;
  5471. }
  5472. OverloadingResult HLSLExternalSource::GetBestViableFunction(
  5473. SourceLocation Loc,
  5474. OverloadCandidateSet& set,
  5475. OverloadCandidateSet::iterator& Best)
  5476. {
  5477. UINT64 bestScore = SCORE_MAX;
  5478. unsigned scoreMatch = 0;
  5479. Best = set.end();
  5480. if (set.size() == 1 && set.begin()->Viable) {
  5481. Best = set.begin();
  5482. return OR_Success;
  5483. }
  5484. for (OverloadCandidateSet::iterator Cand = set.begin(); Cand != set.end(); ++Cand) {
  5485. if (Cand->Viable) {
  5486. UINT64 score = ScoreFunction(Cand);
  5487. if (score != SCORE_MAX) {
  5488. if (score == bestScore) {
  5489. ++scoreMatch;
  5490. } else if (score < bestScore) {
  5491. Best = Cand;
  5492. scoreMatch = 1;
  5493. bestScore = score;
  5494. }
  5495. }
  5496. }
  5497. }
  5498. if (Best == set.end()) {
  5499. return OR_No_Viable_Function;
  5500. }
  5501. if (scoreMatch > 1) {
  5502. Best = set.end();
  5503. return OR_Ambiguous;
  5504. }
  5505. // No need to check for deleted functions to yield OR_Deleted.
  5506. return OR_Success;
  5507. }
  5508. /// <summary>
  5509. /// Initializes the specified <paramref name="initSequence" /> describing how
  5510. /// <paramref name="Entity" /> is initialized with <paramref name="Args" />.
  5511. /// </summary>
  5512. /// <param name="Entity">Entity being initialized; a variable, return result, etc.</param>
  5513. /// <param name="Kind">Kind of initialization: copying, list-initializing, constructing, etc.</param>
  5514. /// <param name="Args">Arguments to the initialization.</param>
  5515. /// <param name="TopLevelOfInitList">Whether this is the top-level of an initialization list.</param>
  5516. /// <param name="initSequence">Initialization sequence description to initialize.</param>
  5517. void HLSLExternalSource::InitializeInitSequenceForHLSL(
  5518. const InitializedEntity& Entity,
  5519. const InitializationKind& Kind,
  5520. MultiExprArg Args,
  5521. bool TopLevelOfInitList,
  5522. _Inout_ InitializationSequence* initSequence)
  5523. {
  5524. DXASSERT_NOMSG(initSequence != nullptr);
  5525. // In HLSL there are no default initializers, eg float4x4 m();
  5526. if (Kind.getKind() == InitializationKind::IK_Default) {
  5527. return;
  5528. }
  5529. // Value initializers occur for temporaries with empty parens or braces.
  5530. if (Kind.getKind() == InitializationKind::IK_Value) {
  5531. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_type_empty_init) << Entity.getType();
  5532. SilenceSequenceDiagnostics(initSequence);
  5533. return;
  5534. }
  5535. // If we have a DirectList, we should have a single InitListExprClass argument.
  5536. DXASSERT(
  5537. Kind.getKind() != InitializationKind::IK_DirectList ||
  5538. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass),
  5539. "otherwise caller is passing in incorrect initialization configuration");
  5540. bool isCast = Kind.isCStyleCast();
  5541. QualType destType = Entity.getType();
  5542. ArTypeObjectKind destShape = GetTypeObjectKind(destType);
  5543. // Direct initialization occurs for explicit constructor arguments.
  5544. // E.g.: http://en.cppreference.com/w/cpp/language/direct_initialization
  5545. if (Kind.getKind() == InitializationKind::IK_Direct && destShape == AR_TOBJ_COMPOUND &&
  5546. !Kind.isCStyleOrFunctionalCast()) {
  5547. m_sema->Diag(Kind.getLocation(), diag::err_hlsl_require_numeric_base_for_ctor);
  5548. SilenceSequenceDiagnostics(initSequence);
  5549. return;
  5550. }
  5551. bool flatten =
  5552. (Kind.getKind() == InitializationKind::IK_Direct && !isCast) ||
  5553. Kind.getKind() == InitializationKind::IK_DirectList ||
  5554. (Args.size() == 1 && Args.front()->getStmtClass() == Stmt::InitListExprClass);
  5555. if (flatten) {
  5556. // TODO: InitializationSequence::Perform in SemaInit should take the arity of incomplete
  5557. // array types to adjust the value - we do calculate this as part of type analysis.
  5558. // Until this is done, s_arr_i_f arr_struct_none[] = { }; succeeds when it should instead fail.
  5559. FlattenedTypeIterator::ComparisonResult comparisonResult =
  5560. FlattenedTypeIterator::CompareTypesForInit(
  5561. *this, destType, Args,
  5562. Kind.getLocation(), Kind.getLocation());
  5563. if (comparisonResult.IsConvertibleAndEqualLength() ||
  5564. (isCast && comparisonResult.IsConvertibleAndLeftLonger()))
  5565. {
  5566. initSequence->AddListInitializationStep(destType);
  5567. }
  5568. else
  5569. {
  5570. SourceLocation diagLocation;
  5571. if (Args.size() > 0)
  5572. {
  5573. diagLocation = Args.front()->getLocStart();
  5574. }
  5575. else
  5576. {
  5577. diagLocation = Entity.getDiagLoc();
  5578. }
  5579. m_sema->Diag(diagLocation,
  5580. diag::err_vector_incorrect_num_initializers)
  5581. << (comparisonResult.RightCount < comparisonResult.LeftCount)
  5582. << comparisonResult.LeftCount << comparisonResult.RightCount;
  5583. SilenceSequenceDiagnostics(initSequence);
  5584. }
  5585. }
  5586. else {
  5587. DXASSERT(Args.size() == 1, "otherwise this was mis-parsed or should be a list initialization");
  5588. Expr* firstArg = Args.front();
  5589. if (IsExpressionBinaryComma(firstArg)) {
  5590. m_sema->Diag(firstArg->getExprLoc(), diag::warn_hlsl_comma_in_init);
  5591. }
  5592. ExprResult expr = ExprResult(firstArg);
  5593. Sema::CheckedConversionKind cck = Kind.isExplicitCast() ?
  5594. Sema::CheckedConversionKind::CCK_CStyleCast :
  5595. Sema::CheckedConversionKind::CCK_ImplicitConversion;
  5596. unsigned int msg = 0;
  5597. CastKind castKind;
  5598. CXXCastPath basePath;
  5599. SourceRange range = Kind.getRange();
  5600. ImplicitConversionSequence ics;
  5601. ics.setStandard();
  5602. bool castWorked = TryStaticCastForHLSL(
  5603. expr, destType, cck, range, msg, castKind, basePath, ListInitializationFalse, SuppressWarningsFalse, SuppressErrorsTrue, &ics.Standard);
  5604. if (castWorked) {
  5605. if (destType.getCanonicalType() ==
  5606. firstArg->getType().getCanonicalType() &&
  5607. (ics.Standard).First != ICK_Lvalue_To_Rvalue) {
  5608. initSequence->AddCAssignmentStep(destType);
  5609. } else {
  5610. initSequence->AddConversionSequenceStep(ics, destType.getNonReferenceType(), TopLevelOfInitList);
  5611. }
  5612. }
  5613. else {
  5614. initSequence->SetFailed(InitializationSequence::FK_ConversionFailed);
  5615. }
  5616. }
  5617. }
  5618. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  5619. const QualType& sourceType,
  5620. const QualType& targetType,
  5621. bool explicitConversion)
  5622. {
  5623. DXASSERT_NOMSG(!sourceType.isNull());
  5624. DXASSERT_NOMSG(!targetType.isNull());
  5625. ArTypeInfo sourceTypeInfo;
  5626. ArTypeInfo targetTypeInfo;
  5627. GetConversionForm(sourceType, explicitConversion, &sourceTypeInfo);
  5628. GetConversionForm(targetType, explicitConversion, &targetTypeInfo);
  5629. if (sourceTypeInfo.EltKind != targetTypeInfo.EltKind)
  5630. {
  5631. return false;
  5632. }
  5633. bool isVecMatTrunc = sourceTypeInfo.ShapeKind == AR_TOBJ_VECTOR &&
  5634. targetTypeInfo.ShapeKind == AR_TOBJ_BASIC;
  5635. if (sourceTypeInfo.ShapeKind != targetTypeInfo.ShapeKind &&
  5636. !isVecMatTrunc)
  5637. {
  5638. return false;
  5639. }
  5640. if (sourceTypeInfo.ShapeKind == AR_TOBJ_OBJECT &&
  5641. sourceTypeInfo.ObjKind == targetTypeInfo.ObjKind) {
  5642. return true;
  5643. }
  5644. // Same struct is eqaul.
  5645. if (sourceTypeInfo.ShapeKind == AR_TOBJ_COMPOUND &&
  5646. sourceType.getCanonicalType().getUnqualifiedType() ==
  5647. targetType.getCanonicalType().getUnqualifiedType()) {
  5648. return true;
  5649. }
  5650. // DerivedFrom is less.
  5651. if (sourceTypeInfo.ShapeKind == AR_TOBJ_COMPOUND ||
  5652. GetTypeObjectKind(sourceType) == AR_TOBJ_COMPOUND) {
  5653. const RecordType *targetRT = targetType->getAsStructureType();
  5654. if (!targetRT)
  5655. targetRT = dyn_cast<RecordType>(targetType);
  5656. const RecordType *sourceRT = sourceType->getAsStructureType();
  5657. if (!sourceRT)
  5658. sourceRT = dyn_cast<RecordType>(sourceType);
  5659. if (targetRT && sourceRT) {
  5660. RecordDecl *targetRD = targetRT->getDecl();
  5661. RecordDecl *sourceRD = sourceRT->getDecl();
  5662. const CXXRecordDecl *targetCXXRD = dyn_cast<CXXRecordDecl>(targetRD);
  5663. const CXXRecordDecl *sourceCXXRD = dyn_cast<CXXRecordDecl>(sourceRD);
  5664. if (targetCXXRD && sourceCXXRD) {
  5665. if (sourceCXXRD->isDerivedFrom(targetCXXRD))
  5666. return true;
  5667. }
  5668. }
  5669. }
  5670. if (sourceTypeInfo.ShapeKind != AR_TOBJ_SCALAR &&
  5671. sourceTypeInfo.ShapeKind != AR_TOBJ_VECTOR &&
  5672. sourceTypeInfo.ShapeKind != AR_TOBJ_MATRIX)
  5673. {
  5674. return false;
  5675. }
  5676. return targetTypeInfo.uTotalElts <= sourceTypeInfo.uTotalElts;
  5677. }
  5678. bool HLSLExternalSource::IsConversionToLessOrEqualElements(
  5679. const ExprResult& sourceExpr,
  5680. const QualType& targetType,
  5681. bool explicitConversion)
  5682. {
  5683. if (sourceExpr.isInvalid() || targetType.isNull())
  5684. {
  5685. return false;
  5686. }
  5687. return IsConversionToLessOrEqualElements(sourceExpr.get()->getType(), targetType, explicitConversion);
  5688. }
  5689. bool HLSLExternalSource::IsTypeNumeric(QualType type, UINT* count)
  5690. {
  5691. DXASSERT_NOMSG(!type.isNull());
  5692. DXASSERT_NOMSG(count != nullptr);
  5693. *count = 0;
  5694. UINT subCount = 0;
  5695. ArTypeObjectKind shapeKind = GetTypeObjectKind(type);
  5696. switch (shapeKind)
  5697. {
  5698. case AR_TOBJ_ARRAY:
  5699. if (IsTypeNumeric(m_context->getAsArrayType(type)->getElementType(), &subCount))
  5700. {
  5701. *count = subCount * GetArraySize(type);
  5702. return true;
  5703. }
  5704. return false;
  5705. case AR_TOBJ_COMPOUND:
  5706. {
  5707. UINT maxCount = 0;
  5708. { // Determine maximum count to prevent infinite loop on incomplete array
  5709. FlattenedTypeIterator itCount(SourceLocation(), type, *this);
  5710. maxCount = itCount.countRemaining();
  5711. if (!maxCount) {
  5712. return false; // empty struct.
  5713. }
  5714. }
  5715. FlattenedTypeIterator it(SourceLocation(), type, *this);
  5716. while (it.hasCurrentElement()) {
  5717. bool isFieldNumeric = IsTypeNumeric(it.getCurrentElement(), &subCount);
  5718. if (!isFieldNumeric) {
  5719. return false;
  5720. }
  5721. if (*count >= maxCount) {
  5722. // this element is an incomplete array at the end; iterator will not advance past this element.
  5723. // don't add to *count either, so *count will represent minimum size of the structure.
  5724. break;
  5725. }
  5726. *count += (subCount * it.getCurrentElementSize());
  5727. it.advanceCurrentElement(it.getCurrentElementSize());
  5728. }
  5729. return true;
  5730. }
  5731. default:
  5732. DXASSERT(false, "unreachable");
  5733. case AR_TOBJ_BASIC:
  5734. case AR_TOBJ_MATRIX:
  5735. case AR_TOBJ_VECTOR:
  5736. *count = GetElementCount(type);
  5737. return IsBasicKindNumeric(GetTypeElementKind(type));
  5738. case AR_TOBJ_OBJECT:
  5739. return false;
  5740. }
  5741. }
  5742. enum MatrixMemberAccessError {
  5743. MatrixMemberAccessError_None, // No errors found.
  5744. MatrixMemberAccessError_BadFormat, // Formatting error (non-digit).
  5745. MatrixMemberAccessError_MixingRefs, // Mix of zero-based and one-based references.
  5746. MatrixMemberAccessError_Empty, // No members specified.
  5747. MatrixMemberAccessError_ZeroInOneBased, // A zero was used in a one-based reference.
  5748. MatrixMemberAccessError_FourInZeroBased, // A four was used in a zero-based reference.
  5749. MatrixMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  5750. };
  5751. static
  5752. MatrixMemberAccessError TryConsumeMatrixDigit(const char*& memberText, uint32_t* value)
  5753. {
  5754. DXASSERT_NOMSG(memberText != nullptr);
  5755. DXASSERT_NOMSG(value != nullptr);
  5756. if ('0' <= *memberText && *memberText <= '9')
  5757. {
  5758. *value = (*memberText) - '0';
  5759. }
  5760. else
  5761. {
  5762. return MatrixMemberAccessError_BadFormat;
  5763. }
  5764. memberText++;
  5765. return MatrixMemberAccessError_None;
  5766. }
  5767. static
  5768. MatrixMemberAccessError TryParseMatrixMemberAccess(_In_z_ const char* memberText, _Out_ MatrixMemberAccessPositions* value)
  5769. {
  5770. DXASSERT_NOMSG(memberText != nullptr);
  5771. DXASSERT_NOMSG(value != nullptr);
  5772. MatrixMemberAccessPositions result;
  5773. bool zeroBasedDecided = false;
  5774. bool zeroBased = false;
  5775. // Set the output value to invalid to allow early exits when errors are found.
  5776. value->IsValid = 0;
  5777. // Assume this is true until proven otherwise.
  5778. result.IsValid = 1;
  5779. result.Count = 0;
  5780. while (*memberText)
  5781. {
  5782. // Check for a leading underscore.
  5783. if (*memberText != '_')
  5784. {
  5785. return MatrixMemberAccessError_BadFormat;
  5786. }
  5787. ++memberText;
  5788. // Check whether we have an 'm' or a digit.
  5789. if (*memberText == 'm')
  5790. {
  5791. if (zeroBasedDecided && !zeroBased)
  5792. {
  5793. return MatrixMemberAccessError_MixingRefs;
  5794. }
  5795. zeroBased = true;
  5796. zeroBasedDecided = true;
  5797. ++memberText;
  5798. }
  5799. else if (!('0' <= *memberText && *memberText <= '9'))
  5800. {
  5801. return MatrixMemberAccessError_BadFormat;
  5802. }
  5803. else
  5804. {
  5805. if (zeroBasedDecided && zeroBased)
  5806. {
  5807. return MatrixMemberAccessError_MixingRefs;
  5808. }
  5809. zeroBased = false;
  5810. zeroBasedDecided = true;
  5811. }
  5812. // Consume two digits for the position.
  5813. uint32_t rowPosition;
  5814. uint32_t colPosition;
  5815. MatrixMemberAccessError digitError;
  5816. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &rowPosition)))
  5817. {
  5818. return digitError;
  5819. }
  5820. if (MatrixMemberAccessError_None != (digitError = TryConsumeMatrixDigit(memberText, &colPosition)))
  5821. {
  5822. return digitError;
  5823. }
  5824. // Look for specific common errors (developer likely mixed up reference style).
  5825. if (zeroBased)
  5826. {
  5827. if (rowPosition == 4 || colPosition == 4)
  5828. {
  5829. return MatrixMemberAccessError_FourInZeroBased;
  5830. }
  5831. }
  5832. else
  5833. {
  5834. if (rowPosition == 0 || colPosition == 0)
  5835. {
  5836. return MatrixMemberAccessError_ZeroInOneBased;
  5837. }
  5838. // SetPosition will use zero-based indices.
  5839. --rowPosition;
  5840. --colPosition;
  5841. }
  5842. if (result.Count == 4)
  5843. {
  5844. return MatrixMemberAccessError_TooManyPositions;
  5845. }
  5846. result.SetPosition(result.Count, rowPosition, colPosition);
  5847. result.Count++;
  5848. }
  5849. if (result.Count == 0)
  5850. {
  5851. return MatrixMemberAccessError_Empty;
  5852. }
  5853. *value = result;
  5854. return MatrixMemberAccessError_None;
  5855. }
  5856. bool HLSLExternalSource::LookupMatrixMemberExprForHLSL(
  5857. Expr& BaseExpr,
  5858. DeclarationName MemberName,
  5859. bool IsArrow,
  5860. SourceLocation OpLoc,
  5861. SourceLocation MemberLoc,
  5862. ExprResult* result)
  5863. {
  5864. DXASSERT_NOMSG(result != nullptr);
  5865. QualType BaseType = BaseExpr.getType();
  5866. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  5867. // Assume failure.
  5868. *result = ExprError();
  5869. if (GetTypeObjectKind(BaseType) != AR_TOBJ_MATRIX)
  5870. {
  5871. return false;
  5872. }
  5873. QualType elementType;
  5874. UINT rowCount, colCount;
  5875. GetRowsAndCols(BaseType, rowCount, colCount);
  5876. elementType = GetMatrixOrVectorElementType(BaseType);
  5877. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  5878. const char *memberText = member->getNameStart();
  5879. MatrixMemberAccessPositions positions;
  5880. MatrixMemberAccessError memberAccessError;
  5881. unsigned msg = 0;
  5882. memberAccessError = TryParseMatrixMemberAccess(memberText, &positions);
  5883. switch (memberAccessError)
  5884. {
  5885. case MatrixMemberAccessError_BadFormat:
  5886. msg = diag::err_hlsl_matrix_member_bad_format;
  5887. break;
  5888. case MatrixMemberAccessError_Empty:
  5889. msg = diag::err_hlsl_matrix_member_empty;
  5890. break;
  5891. case MatrixMemberAccessError_FourInZeroBased:
  5892. msg = diag::err_hlsl_matrix_member_four_in_zero_based;
  5893. break;
  5894. case MatrixMemberAccessError_MixingRefs:
  5895. msg = diag::err_hlsl_matrix_member_mixing_refs;
  5896. break;
  5897. case MatrixMemberAccessError_None:
  5898. msg = 0;
  5899. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  5900. // Check the position with the type now.
  5901. for (unsigned int i = 0; i < positions.Count; i++)
  5902. {
  5903. uint32_t rowPos, colPos;
  5904. positions.GetPosition(i, &rowPos, &colPos);
  5905. if (rowPos >= rowCount || colPos >= colCount)
  5906. {
  5907. msg = diag::err_hlsl_matrix_member_out_of_bounds;
  5908. break;
  5909. }
  5910. }
  5911. break;
  5912. case MatrixMemberAccessError_TooManyPositions:
  5913. msg = diag::err_hlsl_matrix_member_too_many_positions;
  5914. break;
  5915. case MatrixMemberAccessError_ZeroInOneBased:
  5916. msg = diag::err_hlsl_matrix_member_zero_in_one_based;
  5917. break;
  5918. default:
  5919. llvm_unreachable("Unknown MatrixMemberAccessError value");
  5920. }
  5921. if (msg != 0)
  5922. {
  5923. m_sema->Diag(MemberLoc, msg) << memberText;
  5924. // It's possible that it's a simple out-of-bounds condition. In this case,
  5925. // generate the member access expression with the correct arity and continue
  5926. // processing.
  5927. if (!positions.IsValid)
  5928. {
  5929. return true;
  5930. }
  5931. }
  5932. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  5933. // Consume elements
  5934. QualType resultType;
  5935. if (positions.Count == 1)
  5936. resultType = elementType;
  5937. else
  5938. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  5939. // Add qualifiers from BaseType.
  5940. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  5941. ExprValueKind VK =
  5942. positions.ContainsDuplicateElements() ? VK_RValue :
  5943. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  5944. ExtMatrixElementExpr* matrixExpr = new (m_context)ExtMatrixElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  5945. *result = matrixExpr;
  5946. return true;
  5947. }
  5948. enum VectorMemberAccessError {
  5949. VectorMemberAccessError_None, // No errors found.
  5950. VectorMemberAccessError_BadFormat, // Formatting error (not in 'rgba' or 'xyzw').
  5951. VectorMemberAccessError_MixingStyles, // Mix of rgba and xyzw swizzle styles.
  5952. VectorMemberAccessError_Empty, // No members specified.
  5953. VectorMemberAccessError_TooManyPositions, // Too many positions (more than four) were specified.
  5954. };
  5955. static
  5956. VectorMemberAccessError TryConsumeVectorDigit(const char*& memberText, uint32_t* value, bool &rgbaStyle) {
  5957. DXASSERT_NOMSG(memberText != nullptr);
  5958. DXASSERT_NOMSG(value != nullptr);
  5959. rgbaStyle = false;
  5960. switch (*memberText) {
  5961. case 'r':
  5962. rgbaStyle = true;
  5963. case 'x':
  5964. *value = 0;
  5965. break;
  5966. case 'g':
  5967. rgbaStyle = true;
  5968. case 'y':
  5969. *value = 1;
  5970. break;
  5971. case 'b':
  5972. rgbaStyle = true;
  5973. case 'z':
  5974. *value = 2;
  5975. break;
  5976. case 'a':
  5977. rgbaStyle = true;
  5978. case 'w':
  5979. *value = 3;
  5980. break;
  5981. default:
  5982. return VectorMemberAccessError_BadFormat;
  5983. }
  5984. memberText++;
  5985. return VectorMemberAccessError_None;
  5986. }
  5987. static
  5988. VectorMemberAccessError TryParseVectorMemberAccess(_In_z_ const char* memberText, _Out_ VectorMemberAccessPositions* value) {
  5989. DXASSERT_NOMSG(memberText != nullptr);
  5990. DXASSERT_NOMSG(value != nullptr);
  5991. VectorMemberAccessPositions result;
  5992. bool rgbaStyleDecided = false;
  5993. bool rgbaStyle = false;
  5994. // Set the output value to invalid to allow early exits when errors are found.
  5995. value->IsValid = 0;
  5996. // Assume this is true until proven otherwise.
  5997. result.IsValid = 1;
  5998. result.Count = 0;
  5999. while (*memberText) {
  6000. // Consume one character for the swizzle.
  6001. uint32_t colPosition;
  6002. VectorMemberAccessError digitError;
  6003. bool rgbaStyleTmp = false;
  6004. if (VectorMemberAccessError_None != (digitError = TryConsumeVectorDigit(memberText, &colPosition, rgbaStyleTmp))) {
  6005. return digitError;
  6006. }
  6007. if (rgbaStyleDecided && rgbaStyleTmp != rgbaStyle) {
  6008. return VectorMemberAccessError_MixingStyles;
  6009. }
  6010. else {
  6011. rgbaStyleDecided = true;
  6012. rgbaStyle = rgbaStyleTmp;
  6013. }
  6014. if (result.Count == 4) {
  6015. return VectorMemberAccessError_TooManyPositions;
  6016. }
  6017. result.SetPosition(result.Count, colPosition);
  6018. result.Count++;
  6019. }
  6020. if (result.Count == 0) {
  6021. return VectorMemberAccessError_Empty;
  6022. }
  6023. *value = result;
  6024. return VectorMemberAccessError_None;
  6025. }
  6026. bool HLSLExternalSource::LookupVectorMemberExprForHLSL(
  6027. Expr& BaseExpr,
  6028. DeclarationName MemberName,
  6029. bool IsArrow,
  6030. SourceLocation OpLoc,
  6031. SourceLocation MemberLoc,
  6032. ExprResult* result) {
  6033. DXASSERT_NOMSG(result != nullptr);
  6034. QualType BaseType = BaseExpr.getType();
  6035. DXASSERT(!BaseType.isNull(), "otherwise caller should have stopped analysis much earlier");
  6036. // Assume failure.
  6037. *result = ExprError();
  6038. if (GetTypeObjectKind(BaseType) != AR_TOBJ_VECTOR) {
  6039. return false;
  6040. }
  6041. QualType elementType;
  6042. UINT colCount = GetHLSLVecSize(BaseType);
  6043. elementType = GetMatrixOrVectorElementType(BaseType);
  6044. IdentifierInfo *member = MemberName.getAsIdentifierInfo();
  6045. const char *memberText = member->getNameStart();
  6046. VectorMemberAccessPositions positions;
  6047. VectorMemberAccessError memberAccessError;
  6048. unsigned msg = 0;
  6049. memberAccessError = TryParseVectorMemberAccess(memberText, &positions);
  6050. switch (memberAccessError) {
  6051. case VectorMemberAccessError_BadFormat:
  6052. msg = diag::err_hlsl_vector_member_bad_format;
  6053. break;
  6054. case VectorMemberAccessError_Empty:
  6055. msg = diag::err_hlsl_vector_member_empty;
  6056. break;
  6057. case VectorMemberAccessError_MixingStyles:
  6058. msg = diag::err_ext_vector_component_name_mixedsets;
  6059. break;
  6060. case VectorMemberAccessError_None:
  6061. msg = 0;
  6062. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6063. // Check the position with the type now.
  6064. for (unsigned int i = 0; i < positions.Count; i++) {
  6065. uint32_t colPos;
  6066. positions.GetPosition(i, &colPos);
  6067. if (colPos >= colCount) {
  6068. msg = diag::err_hlsl_vector_member_out_of_bounds;
  6069. break;
  6070. }
  6071. }
  6072. break;
  6073. case VectorMemberAccessError_TooManyPositions:
  6074. msg = diag::err_hlsl_vector_member_too_many_positions;
  6075. break;
  6076. default:
  6077. llvm_unreachable("Unknown VectorMemberAccessError value");
  6078. }
  6079. if (msg != 0) {
  6080. m_sema->Diag(MemberLoc, msg) << memberText;
  6081. // It's possible that it's a simple out-of-bounds condition. In this case,
  6082. // generate the member access expression with the correct arity and continue
  6083. // processing.
  6084. if (!positions.IsValid) {
  6085. return true;
  6086. }
  6087. }
  6088. DXASSERT(positions.IsValid, "otherwise an error should have been returned");
  6089. // Consume elements
  6090. QualType resultType;
  6091. if (positions.Count == 1)
  6092. resultType = elementType;
  6093. else
  6094. resultType = NewSimpleAggregateType(AR_TOBJ_UNKNOWN, GetTypeElementKind(elementType), 0, OneRow, positions.Count);
  6095. // Add qualifiers from BaseType.
  6096. resultType = m_context->getQualifiedType(resultType, BaseType.getQualifiers());
  6097. ExprValueKind VK =
  6098. positions.ContainsDuplicateElements() ? VK_RValue :
  6099. (IsArrow ? VK_LValue : BaseExpr.getValueKind());
  6100. HLSLVectorElementExpr* vectorExpr = new (m_context)HLSLVectorElementExpr(resultType, VK, &BaseExpr, *member, MemberLoc, positions);
  6101. *result = vectorExpr;
  6102. return true;
  6103. }
  6104. ExprResult HLSLExternalSource::MaybeConvertScalarToVector(_In_ clang::Expr* E) {
  6105. DXASSERT_NOMSG(E != nullptr);
  6106. ArBasicKind basic = GetTypeElementKind(E->getType());
  6107. if (!IS_BASIC_PRIMITIVE(basic)) {
  6108. return E;
  6109. }
  6110. ArTypeObjectKind kind = GetTypeObjectKind(E->getType());
  6111. if (kind != AR_TOBJ_SCALAR) {
  6112. return E;
  6113. }
  6114. QualType targetType = NewSimpleAggregateType(AR_TOBJ_VECTOR, basic, 0, 1, 1);
  6115. return ImplicitCastExpr::Create(*m_context, targetType, CastKind::CK_HLSLVectorSplat, E, nullptr, E->getValueKind());
  6116. }
  6117. static clang::CastKind ImplicitConversionKindToCastKind(
  6118. clang::ImplicitConversionKind ICK,
  6119. ArBasicKind FromKind,
  6120. ArBasicKind ToKind) {
  6121. // TODO: Shouldn't we have more specific ICK enums so we don't have to re-evaluate
  6122. // based on from/to kinds in order to determine CastKind?
  6123. // There's a FIXME note in PerformImplicitConversion that calls out exactly this
  6124. // problem.
  6125. switch (ICK) {
  6126. case ICK_Integral_Promotion:
  6127. case ICK_Integral_Conversion:
  6128. return CK_IntegralCast;
  6129. case ICK_Floating_Promotion:
  6130. case ICK_Floating_Conversion:
  6131. return CK_FloatingCast;
  6132. case ICK_Floating_Integral:
  6133. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_AINT(ToKind))
  6134. return CK_FloatingToIntegral;
  6135. else if ((IS_BASIC_AINT(FromKind) || IS_BASIC_BOOL(FromKind)) && IS_BASIC_FLOAT(ToKind))
  6136. return CK_IntegralToFloating;
  6137. break;
  6138. case ICK_Boolean_Conversion:
  6139. if (IS_BASIC_FLOAT(FromKind) && IS_BASIC_BOOL(ToKind))
  6140. return CK_FloatingToBoolean;
  6141. else if (IS_BASIC_AINT(FromKind) && IS_BASIC_BOOL(ToKind))
  6142. return CK_IntegralToBoolean;
  6143. break;
  6144. }
  6145. return CK_Invalid;
  6146. }
  6147. static clang::CastKind ConvertToComponentCastKind(clang::CastKind CK) {
  6148. switch (CK) {
  6149. case CK_IntegralCast:
  6150. return CK_HLSLCC_IntegralCast;
  6151. case CK_FloatingCast:
  6152. return CK_HLSLCC_FloatingCast;
  6153. case CK_FloatingToIntegral:
  6154. return CK_HLSLCC_FloatingToIntegral;
  6155. case CK_IntegralToFloating:
  6156. return CK_HLSLCC_IntegralToFloating;
  6157. case CK_FloatingToBoolean:
  6158. return CK_HLSLCC_FloatingToBoolean;
  6159. case CK_IntegralToBoolean:
  6160. return CK_HLSLCC_IntegralToBoolean;
  6161. }
  6162. return CK_Invalid;
  6163. }
  6164. clang::Expr *HLSLExternalSource::HLSLImpCastToScalar(
  6165. _In_ clang::Sema* self,
  6166. _In_ clang::Expr* From,
  6167. ArTypeObjectKind FromShape,
  6168. ArBasicKind EltKind)
  6169. {
  6170. clang::CastKind CK = CK_Invalid;
  6171. if (AR_TOBJ_MATRIX == FromShape)
  6172. CK = CK_HLSLMatrixToScalarCast;
  6173. if (AR_TOBJ_VECTOR == FromShape)
  6174. CK = CK_HLSLVectorToScalarCast;
  6175. if (CK_Invalid != CK) {
  6176. return self->ImpCastExprToType(From,
  6177. NewSimpleAggregateType(AR_TOBJ_BASIC, EltKind, 0, 1, 1), CK, From->getValueKind()).get();
  6178. }
  6179. return From;
  6180. }
  6181. clang::ExprResult HLSLExternalSource::PerformHLSLConversion(
  6182. _In_ clang::Expr* From,
  6183. _In_ clang::QualType targetType,
  6184. _In_ const clang::StandardConversionSequence &SCS,
  6185. _In_ clang::Sema::CheckedConversionKind CCK)
  6186. {
  6187. QualType sourceType = From->getType();
  6188. sourceType = GetStructuralForm(sourceType);
  6189. targetType = GetStructuralForm(targetType);
  6190. ArTypeInfo SourceInfo, TargetInfo;
  6191. CollectInfo(sourceType, &SourceInfo);
  6192. CollectInfo(targetType, &TargetInfo);
  6193. clang::CastKind CK = CK_Invalid;
  6194. QualType intermediateTarget;
  6195. // TODO: construct vector/matrix and component cast expressions
  6196. switch (SCS.Second) {
  6197. case ICK_Flat_Conversion: {
  6198. // TODO: determine how to handle individual component conversions:
  6199. // - have an array of conversions for ComponentConversion in SCS?
  6200. // convert that to an array of casts under a special kind of flat
  6201. // flat conversion node? What do component conversion casts cast
  6202. // from? We don't have a From expression for individiual components.
  6203. From = m_sema->ImpCastExprToType(From, targetType.getUnqualifiedType(), CK_FlatConversion, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6204. break;
  6205. }
  6206. case ICK_HLSL_Derived_To_Base: {
  6207. From = m_sema->ImpCastExprToType(From, targetType.getUnqualifiedType(), CK_HLSLDerivedToBase, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6208. break;
  6209. }
  6210. case ICK_HLSLVector_Splat: {
  6211. // 1. optionally convert from vec1 or mat1x1 to scalar
  6212. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6213. // 2. optionally convert component type
  6214. if (ICK_Identity != SCS.ComponentConversion) {
  6215. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6216. if (CK_Invalid != CK) {
  6217. From = m_sema->ImpCastExprToType(From,
  6218. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6219. }
  6220. }
  6221. // 3. splat scalar to final vector or matrix
  6222. CK = CK_Invalid;
  6223. if (AR_TOBJ_VECTOR == TargetInfo.ShapeKind)
  6224. CK = CK_HLSLVectorSplat;
  6225. else if (AR_TOBJ_MATRIX == TargetInfo.ShapeKind)
  6226. CK = CK_HLSLMatrixSplat;
  6227. if (CK_Invalid != CK) {
  6228. From = m_sema->ImpCastExprToType(From,
  6229. NewSimpleAggregateType(TargetInfo.ShapeKind, TargetInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6230. }
  6231. break;
  6232. }
  6233. case ICK_HLSLVector_Scalar: {
  6234. // 1. select vector or matrix component
  6235. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6236. // 2. optionally convert component type
  6237. if (ICK_Identity != SCS.ComponentConversion) {
  6238. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6239. if (CK_Invalid != CK) {
  6240. From = m_sema->ImpCastExprToType(From,
  6241. NewSimpleAggregateType(AR_TOBJ_BASIC, TargetInfo.EltKind, 0, 1, 1), CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6242. }
  6243. }
  6244. break;
  6245. }
  6246. // The following two (three if we re-introduce ICK_HLSLComponent_Conversion) steps
  6247. // can be done with case fall-through, since this is the order in which we want to
  6248. // do the conversion operations.
  6249. case ICK_HLSLVector_Truncation: {
  6250. // 1. dimension truncation
  6251. // vector truncation or matrix truncation?
  6252. if (SourceInfo.ShapeKind == AR_TOBJ_VECTOR) {
  6253. From = m_sema->ImpCastExprToType(From,
  6254. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, 1, TargetInfo.uTotalElts),
  6255. CK_HLSLVectorTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6256. } else if (SourceInfo.ShapeKind == AR_TOBJ_MATRIX) {
  6257. if (TargetInfo.ShapeKind == AR_TOBJ_VECTOR && 1 == SourceInfo.uCols) {
  6258. // Handle the column to vector case
  6259. From = m_sema->ImpCastExprToType(From,
  6260. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uCols, 1),
  6261. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6262. } else {
  6263. From = m_sema->ImpCastExprToType(From,
  6264. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6265. CK_HLSLMatrixTruncationCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6266. }
  6267. } else {
  6268. DXASSERT(false, "PerformHLSLConversion: Invalid source type for truncation cast");
  6269. }
  6270. }
  6271. __fallthrough;
  6272. case ICK_HLSLVector_Conversion: {
  6273. // 2. Do ShapeKind conversion if necessary
  6274. if (SourceInfo.ShapeKind != TargetInfo.ShapeKind) {
  6275. switch (TargetInfo.ShapeKind) {
  6276. case AR_TOBJ_VECTOR:
  6277. DXASSERT(AR_TOBJ_MATRIX == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  6278. From = m_sema->ImpCastExprToType(From,
  6279. NewSimpleAggregateType(AR_TOBJ_VECTOR, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6280. CK_HLSLMatrixToVectorCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6281. break;
  6282. case AR_TOBJ_MATRIX:
  6283. DXASSERT(AR_TOBJ_VECTOR == SourceInfo.ShapeKind, "otherwise, invalid casting sequence");
  6284. From = m_sema->ImpCastExprToType(From,
  6285. NewSimpleAggregateType(AR_TOBJ_MATRIX, SourceInfo.EltKind, 0, TargetInfo.uRows, TargetInfo.uCols),
  6286. CK_HLSLVectorToMatrixCast, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6287. break;
  6288. case AR_TOBJ_BASIC:
  6289. // Truncation may be followed by cast to scalar
  6290. From = HLSLImpCastToScalar(m_sema, From, SourceInfo.ShapeKind, SourceInfo.EltKind);
  6291. break;
  6292. default:
  6293. DXASSERT(false, "otherwise, invalid casting sequence");
  6294. break;
  6295. }
  6296. }
  6297. // 3. Do component type conversion
  6298. if (ICK_Identity != SCS.ComponentConversion) {
  6299. CK = ImplicitConversionKindToCastKind(SCS.ComponentConversion, SourceInfo.EltKind, TargetInfo.EltKind);
  6300. if (TargetInfo.ShapeKind != AR_TOBJ_BASIC)
  6301. CK = ConvertToComponentCastKind(CK);
  6302. if (CK_Invalid != CK) {
  6303. From = m_sema->ImpCastExprToType(From, targetType, CK, From->getValueKind(), /*BasePath=*/0, CCK).get();
  6304. }
  6305. }
  6306. break;
  6307. }
  6308. case ICK_Identity:
  6309. // Nothing to do.
  6310. break;
  6311. default:
  6312. DXASSERT(false, "PerformHLSLConversion: Invalid SCS.Second conversion kind");
  6313. }
  6314. return From;
  6315. }
  6316. void HLSLExternalSource::GetConversionForm(
  6317. QualType type,
  6318. bool explicitConversion,
  6319. ArTypeInfo* pTypeInfo)
  6320. {
  6321. //if (!CollectInfo(AR_TINFO_ALLOW_ALL, pTypeInfo))
  6322. CollectInfo(type, pTypeInfo);
  6323. // The fxc implementation reported pTypeInfo->ShapeKind separately in an output argument,
  6324. // but that value is only used for pointer conversions.
  6325. // When explicitly converting types complex aggregates can be treated
  6326. // as vectors if they are entirely numeric.
  6327. switch (pTypeInfo->ShapeKind)
  6328. {
  6329. case AR_TOBJ_COMPOUND:
  6330. case AR_TOBJ_ARRAY:
  6331. if (explicitConversion && IsTypeNumeric(type, &pTypeInfo->uTotalElts))
  6332. {
  6333. pTypeInfo->ShapeKind = AR_TOBJ_VECTOR;
  6334. }
  6335. else
  6336. {
  6337. pTypeInfo->ShapeKind = AR_TOBJ_COMPOUND;
  6338. }
  6339. DXASSERT_NOMSG(pTypeInfo->uRows == 1);
  6340. pTypeInfo->uCols = pTypeInfo->uTotalElts;
  6341. break;
  6342. case AR_TOBJ_VECTOR:
  6343. case AR_TOBJ_MATRIX:
  6344. // Convert 1x1 types to scalars.
  6345. if (pTypeInfo->uCols == 1 && pTypeInfo->uRows == 1)
  6346. {
  6347. pTypeInfo->ShapeKind = AR_TOBJ_BASIC;
  6348. }
  6349. break;
  6350. }
  6351. }
  6352. static
  6353. bool HandleVoidConversion(QualType source, QualType target, bool explicitConversion, _Out_ bool* allowed)
  6354. {
  6355. DXASSERT_NOMSG(allowed != nullptr);
  6356. bool applicable = true;
  6357. *allowed = true;
  6358. if (explicitConversion) {
  6359. // (void) non-void
  6360. if (target->isVoidType()) {
  6361. DXASSERT_NOMSG(*allowed);
  6362. }
  6363. // (non-void) void
  6364. else if (source->isVoidType()) {
  6365. *allowed = false;
  6366. }
  6367. else {
  6368. applicable = false;
  6369. }
  6370. }
  6371. else {
  6372. // (void) void
  6373. if (source->isVoidType() && target->isVoidType()) {
  6374. DXASSERT_NOMSG(*allowed);
  6375. }
  6376. // (void) non-void, (non-void) void
  6377. else if (source->isVoidType() || target->isVoidType()) {
  6378. *allowed = false;
  6379. }
  6380. else {
  6381. applicable = false;
  6382. }
  6383. }
  6384. return applicable;
  6385. }
  6386. _Use_decl_annotations_
  6387. bool HLSLExternalSource::CanConvert(
  6388. SourceLocation loc,
  6389. Expr* sourceExpr,
  6390. QualType target,
  6391. bool explicitConversion,
  6392. _Out_opt_ TYPE_CONVERSION_REMARKS* remarks,
  6393. _Inout_opt_ StandardConversionSequence* standard)
  6394. {
  6395. DXASSERT_NOMSG(sourceExpr != nullptr);
  6396. DXASSERT_NOMSG(!target.isNull());
  6397. // Implements the semantics of ArType::CanConvertTo.
  6398. TYPE_CONVERSION_FLAGS Flags = explicitConversion ? TYPE_CONVERSION_EXPLICIT : TYPE_CONVERSION_DEFAULT;
  6399. TYPE_CONVERSION_REMARKS Remarks = TYPE_CONVERSION_NONE;
  6400. QualType source = sourceExpr->getType();
  6401. // Cannot cast function type.
  6402. if (source->isFunctionType())
  6403. return false;
  6404. // Convert to an r-value to begin with.
  6405. bool needsLValueToRValue = sourceExpr->isLValue() &&
  6406. !target->isLValueReferenceType() &&
  6407. IsConversionToLessOrEqualElements(source, target, explicitConversion);
  6408. bool targetRef = target->isReferenceType();
  6409. // Initialize the output standard sequence if available.
  6410. if (standard != nullptr) {
  6411. // Set up a no-op conversion, other than lvalue to rvalue - HLSL does not support references.
  6412. standard->setAsIdentityConversion();
  6413. if (needsLValueToRValue) {
  6414. standard->First = ICK_Lvalue_To_Rvalue;
  6415. }
  6416. standard->setFromType(source);
  6417. standard->setAllToTypes(target);
  6418. }
  6419. source = GetStructuralForm(source);
  6420. target = GetStructuralForm(target);
  6421. // Temporary conversion kind tracking which will be used/fixed up at the end
  6422. ImplicitConversionKind Second = ICK_Identity;
  6423. ImplicitConversionKind ComponentConversion = ICK_Identity;
  6424. // Identical types require no conversion.
  6425. if (source == target) {
  6426. Remarks = TYPE_CONVERSION_IDENTICAL;
  6427. goto lSuccess;
  6428. }
  6429. // Trivial cases for void.
  6430. bool allowed;
  6431. if (HandleVoidConversion(source, target, explicitConversion, &allowed)) {
  6432. if (allowed) {
  6433. Remarks = target->isVoidType() ? TYPE_CONVERSION_TO_VOID : Remarks;
  6434. goto lSuccess;
  6435. }
  6436. else {
  6437. return false;
  6438. }
  6439. }
  6440. ArTypeInfo TargetInfo, SourceInfo;
  6441. CollectInfo(target, &TargetInfo);
  6442. CollectInfo(source, &SourceInfo);
  6443. UINT uTSize = TargetInfo.uTotalElts;
  6444. UINT uSSize = SourceInfo.uTotalElts;
  6445. // TODO: TYPE_CONVERSION_BY_REFERENCE does not seem possible here
  6446. // are we missing cases?
  6447. if ((Flags & TYPE_CONVERSION_BY_REFERENCE) != 0 && uTSize != uSSize) {
  6448. return false;
  6449. }
  6450. // Structure cast.
  6451. if (TargetInfo.ShapeKind == AR_TOBJ_COMPOUND || TargetInfo.ShapeKind == AR_TOBJ_ARRAY ||
  6452. SourceInfo.ShapeKind == AR_TOBJ_COMPOUND || SourceInfo.ShapeKind == AR_TOBJ_ARRAY) {
  6453. if (!explicitConversion && TargetInfo.ShapeKind != SourceInfo.ShapeKind)
  6454. {
  6455. return false;
  6456. }
  6457. const RecordType *targetRT = target->getAsStructureType();
  6458. if (!targetRT)
  6459. targetRT = dyn_cast<RecordType>(target);
  6460. const RecordType *sourceRT = source->getAsStructureType();
  6461. if (!sourceRT)
  6462. sourceRT = dyn_cast<RecordType>(source);
  6463. if (targetRT && sourceRT) {
  6464. RecordDecl *targetRD = targetRT->getDecl();
  6465. RecordDecl *sourceRD = sourceRT->getDecl();
  6466. const CXXRecordDecl *targetCXXRD = dyn_cast<CXXRecordDecl>(targetRD);
  6467. const CXXRecordDecl *sourceCXXRD = dyn_cast<CXXRecordDecl>(sourceRD);
  6468. if (targetCXXRD && sourceCXXRD) {
  6469. if (targetRD == sourceRD) {
  6470. Second = ICK_Flat_Conversion;
  6471. goto lSuccess;
  6472. }
  6473. if (sourceCXXRD->isDerivedFrom(targetCXXRD)) {
  6474. Second = ICK_HLSL_Derived_To_Base;
  6475. goto lSuccess;
  6476. }
  6477. } else {
  6478. if (targetRD == sourceRD) {
  6479. Second = ICK_Flat_Conversion;
  6480. goto lSuccess;
  6481. }
  6482. }
  6483. }
  6484. if (const BuiltinType *BT = source->getAs<BuiltinType>()) {
  6485. BuiltinType::Kind kind = BT->getKind();
  6486. switch (kind) {
  6487. case BuiltinType::Kind::UInt:
  6488. case BuiltinType::Kind::Int:
  6489. case BuiltinType::Kind::Float:
  6490. case BuiltinType::Kind::LitFloat:
  6491. case BuiltinType::Kind::LitInt:
  6492. if (explicitConversion) {
  6493. Second = ICK_Flat_Conversion;
  6494. goto lSuccess;
  6495. }
  6496. break;
  6497. }
  6498. }
  6499. if (const BuiltinType *BT = source->getAs<BuiltinType>()) {
  6500. BuiltinType::Kind kind = BT->getKind();
  6501. switch (kind) {
  6502. case BuiltinType::Kind::UInt:
  6503. case BuiltinType::Kind::Int:
  6504. case BuiltinType::Kind::Float:
  6505. case BuiltinType::Kind::LitFloat:
  6506. case BuiltinType::Kind::LitInt:
  6507. if (explicitConversion) {
  6508. Second = ICK_Flat_Conversion;
  6509. goto lSuccess;
  6510. }
  6511. break;
  6512. }
  6513. }
  6514. FlattenedTypeIterator::ComparisonResult result =
  6515. FlattenedTypeIterator::CompareTypes(*this, loc, loc, target, source);
  6516. if (!result.CanConvertElements) {
  6517. return false;
  6518. }
  6519. // Only allow scalar to compound or array with explicit cast
  6520. if (result.IsConvertibleAndLeftLonger()) {
  6521. if (!explicitConversion || SourceInfo.ShapeKind != AR_TOBJ_SCALAR) {
  6522. return false;
  6523. }
  6524. }
  6525. // Assignment is valid if elements are exactly the same in type and size; if
  6526. // an explicit conversion is being done, we accept converted elements and a
  6527. // longer right-hand sequence.
  6528. if (!explicitConversion &&
  6529. (!result.AreElementsEqual || result.IsRightLonger()))
  6530. {
  6531. return false;
  6532. }
  6533. Second = ICK_Flat_Conversion;
  6534. goto lSuccess;
  6535. }
  6536. // Base type cast.
  6537. //
  6538. // The rules for aggregate conversions are:
  6539. // 1. A scalar can be replicated to any layout.
  6540. // 2. The result of two vectors is the smaller vector.
  6541. // 3. The result of two matrices is the smaller matrix.
  6542. // 4. The result of a vector and a matrix is:
  6543. // a. If the matrix has one row it's a vector-sized
  6544. // piece of the row.
  6545. // b. If the matrix has one column it's a vector-sized
  6546. // piece of the column.
  6547. // c. Otherwise the number of elements in the vector
  6548. // and matrix must match and the result is the vector.
  6549. // 5. The result of a matrix and a vector is similar to #4.
  6550. //
  6551. bool bCheckElt = false;
  6552. switch (TargetInfo.ShapeKind) {
  6553. case AR_TOBJ_BASIC:
  6554. switch (SourceInfo.ShapeKind)
  6555. {
  6556. case AR_TOBJ_BASIC:
  6557. Second = ICK_Identity;
  6558. break;
  6559. case AR_TOBJ_VECTOR:
  6560. if(1 < SourceInfo.uCols)
  6561. Second = ICK_HLSLVector_Truncation;
  6562. else
  6563. Second = ICK_HLSLVector_Scalar;
  6564. break;
  6565. case AR_TOBJ_MATRIX:
  6566. if(1 < SourceInfo.uRows * SourceInfo.uCols)
  6567. Second = ICK_HLSLVector_Truncation;
  6568. else
  6569. Second = ICK_HLSLVector_Scalar;
  6570. break;
  6571. case AR_TOBJ_OBJECT:
  6572. case AR_TOBJ_INTERFACE:
  6573. case AR_TOBJ_POINTER:
  6574. return false;
  6575. }
  6576. bCheckElt = true;
  6577. break;
  6578. case AR_TOBJ_VECTOR:
  6579. switch (SourceInfo.ShapeKind)
  6580. {
  6581. case AR_TOBJ_BASIC:
  6582. // Conversions between scalars and aggregates are always supported.
  6583. Second = ICK_HLSLVector_Splat;
  6584. break;
  6585. case AR_TOBJ_VECTOR:
  6586. if (TargetInfo.uCols > SourceInfo.uCols) {
  6587. if (SourceInfo.uCols == 1) {
  6588. Second = ICK_HLSLVector_Splat;
  6589. } else {
  6590. return false;
  6591. }
  6592. } else if (TargetInfo.uCols < SourceInfo.uCols) {
  6593. Second = ICK_HLSLVector_Truncation;
  6594. } else {
  6595. Second = ICK_Identity;
  6596. }
  6597. break;
  6598. case AR_TOBJ_MATRIX: {
  6599. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  6600. if (1 == SourceComponents && TargetInfo.uCols != 1) {
  6601. // splat: matrix<[..], 1, 1> -> vector<[..], O>
  6602. Second = ICK_HLSLVector_Splat;
  6603. } else if (1 == SourceInfo.uRows || 1 == SourceInfo.uCols) {
  6604. // cases for: matrix<[..], M, N> -> vector<[..], O>, where N == 1 or M == 1
  6605. if (TargetInfo.uCols > SourceComponents) // illegal: O > N*M
  6606. return false;
  6607. else if (TargetInfo.uCols < SourceComponents) // truncation: O < N*M
  6608. Second = ICK_HLSLVector_Truncation;
  6609. else // equalivalent: O == N*M
  6610. Second = ICK_HLSLVector_Conversion;
  6611. } else if (TargetInfo.uCols != SourceComponents) {
  6612. // illegal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O != N*M
  6613. return false;
  6614. } else {
  6615. // legal: matrix<[..], M, N> -> vector<[..], O> where N != 1 and M != 1 and O == N*M
  6616. Second = ICK_HLSLVector_Conversion;
  6617. }
  6618. break;
  6619. }
  6620. case AR_TOBJ_OBJECT:
  6621. case AR_TOBJ_INTERFACE:
  6622. case AR_TOBJ_POINTER:
  6623. return false;
  6624. }
  6625. bCheckElt = true;
  6626. break;
  6627. case AR_TOBJ_MATRIX: {
  6628. UINT TargetComponents = TargetInfo.uRows * TargetInfo.uCols;
  6629. switch (SourceInfo.ShapeKind)
  6630. {
  6631. case AR_TOBJ_BASIC:
  6632. // Conversions between scalars and aggregates are always supported.
  6633. Second = ICK_HLSLVector_Splat;
  6634. break;
  6635. case AR_TOBJ_VECTOR: {
  6636. if (1 == SourceInfo.uCols && TargetComponents != 1) {
  6637. // splat: vector<[..], 1> -> matrix<[..], M, N>
  6638. Second = ICK_HLSLVector_Splat;
  6639. } else if (1 == TargetInfo.uRows || 1 == TargetInfo.uCols) {
  6640. // cases for: vector<[..], O> -> matrix<[..], N, M>, where N == 1 or M == 1
  6641. if (TargetComponents > SourceInfo.uCols) // illegal: N*M > O
  6642. return false;
  6643. else if (TargetComponents < SourceInfo.uCols) // truncation: N*M < O
  6644. Second = ICK_HLSLVector_Truncation;
  6645. else // equalivalent: N*M == O
  6646. Second = ICK_HLSLVector_Conversion;
  6647. } else if (TargetComponents != SourceInfo.uCols) {
  6648. // illegal: vector<[..], O> -> matrix<[..], M, N> where N != 1 and M != 1 and O != N*M
  6649. return false;
  6650. } else {
  6651. // legal: vector<[..], O> -> matrix<[..], M, N> where N != 1 and M != 1 and O == N*M
  6652. Second = ICK_HLSLVector_Conversion;
  6653. }
  6654. break;
  6655. }
  6656. case AR_TOBJ_MATRIX: {
  6657. UINT SourceComponents = SourceInfo.uRows * SourceInfo.uCols;
  6658. if (1 == SourceComponents && TargetComponents != 1) {
  6659. // splat: matrix<[..], 1, 1> -> matrix<[..], M, N>
  6660. Second = ICK_HLSLVector_Splat;
  6661. } else if (TargetInfo.uRows > SourceInfo.uRows || TargetInfo.uCols > SourceInfo.uCols) {
  6662. return false;
  6663. } else if(TargetInfo.uRows < SourceInfo.uRows || TargetInfo.uCols < SourceInfo.uCols) {
  6664. Second = ICK_HLSLVector_Truncation;
  6665. } else {
  6666. Second = ICK_Identity;
  6667. }
  6668. break;
  6669. }
  6670. case AR_TOBJ_OBJECT:
  6671. case AR_TOBJ_INTERFACE:
  6672. case AR_TOBJ_POINTER:
  6673. return false;
  6674. }
  6675. bCheckElt = true;
  6676. break;
  6677. }
  6678. case AR_TOBJ_OBJECT:
  6679. // There are no compatible object assignments that aren't
  6680. // from one type to itself, which is already covered.
  6681. DXASSERT(source != target, "otherwise trivial case was not checked by this function");
  6682. return false;
  6683. default:
  6684. DXASSERT_NOMSG(false);
  6685. return false;
  6686. }
  6687. if (bCheckElt)
  6688. {
  6689. bool precisionLoss = false;
  6690. if (GET_BASIC_BITS(TargetInfo.EltKind) != 0 &&
  6691. GET_BASIC_BITS(TargetInfo.EltKind) <
  6692. GET_BASIC_BITS(SourceInfo.EltKind))
  6693. {
  6694. precisionLoss = true;
  6695. Remarks |= TYPE_CONVERSION_PRECISION_LOSS;
  6696. }
  6697. if (TargetInfo.uTotalElts < SourceInfo.uTotalElts)
  6698. {
  6699. Remarks |= TYPE_CONVERSION_ELT_TRUNCATION;
  6700. }
  6701. // enum -> enum not allowed
  6702. if ((SourceInfo.EltKind == AR_BASIC_ENUM &&
  6703. TargetInfo.EltKind == AR_BASIC_ENUM) ||
  6704. SourceInfo.EltKind == AR_BASIC_ENUM_CLASS ||
  6705. TargetInfo.EltKind == AR_BASIC_ENUM_CLASS) {
  6706. return false;
  6707. }
  6708. if (SourceInfo.EltKind != TargetInfo.EltKind)
  6709. {
  6710. if (TargetInfo.EltKind == AR_BASIC_UNKNOWN ||
  6711. SourceInfo.EltKind == AR_BASIC_UNKNOWN)
  6712. {
  6713. Second = ICK_Flat_Conversion;
  6714. }
  6715. else if (IS_BASIC_BOOL(TargetInfo.EltKind))
  6716. {
  6717. ComponentConversion = ICK_Boolean_Conversion;
  6718. }
  6719. else if (IS_BASIC_ENUM(TargetInfo.EltKind))
  6720. {
  6721. // conversion to enum type not allowed
  6722. return false;
  6723. }
  6724. else if (IS_BASIC_ENUM(SourceInfo.EltKind))
  6725. {
  6726. // enum -> int/float
  6727. ComponentConversion = ICK_Integral_Conversion;
  6728. }
  6729. else
  6730. {
  6731. bool targetIsInt = IS_BASIC_AINT(TargetInfo.EltKind);
  6732. if (IS_BASIC_AINT(SourceInfo.EltKind))
  6733. {
  6734. if (targetIsInt)
  6735. {
  6736. ComponentConversion = precisionLoss ? ICK_Integral_Conversion : ICK_Integral_Promotion;
  6737. }
  6738. else
  6739. {
  6740. ComponentConversion = ICK_Floating_Integral;
  6741. }
  6742. }
  6743. else if (IS_BASIC_FLOAT(SourceInfo.EltKind))
  6744. {
  6745. DXASSERT(IS_BASIC_FLOAT(SourceInfo.EltKind), "otherwise should not be checking element types");
  6746. if (targetIsInt)
  6747. {
  6748. ComponentConversion = ICK_Floating_Integral;
  6749. }
  6750. else
  6751. {
  6752. ComponentConversion = precisionLoss ? ICK_Floating_Conversion : ICK_Floating_Promotion;
  6753. }
  6754. } else if (IS_BASIC_BOOL(SourceInfo.EltKind)) {
  6755. if (targetIsInt)
  6756. ComponentConversion = ICK_Integral_Conversion;
  6757. else
  6758. ComponentConversion = ICK_Floating_Integral;
  6759. }
  6760. }
  6761. }
  6762. }
  6763. lSuccess:
  6764. if (standard)
  6765. {
  6766. if (sourceExpr->isLValue())
  6767. {
  6768. if (needsLValueToRValue) {
  6769. standard->First = ICK_Lvalue_To_Rvalue;
  6770. } else {
  6771. switch (Second)
  6772. {
  6773. case ICK_NoReturn_Adjustment:
  6774. case ICK_Vector_Conversion:
  6775. case ICK_Vector_Splat:
  6776. DXASSERT(false, "We shouldn't be producing these implicit conversion kinds");
  6777. case ICK_Flat_Conversion:
  6778. case ICK_HLSLVector_Splat:
  6779. standard->First = ICK_Lvalue_To_Rvalue;
  6780. break;
  6781. }
  6782. switch (ComponentConversion)
  6783. {
  6784. case ICK_Integral_Promotion:
  6785. case ICK_Integral_Conversion:
  6786. case ICK_Floating_Promotion:
  6787. case ICK_Floating_Conversion:
  6788. case ICK_Floating_Integral:
  6789. case ICK_Boolean_Conversion:
  6790. standard->First = ICK_Lvalue_To_Rvalue;
  6791. break;
  6792. }
  6793. }
  6794. }
  6795. // Finally fix up the cases for scalar->scalar component conversion, and
  6796. // identity vector/matrix component conversion
  6797. if (ICK_Identity != ComponentConversion) {
  6798. if (Second == ICK_Identity) {
  6799. if (TargetInfo.ShapeKind == AR_TOBJ_BASIC) {
  6800. // Scalar to scalar type conversion, use normal mechanism (Second)
  6801. Second = ComponentConversion;
  6802. ComponentConversion = ICK_Identity;
  6803. } else {
  6804. // vector or matrix dimensions are not being changed, but component type
  6805. // is being converted, so change Second to signal the conversion
  6806. Second = ICK_HLSLVector_Conversion;
  6807. }
  6808. }
  6809. }
  6810. standard->Second = Second;
  6811. standard->ComponentConversion = ComponentConversion;
  6812. // For conversion which change to RValue but targeting reference type
  6813. // Hold the conversion to codeGen
  6814. if (targetRef && standard->First == ICK_Lvalue_To_Rvalue) {
  6815. standard->First = ICK_Identity;
  6816. standard->Second = ICK_Identity;
  6817. }
  6818. }
  6819. AssignOpt(Remarks, remarks);
  6820. return true;
  6821. }
  6822. Expr* HLSLExternalSource::CastExprToTypeNumeric(Expr* expr, QualType type)
  6823. {
  6824. DXASSERT_NOMSG(expr != nullptr);
  6825. DXASSERT_NOMSG(!type.isNull());
  6826. if (expr->getType() != type) {
  6827. StandardConversionSequence standard;
  6828. if (CanConvert(SourceLocation(), expr, type, /*explicitConversion*/false, nullptr, &standard) &&
  6829. (standard.First != ICK_Identity || !standard.isIdentityConversion())) {
  6830. ExprResult result = m_sema->PerformImplicitConversion(expr, type, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  6831. if (result.isUsable()) {
  6832. return result.get();
  6833. }
  6834. }
  6835. }
  6836. return expr;
  6837. }
  6838. bool HLSLExternalSource::ValidateTypeRequirements(
  6839. SourceLocation loc,
  6840. ArBasicKind elementKind,
  6841. ArTypeObjectKind objectKind,
  6842. bool requiresIntegrals,
  6843. bool requiresNumerics)
  6844. {
  6845. if (requiresIntegrals || requiresNumerics)
  6846. {
  6847. if (!IsObjectKindPrimitiveAggregate(objectKind))
  6848. {
  6849. m_sema->Diag(loc, diag::err_hlsl_requires_non_aggregate);
  6850. return false;
  6851. }
  6852. }
  6853. if (requiresIntegrals)
  6854. {
  6855. if (!IsBasicKindIntegral(elementKind))
  6856. {
  6857. m_sema->Diag(loc, diag::err_hlsl_requires_int_or_uint);
  6858. return false;
  6859. }
  6860. }
  6861. else if (requiresNumerics)
  6862. {
  6863. if (!IsBasicKindNumeric(elementKind))
  6864. {
  6865. m_sema->Diag(loc, diag::err_hlsl_requires_numeric);
  6866. return false;
  6867. }
  6868. }
  6869. return true;
  6870. }
  6871. bool HLSLExternalSource::ValidatePrimitiveTypeForOperand(SourceLocation loc, QualType type, ArTypeObjectKind kind)
  6872. {
  6873. bool isValid = true;
  6874. if (IsBuiltInObjectType(type)) {
  6875. m_sema->Diag(loc, diag::err_hlsl_unsupported_builtin_op) << type;
  6876. isValid = false;
  6877. }
  6878. if (kind == AR_TOBJ_COMPOUND) {
  6879. m_sema->Diag(loc, diag::err_hlsl_unsupported_struct_op) << type;
  6880. isValid = false;
  6881. }
  6882. return isValid;
  6883. }
  6884. HRESULT HLSLExternalSource::CombineDimensions(QualType leftType, QualType rightType, QualType *resultType)
  6885. {
  6886. UINT leftRows, leftCols;
  6887. UINT rightRows, rightCols;
  6888. GetRowsAndColsForAny(leftType, leftRows, leftCols);
  6889. GetRowsAndColsForAny(rightType, rightRows, rightCols);
  6890. UINT leftTotal = leftRows * leftCols;
  6891. UINT rightTotal = rightRows * rightCols;
  6892. if (rightTotal == 1) {
  6893. *resultType = leftType;
  6894. return S_OK;
  6895. } else if (leftTotal == 1) {
  6896. *resultType = rightType;
  6897. return S_OK;
  6898. } else if (leftRows <= rightRows && leftCols <= rightCols) {
  6899. *resultType = leftType;
  6900. return S_OK;
  6901. } else if (rightRows <= leftRows && rightCols <= leftCols) {
  6902. *resultType = rightType;
  6903. return S_OK;
  6904. } else if ( (1 == leftRows || 1 == leftCols) &&
  6905. (1 == rightRows || 1 == rightCols)) {
  6906. // Handles cases where 1xN or Nx1 matrices are involved possibly mixed with vectors
  6907. if (leftTotal <= rightTotal) {
  6908. *resultType = leftType;
  6909. return S_OK;
  6910. } else {
  6911. *resultType = rightType;
  6912. return S_OK;
  6913. }
  6914. }
  6915. return E_FAIL;
  6916. }
  6917. /// <summary>Validates and adjusts operands for the specified binary operator.</summary>
  6918. /// <param name="OpLoc">Source location for operator.</param>
  6919. /// <param name="Opc">Kind of binary operator.</param>
  6920. /// <param name="LHS">Left-hand-side expression, possibly updated by this function.</param>
  6921. /// <param name="RHS">Right-hand-side expression, possibly updated by this function.</param>
  6922. /// <param name="ResultTy">Result type for operator expression.</param>
  6923. /// <param name="CompLHSTy">Type of LHS after promotions for computation.</param>
  6924. /// <param name="CompResultTy">Type of computation result.</param>
  6925. void HLSLExternalSource::CheckBinOpForHLSL(
  6926. SourceLocation OpLoc,
  6927. BinaryOperatorKind Opc,
  6928. ExprResult& LHS,
  6929. ExprResult& RHS,
  6930. QualType& ResultTy,
  6931. QualType& CompLHSTy,
  6932. QualType& CompResultTy)
  6933. {
  6934. // At the start, none of the output types should be valid.
  6935. DXASSERT_NOMSG(ResultTy.isNull());
  6936. DXASSERT_NOMSG(CompLHSTy.isNull());
  6937. DXASSERT_NOMSG(CompResultTy.isNull());
  6938. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  6939. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  6940. // If either expression is invalid to begin with, propagate that.
  6941. if (LHS.isInvalid() || RHS.isInvalid()) {
  6942. return;
  6943. }
  6944. // TODO: re-review the Check** in Clang and add equivalent diagnostics if/as needed, possibly after conversions
  6945. // Handle Assign and Comma operators and return
  6946. switch (Opc)
  6947. {
  6948. case BO_AddAssign:
  6949. case BO_AndAssign:
  6950. case BO_DivAssign:
  6951. case BO_MulAssign:
  6952. case BO_RemAssign:
  6953. case BO_ShlAssign:
  6954. case BO_ShrAssign:
  6955. case BO_SubAssign:
  6956. case BO_OrAssign:
  6957. case BO_XorAssign: {
  6958. extern bool CheckForModifiableLvalue(Expr * E, SourceLocation Loc,
  6959. Sema & S);
  6960. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  6961. return;
  6962. }
  6963. } break;
  6964. case BO_Assign: {
  6965. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  6966. if (CheckForModifiableLvalue(LHS.get(), OpLoc, *m_sema)) {
  6967. return;
  6968. }
  6969. bool complained = false;
  6970. ResultTy = LHS.get()->getType();
  6971. if (m_sema->DiagnoseAssignmentResult(Sema::AssignConvertType::Compatible,
  6972. OpLoc, ResultTy, RHS.get()->getType(), RHS.get(),
  6973. Sema::AssignmentAction::AA_Assigning, &complained)) {
  6974. return;
  6975. }
  6976. StandardConversionSequence standard;
  6977. if (!ValidateCast(OpLoc, RHS.get(), ResultTy,
  6978. ExplicitConversionFalse, complained, complained, &standard)) {
  6979. return;
  6980. }
  6981. if (RHS.get()->isLValue()) {
  6982. standard.First = ICK_Lvalue_To_Rvalue;
  6983. }
  6984. RHS = m_sema->PerformImplicitConversion(RHS.get(), ResultTy,
  6985. standard, Sema::AA_Converting, Sema::CCK_ImplicitConversion);
  6986. return;
  6987. }
  6988. break;
  6989. case BO_Comma:
  6990. // C performs conversions, C++ doesn't but still checks for type completeness.
  6991. // There are also diagnostics for improper comma use.
  6992. // In the HLSL case these cases don't apply or simply aren't surfaced.
  6993. ResultTy = RHS.get()->getType();
  6994. return;
  6995. }
  6996. // Leave this diagnostic for last to emulate fxc behavior.
  6997. bool isCompoundAssignment = BinaryOperatorKindIsCompoundAssignment(Opc);
  6998. bool unsupportedBoolLvalue = isCompoundAssignment &&
  6999. !BinaryOperatorKindIsCompoundAssignmentForBool(Opc) &&
  7000. GetTypeElementKind(LHS.get()->getType()) == AR_BASIC_BOOL;
  7001. // Turn operand inputs into r-values.
  7002. QualType LHSTypeAsPossibleLValue = LHS.get()->getType();
  7003. if (!isCompoundAssignment) {
  7004. LHS = m_sema->DefaultLvalueConversion(LHS.get());
  7005. }
  7006. RHS = m_sema->DefaultLvalueConversion(RHS.get());
  7007. if (LHS.isInvalid() || RHS.isInvalid()) {
  7008. return;
  7009. }
  7010. // Promote bool to int now if necessary
  7011. if (BinaryOperatorKindRequiresBoolAsNumeric(Opc) &&
  7012. !isCompoundAssignment) {
  7013. LHS = PromoteToIntIfBool(LHS);
  7014. }
  7015. // Gather type info
  7016. QualType leftType = GetStructuralForm(LHS.get()->getType());
  7017. QualType rightType = GetStructuralForm(RHS.get()->getType());
  7018. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  7019. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  7020. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  7021. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  7022. // Validate type requirements
  7023. {
  7024. bool requiresNumerics = BinaryOperatorKindRequiresNumeric(Opc);
  7025. bool requiresIntegrals = BinaryOperatorKindRequiresIntegrals(Opc);
  7026. if (!ValidateTypeRequirements(OpLoc, leftElementKind, leftObjectKind, requiresIntegrals, requiresNumerics)) {
  7027. return;
  7028. }
  7029. if (!ValidateTypeRequirements(OpLoc, rightElementKind, rightObjectKind, requiresIntegrals, requiresNumerics)) {
  7030. return;
  7031. }
  7032. }
  7033. // Promote rhs bool to int if necessary.
  7034. if (BinaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  7035. RHS = PromoteToIntIfBool(RHS);
  7036. }
  7037. if (unsupportedBoolLvalue) {
  7038. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  7039. return;
  7040. }
  7041. // We don't support binary operators on built-in object types other than assignment or commas.
  7042. {
  7043. DXASSERT(Opc != BO_Assign, "otherwise this wasn't handled as an early exit");
  7044. DXASSERT(Opc != BO_Comma, "otherwise this wasn't handled as an early exit");
  7045. bool isValid;
  7046. isValid = ValidatePrimitiveTypeForOperand(OpLoc, leftType, leftObjectKind);
  7047. if (leftType != rightType && !ValidatePrimitiveTypeForOperand(OpLoc, rightType, rightObjectKind)) {
  7048. isValid = false;
  7049. }
  7050. if (!isValid) {
  7051. return;
  7052. }
  7053. }
  7054. // We don't support equality comparisons on arrays.
  7055. if ((Opc == BO_EQ || Opc == BO_NE) && (leftObjectKind == AR_TOBJ_ARRAY || rightObjectKind == AR_TOBJ_ARRAY)) {
  7056. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_array_equality_op);
  7057. return;
  7058. }
  7059. // Combine element types for computation.
  7060. ArBasicKind resultElementKind = leftElementKind;
  7061. {
  7062. if (BinaryOperatorKindIsLogical(Opc)) {
  7063. resultElementKind = AR_BASIC_BOOL;
  7064. } else if (!BinaryOperatorKindIsBitwiseShift(Opc) && leftElementKind != rightElementKind) {
  7065. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind, nullptr, nullptr)) {
  7066. m_sema->Diag(OpLoc, diag::err_hlsl_type_mismatch);
  7067. return;
  7068. }
  7069. } else if (BinaryOperatorKindIsBitwiseShift(Opc) &&
  7070. (resultElementKind == AR_BASIC_LITERAL_INT ||
  7071. resultElementKind == AR_BASIC_LITERAL_FLOAT) &&
  7072. rightElementKind != AR_BASIC_LITERAL_INT &&
  7073. rightElementKind != AR_BASIC_LITERAL_FLOAT) {
  7074. // For case like 1<<x.
  7075. resultElementKind = AR_BASIC_UINT32;
  7076. }
  7077. // The following combines the selected/combined element kind above with
  7078. // the dimensions that are legal to implicitly cast. This means that
  7079. // element kind may be taken from one side and the dimensions from the
  7080. // other.
  7081. if (!isCompoundAssignment) {
  7082. // Legal dimension combinations are identical, splat, and truncation.
  7083. // ResultTy will be set to whichever type can be converted to, if legal,
  7084. // with preference for leftType if both are possible.
  7085. if (FAILED(CombineDimensions(leftType, rightType, &ResultTy))) {
  7086. m_sema->Diag(OpLoc, diag::err_hlsl_type_mismatch);
  7087. return;
  7088. }
  7089. } else {
  7090. ResultTy = LHS.get()->getType();
  7091. }
  7092. // Here, element kind is combined with dimensions for computation type.
  7093. UINT rowCount, colCount;
  7094. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7095. ResultTy = NewSimpleAggregateType(AR_TOBJ_INVALID, resultElementKind, 0, rowCount, colCount)->getCanonicalTypeInternal();
  7096. }
  7097. // Perform necessary conversion sequences for LHS and RHS
  7098. if (RHS.get()->getType() != ResultTy) {
  7099. RHS = CastExprToTypeNumeric(RHS.get(), ResultTy);
  7100. }
  7101. if (isCompoundAssignment) {
  7102. bool complained = false;
  7103. StandardConversionSequence standard;
  7104. if (!ValidateCast(OpLoc, RHS.get(), LHS.get()->getType(), ExplicitConversionFalse,
  7105. complained, complained, &standard)) {
  7106. ResultTy = QualType();
  7107. return;
  7108. }
  7109. CompResultTy = ResultTy;
  7110. CompLHSTy = CompResultTy;
  7111. // For a compound operation, C/C++ promotes both types, performs the arithmetic,
  7112. // then converts to the result type and then assigns.
  7113. //
  7114. // So int + float promotes the int to float, does a floating-point addition,
  7115. // then the result becomes and int and is assigned.
  7116. ResultTy = LHSTypeAsPossibleLValue;
  7117. } else if (LHS.get()->getType() != ResultTy) {
  7118. LHS = CastExprToTypeNumeric(LHS.get(), ResultTy);
  7119. }
  7120. if (BinaryOperatorKindIsComparison(Opc) || BinaryOperatorKindIsLogical(Opc))
  7121. {
  7122. DXASSERT(!isCompoundAssignment, "otherwise binary lookup tables are inconsistent");
  7123. // Return bool vector for vector types.
  7124. if (IsVectorType(m_sema, ResultTy)) {
  7125. UINT rowCount, colCount;
  7126. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7127. ResultTy = LookupVectorType(HLSLScalarType::HLSLScalarType_bool, colCount);
  7128. } else if (IsMatrixType(m_sema, ResultTy)) {
  7129. UINT rowCount, colCount;
  7130. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7131. ResultTy = LookupMatrixType(HLSLScalarType::HLSLScalarType_bool, rowCount, colCount);
  7132. } else
  7133. ResultTy = m_context->BoolTy.withConst();
  7134. }
  7135. // Run diagnostics. Some are emulating checks that occur in IR emission in fxc.
  7136. if (Opc == BO_Div || Opc == BO_DivAssign || Opc == BO_Rem || Opc == BO_RemAssign) {
  7137. if (IsBasicKindIntMinPrecision(resultElementKind)) {
  7138. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_div_minint);
  7139. return;
  7140. }
  7141. }
  7142. if (Opc == BO_Rem || Opc == BO_RemAssign) {
  7143. if (resultElementKind == AR_BASIC_FLOAT64) {
  7144. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_mod_double);
  7145. return;
  7146. }
  7147. }
  7148. }
  7149. /// <summary>Validates and adjusts operands for the specified unary operator.</summary>
  7150. /// <param name="OpLoc">Source location for operator.</param>
  7151. /// <param name="Opc">Kind of operator.</param>
  7152. /// <param name="InputExpr">Input expression to the operator.</param>
  7153. /// <param name="VK">Value kind for resulting expression.</param>
  7154. /// <param name="OK">Object kind for resulting expression.</param>
  7155. /// <returns>The result type for the expression.</returns>
  7156. QualType HLSLExternalSource::CheckUnaryOpForHLSL(
  7157. SourceLocation OpLoc,
  7158. UnaryOperatorKind Opc,
  7159. ExprResult& InputExpr,
  7160. ExprValueKind& VK,
  7161. ExprObjectKind& OK)
  7162. {
  7163. InputExpr = m_sema->CorrectDelayedTyposInExpr(InputExpr);
  7164. if (InputExpr.isInvalid())
  7165. return QualType();
  7166. // Reject unsupported operators * and &
  7167. switch (Opc) {
  7168. case UO_AddrOf:
  7169. case UO_Deref:
  7170. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_operator);
  7171. return QualType();
  7172. }
  7173. Expr* expr = InputExpr.get();
  7174. if (expr->isTypeDependent())
  7175. return m_context->DependentTy;
  7176. ArBasicKind elementKind = GetTypeElementKind(expr->getType());
  7177. if (UnaryOperatorKindRequiresModifiableValue(Opc)) {
  7178. if (elementKind == AR_BASIC_ENUM) {
  7179. bool isInc = IsIncrementOp(Opc);
  7180. m_sema->Diag(OpLoc, diag::err_increment_decrement_enum) << isInc << expr->getType();
  7181. return QualType();
  7182. }
  7183. extern bool CheckForModifiableLvalue(Expr *E, SourceLocation Loc, Sema &S);
  7184. if (CheckForModifiableLvalue(expr, OpLoc, *m_sema))
  7185. return QualType();
  7186. } else {
  7187. InputExpr = m_sema->DefaultLvalueConversion(InputExpr.get()).get();
  7188. if (InputExpr.isInvalid()) return QualType();
  7189. }
  7190. if (UnaryOperatorKindDisallowsBool(Opc) && IS_BASIC_BOOL(elementKind)) {
  7191. m_sema->Diag(OpLoc, diag::err_hlsl_unsupported_bool_lvalue_op);
  7192. return QualType();
  7193. }
  7194. if (UnaryOperatorKindRequiresBoolAsNumeric(Opc)) {
  7195. InputExpr = PromoteToIntIfBool(InputExpr);
  7196. expr = InputExpr.get();
  7197. elementKind = GetTypeElementKind(expr->getType());
  7198. }
  7199. ArTypeObjectKind objectKind = GetTypeObjectKind(expr->getType());
  7200. bool requiresIntegrals = UnaryOperatorKindRequiresIntegrals(Opc);
  7201. bool requiresNumerics = UnaryOperatorKindRequiresNumerics(Opc);
  7202. if (!ValidateTypeRequirements(OpLoc, elementKind, objectKind, requiresIntegrals, requiresNumerics)) {
  7203. return QualType();
  7204. }
  7205. if (Opc == UnaryOperatorKind::UO_Minus) {
  7206. if (IS_BASIC_UINT(Opc)) {
  7207. m_sema->Diag(OpLoc, diag::warn_hlsl_unary_negate_unsigned);
  7208. }
  7209. }
  7210. // By default, the result type is the operand type.
  7211. // Logical not however should cast to a bool.
  7212. QualType resultType = expr->getType();
  7213. if (Opc == UnaryOperatorKind::UO_LNot) {
  7214. UINT rowCount, colCount;
  7215. GetRowsAndColsForAny(expr->getType(), rowCount, colCount);
  7216. resultType = NewSimpleAggregateType(objectKind, AR_BASIC_BOOL, AR_QUAL_CONST, rowCount, colCount);
  7217. StandardConversionSequence standard;
  7218. if (!CanConvert(OpLoc, expr, resultType, false, nullptr, &standard)) {
  7219. m_sema->Diag(OpLoc, diag::err_hlsl_requires_bool_for_not);
  7220. return QualType();
  7221. }
  7222. // Cast argument.
  7223. ExprResult result = m_sema->PerformImplicitConversion(InputExpr.get(), resultType, standard, Sema::AA_Casting, Sema::CCK_ImplicitConversion);
  7224. if (result.isUsable()) {
  7225. InputExpr = result.get();
  7226. }
  7227. }
  7228. bool isPrefix = Opc == UO_PreInc || Opc == UO_PreDec;
  7229. if (isPrefix) {
  7230. VK = VK_LValue;
  7231. return resultType;
  7232. }
  7233. else {
  7234. VK = VK_RValue;
  7235. return resultType.getUnqualifiedType();
  7236. }
  7237. }
  7238. clang::QualType HLSLExternalSource::CheckVectorConditional(
  7239. _In_ ExprResult &Cond,
  7240. _In_ ExprResult &LHS,
  7241. _In_ ExprResult &RHS,
  7242. _In_ SourceLocation QuestionLoc)
  7243. {
  7244. Cond = m_sema->CorrectDelayedTyposInExpr(Cond);
  7245. LHS = m_sema->CorrectDelayedTyposInExpr(LHS);
  7246. RHS = m_sema->CorrectDelayedTyposInExpr(RHS);
  7247. // If either expression is invalid to begin with, propagate that.
  7248. if (Cond.isInvalid() || LHS.isInvalid() || RHS.isInvalid()) {
  7249. return QualType();
  7250. }
  7251. // Gather type info
  7252. QualType condType = GetStructuralForm(Cond.get()->getType());
  7253. QualType leftType = GetStructuralForm(LHS.get()->getType());
  7254. QualType rightType = GetStructuralForm(RHS.get()->getType());
  7255. ArBasicKind condElementKind = GetTypeElementKind(condType);
  7256. ArBasicKind leftElementKind = GetTypeElementKind(leftType);
  7257. ArBasicKind rightElementKind = GetTypeElementKind(rightType);
  7258. ArTypeObjectKind condObjectKind = GetTypeObjectKind(condType);
  7259. ArTypeObjectKind leftObjectKind = GetTypeObjectKind(leftType);
  7260. ArTypeObjectKind rightObjectKind = GetTypeObjectKind(rightType);
  7261. QualType ResultTy = leftType;
  7262. bool condIsSimple = condObjectKind == AR_TOBJ_BASIC || condObjectKind == AR_TOBJ_VECTOR || condObjectKind == AR_TOBJ_MATRIX;
  7263. if (!condIsSimple) {
  7264. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_cond_typecheck);
  7265. return QualType();
  7266. }
  7267. UINT rowCountCond, colCountCond;
  7268. GetRowsAndColsForAny(condType, rowCountCond, colCountCond);
  7269. bool leftIsSimple =
  7270. leftObjectKind == AR_TOBJ_BASIC || leftObjectKind == AR_TOBJ_VECTOR ||
  7271. leftObjectKind == AR_TOBJ_MATRIX;
  7272. bool rightIsSimple =
  7273. rightObjectKind == AR_TOBJ_BASIC || rightObjectKind == AR_TOBJ_VECTOR ||
  7274. rightObjectKind == AR_TOBJ_MATRIX;
  7275. UINT rowCount, colCount;
  7276. GetRowsAndColsForAny(ResultTy, rowCount, colCount);
  7277. if (!leftIsSimple || !rightIsSimple) {
  7278. if (leftObjectKind == AR_TOBJ_OBJECT && leftObjectKind == AR_TOBJ_OBJECT) {
  7279. if (leftType == rightType) {
  7280. return leftType;
  7281. }
  7282. }
  7283. // NOTE: Limiting this operator to working only on basic numeric types.
  7284. // This is due to extremely limited (and even broken) support for any other case.
  7285. // In the future we may decide to support more cases.
  7286. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_typecheck);
  7287. return QualType();
  7288. }
  7289. // Types should be only scalar, vector, or matrix after this point.
  7290. ArBasicKind resultElementKind = leftElementKind;
  7291. // Combine LHS and RHS element types for computation.
  7292. if (leftElementKind != rightElementKind) {
  7293. if (!CombineBasicTypes(leftElementKind, rightElementKind, &resultElementKind, nullptr, nullptr)) {
  7294. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_comptype_mismatch);
  7295. return QualType();
  7296. }
  7297. }
  7298. // Combine LHS and RHS dimensions
  7299. if (FAILED(CombineDimensions(leftType, rightType, &ResultTy))) {
  7300. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_result_dimensions);
  7301. return QualType();
  7302. }
  7303. // If result is scalar, use condition dimensions.
  7304. // Otherwise, condition must either match or is scalar, then use result dimensions
  7305. if (rowCount * colCount == 1) {
  7306. rowCount = rowCountCond;
  7307. colCount = colCountCond;
  7308. }
  7309. else if (rowCountCond * colCountCond != 1 && (rowCountCond != rowCount || colCountCond != colCount)) {
  7310. m_sema->Diag(QuestionLoc, diag::err_hlsl_conditional_dimensions);
  7311. return QualType();
  7312. }
  7313. // Here, element kind is combined with dimensions for result type.
  7314. ResultTy = NewSimpleAggregateType(AR_TOBJ_INVALID, resultElementKind, 0, rowCount, colCount)->getCanonicalTypeInternal();
  7315. // Cast condition to RValue
  7316. if (Cond.get()->isLValue())
  7317. Cond.set(CreateLValueToRValueCast(Cond.get()));
  7318. // Convert condition component type to bool, using result component dimensions
  7319. if (condElementKind != AR_BASIC_BOOL) {
  7320. Cond = CastExprToTypeNumeric(Cond.get(),
  7321. NewSimpleAggregateType(AR_TOBJ_INVALID, AR_BASIC_BOOL, 0, rowCount, colCount)->getCanonicalTypeInternal());
  7322. }
  7323. // Cast LHS/RHS to RValue
  7324. if (LHS.get()->isLValue())
  7325. LHS.set(CreateLValueToRValueCast(LHS.get()));
  7326. if (RHS.get()->isLValue())
  7327. RHS.set(CreateLValueToRValueCast(RHS.get()));
  7328. // TODO: Why isn't vector truncation being reported?
  7329. if (leftType != ResultTy) {
  7330. LHS = CastExprToTypeNumeric(LHS.get(), ResultTy);
  7331. }
  7332. if (rightType != ResultTy) {
  7333. RHS = CastExprToTypeNumeric(RHS.get(), ResultTy);
  7334. }
  7335. return ResultTy;
  7336. }
  7337. // Apply type specifier sign to the given QualType.
  7338. // Other than privmitive int type, only allow shorthand vectors and matrices to be unsigned.
  7339. clang::QualType HLSLExternalSource::ApplyTypeSpecSignToParsedType(
  7340. _In_ clang::QualType &type, _In_ clang::TypeSpecifierSign TSS,
  7341. _In_ clang::SourceLocation Loc) {
  7342. if (TSS == TypeSpecifierSign::TSS_unspecified) {
  7343. return type;
  7344. }
  7345. DXASSERT(TSS != TypeSpecifierSign::TSS_signed, "else signed keyword is supported in HLSL");
  7346. ArTypeObjectKind objKind = GetTypeObjectKind(type);
  7347. if (objKind != AR_TOBJ_VECTOR && objKind != AR_TOBJ_MATRIX &&
  7348. objKind != AR_TOBJ_BASIC && objKind != AR_TOBJ_ARRAY) {
  7349. return type;
  7350. }
  7351. // check if element type is unsigned and check if such vector exists
  7352. // If not create a new one, Make a QualType of the new kind
  7353. ArBasicKind elementKind = GetTypeElementKind(type);
  7354. // Only ints can have signed/unsigend ty
  7355. if (!IS_BASIC_UNSIGNABLE(elementKind)) {
  7356. return type;
  7357. }
  7358. else {
  7359. // Check given TypeSpecifierSign. If unsigned, change int to uint.
  7360. HLSLScalarType scalarType = ScalarTypeForBasic(elementKind);
  7361. HLSLScalarType newScalarType = MakeUnsigned(scalarType);
  7362. // Get new vector types for a given TypeSpecifierSign.
  7363. if (objKind == AR_TOBJ_VECTOR) {
  7364. UINT colCount = GetHLSLVecSize(type);
  7365. TypedefDecl *qts = LookupVectorShorthandType(newScalarType, colCount);
  7366. return m_context->getTypeDeclType(qts);
  7367. } else if (objKind == AR_TOBJ_MATRIX) {
  7368. UINT rowCount, colCount;
  7369. GetRowsAndCols(type, rowCount, colCount);
  7370. TypedefDecl *qts = LookupMatrixShorthandType(newScalarType, rowCount, colCount);
  7371. return m_context->getTypeDeclType(qts);
  7372. } else {
  7373. DXASSERT_NOMSG(objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY);
  7374. return m_scalarTypes[newScalarType];
  7375. }
  7376. }
  7377. }
  7378. Sema::TemplateDeductionResult HLSLExternalSource::DeduceTemplateArgumentsForHLSL(
  7379. FunctionTemplateDecl *FunctionTemplate,
  7380. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  7381. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  7382. {
  7383. DXASSERT_NOMSG(FunctionTemplate != nullptr);
  7384. // Get information about the function we have.
  7385. CXXMethodDecl* functionMethod = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl());
  7386. DXASSERT(functionMethod != nullptr,
  7387. "otherwise this is standalone function rather than a method, which isn't supported in the HLSL object model");
  7388. CXXRecordDecl* functionParentRecord = functionMethod->getParent();
  7389. DXASSERT(functionParentRecord != nullptr, "otherwise function is orphaned");
  7390. QualType objectElement = GetFirstElementTypeFromDecl(functionParentRecord);
  7391. // Handle subscript overloads.
  7392. if (FunctionTemplate->getDeclName() == m_context->DeclarationNames.getCXXOperatorName(OO_Subscript))
  7393. {
  7394. DeclContext* functionTemplateContext = FunctionTemplate->getDeclContext();
  7395. FindStructBasicTypeResult findResult = FindStructBasicType(functionTemplateContext);
  7396. if (!findResult.Found())
  7397. {
  7398. // This might be a nested type. Do a lookup on the parent.
  7399. CXXRecordDecl* parentRecordType = dyn_cast_or_null<CXXRecordDecl>(functionTemplateContext);
  7400. if (parentRecordType == nullptr || parentRecordType->getDeclContext() == nullptr)
  7401. {
  7402. return Sema::TemplateDeductionResult::TDK_Invalid;
  7403. }
  7404. findResult = FindStructBasicType(parentRecordType->getDeclContext());
  7405. if (!findResult.Found())
  7406. {
  7407. return Sema::TemplateDeductionResult::TDK_Invalid;
  7408. }
  7409. DXASSERT(
  7410. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::CXXRecord ||
  7411. parentRecordType->getDeclContext()->getDeclKind() == Decl::Kind::ClassTemplateSpecialization,
  7412. "otherwise FindStructBasicType should have failed - no other types are allowed");
  7413. objectElement = GetFirstElementTypeFromDecl(
  7414. cast<CXXRecordDecl>(parentRecordType->getDeclContext()));
  7415. }
  7416. Specialization = AddSubscriptSpecialization(FunctionTemplate, objectElement, findResult);
  7417. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  7418. FunctionTemplate->getCanonicalDecl());
  7419. return Sema::TemplateDeductionResult::TDK_Success;
  7420. }
  7421. // Reject overload lookups that aren't identifier-based.
  7422. if (!FunctionTemplate->getDeclName().isIdentifier())
  7423. {
  7424. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  7425. }
  7426. // Find the table of intrinsics based on the object type.
  7427. const HLSL_INTRINSIC* intrinsics;
  7428. size_t intrinsicCount;
  7429. const char* objectName;
  7430. FindIntrinsicTable(FunctionTemplate->getDeclContext(), &objectName, &intrinsics, &intrinsicCount);
  7431. DXASSERT(intrinsics != nullptr,
  7432. "otherwise FindIntrinsicTable failed to lookup a valid object, "
  7433. "or the parser let a user-defined template object through");
  7434. // Look for an intrinsic for which we can match arguments.
  7435. size_t argCount;
  7436. QualType argTypes[g_MaxIntrinsicParamCount + 1];
  7437. StringRef nameIdentifier = FunctionTemplate->getName();
  7438. IntrinsicDefIter cursor = FindIntrinsicByNameAndArgCount(intrinsics, intrinsicCount, objectName, nameIdentifier, Args.size());
  7439. IntrinsicDefIter end = IntrinsicDefIter::CreateEnd(intrinsics, intrinsicCount, IntrinsicTableDefIter::CreateEnd(m_intrinsicTables));
  7440. while (cursor != end)
  7441. {
  7442. if (!MatchArguments(*cursor, objectElement, Args, argTypes, &argCount))
  7443. {
  7444. ++cursor;
  7445. continue;
  7446. }
  7447. // Currently only intrinsic we allow for explicit template arguments are
  7448. // for Load return types for ByteAddressBuffer/RWByteAddressBuffer
  7449. // TODO: handle template arguments for future intrinsics in a more natural way
  7450. // Check Explicit template arguments
  7451. UINT intrinsicOp = (*cursor)->Op;
  7452. LPCSTR intrinsicName = (*cursor)->pArgs[0].pName;
  7453. bool Is2018 = getSema()->getLangOpts().HLSLVersion >= 2018;
  7454. bool IsBAB =
  7455. objectName == g_ArBasicTypeNames[AR_OBJECT_BYTEADDRESS_BUFFER] ||
  7456. objectName == g_ArBasicTypeNames[AR_OBJECT_RWBYTEADDRESS_BUFFER];
  7457. bool IsBABLoad = IsBAB && intrinsicOp == (UINT)IntrinsicOp::MOP_Load;
  7458. bool IsBABStore = IsBAB && intrinsicOp == (UINT)IntrinsicOp::MOP_Store;
  7459. if (ExplicitTemplateArgs && ExplicitTemplateArgs->size() > 0) {
  7460. bool isLegalTemplate = false;
  7461. SourceLocation Loc = ExplicitTemplateArgs->getLAngleLoc();
  7462. auto TemplateDiag =
  7463. !IsBABLoad
  7464. ? diag::err_hlsl_intrinsic_template_arg_unsupported
  7465. : !Is2018 ? diag::err_hlsl_intrinsic_template_arg_requires_2018
  7466. : diag::err_hlsl_intrinsic_template_arg_requires_2018;
  7467. if (IsBABLoad && Is2018 && ExplicitTemplateArgs->size() == 1) {
  7468. Loc = (*ExplicitTemplateArgs)[0].getLocation();
  7469. QualType explicitType = (*ExplicitTemplateArgs)[0].getArgument().getAsType();
  7470. ArTypeObjectKind explicitKind = GetTypeObjectKind(explicitType);
  7471. if (explicitKind == AR_TOBJ_BASIC || explicitKind == AR_TOBJ_VECTOR) {
  7472. isLegalTemplate = GET_BASIC_BITS(GetTypeElementKind(explicitType)) != BPROP_BITS64 ||
  7473. GetNumElements(explicitType) <= 2;
  7474. }
  7475. if (isLegalTemplate) {
  7476. argTypes[0] = explicitType;
  7477. }
  7478. }
  7479. if (!isLegalTemplate) {
  7480. getSema()->Diag(Loc, TemplateDiag) << intrinsicName;
  7481. return Sema::TemplateDeductionResult::TDK_Invalid;
  7482. }
  7483. } else if (IsBABStore) {
  7484. // Prior to HLSL 2018, Store operation only stored scalar uint.
  7485. if (!Is2018) {
  7486. if (GetNumElements(argTypes[2]) != 1) {
  7487. getSema()->Diag(Args[1]->getLocStart(),
  7488. diag::err_ovl_no_viable_member_function_in_call)
  7489. << intrinsicName;
  7490. return Sema::TemplateDeductionResult::TDK_Invalid;
  7491. }
  7492. argTypes[2] = getSema()->getASTContext().getIntTypeForBitwidth(
  7493. 32, /*signed*/ false);
  7494. } else {
  7495. // not supporting types > 16 bytes yet.
  7496. if (GET_BASIC_BITS(GetTypeElementKind(argTypes[2])) == BPROP_BITS64 &&
  7497. GetNumElements(argTypes[2]) > 2) {
  7498. getSema()->Diag(Args[1]->getLocStart(),
  7499. diag::err_ovl_no_viable_member_function_in_call)
  7500. << intrinsicName;
  7501. return Sema::TemplateDeductionResult::TDK_Invalid;
  7502. }
  7503. }
  7504. }
  7505. Specialization = AddHLSLIntrinsicMethod(cursor.GetTableName(), cursor.GetLoweringStrategy(), *cursor, FunctionTemplate, Args, argTypes, argCount);
  7506. DXASSERT_NOMSG(Specialization->getPrimaryTemplate()->getCanonicalDecl() ==
  7507. FunctionTemplate->getCanonicalDecl());
  7508. if (!IsValidateObjectElement(*cursor, objectElement)) {
  7509. m_sema->Diag(Args[0]->getExprLoc(), diag::err_hlsl_invalid_resource_type_on_intrinsic) <<
  7510. nameIdentifier << g_ArBasicTypeNames[GetTypeElementKind(objectElement)];
  7511. }
  7512. return Sema::TemplateDeductionResult::TDK_Success;
  7513. }
  7514. return Sema::TemplateDeductionResult::TDK_NonDeducedMismatch;
  7515. }
  7516. void HLSLExternalSource::DiagnoseAssignmentResultForHLSL(
  7517. Sema::AssignConvertType ConvTy,
  7518. SourceLocation Loc,
  7519. QualType DstType, QualType SrcType,
  7520. _In_ Expr *SrcExpr, Sema::AssignmentAction Action,
  7521. _Out_opt_ bool *Complained)
  7522. {
  7523. if (Complained) *Complained = false;
  7524. // No work to do if there is not type change.
  7525. if (DstType == SrcType) {
  7526. return;
  7527. }
  7528. // Don't generate a warning if the user is casting explicitly
  7529. // or if initializing - our initialization handling already emits this.
  7530. if (Action == Sema::AssignmentAction::AA_Casting ||
  7531. Action == Sema::AssignmentAction::AA_Initializing) {
  7532. return;
  7533. }
  7534. ArBasicKind src = BasicTypeForScalarType(SrcType->getCanonicalTypeUnqualified());
  7535. if (src == AR_BASIC_UNKNOWN || src == AR_BASIC_BOOL) {
  7536. return;
  7537. }
  7538. ArBasicKind dst = BasicTypeForScalarType(DstType->getCanonicalTypeUnqualified());
  7539. if (dst == AR_BASIC_UNKNOWN) {
  7540. return;
  7541. }
  7542. bool warnAboutNarrowing = false;
  7543. switch (dst) {
  7544. case AR_BASIC_FLOAT32:
  7545. case AR_BASIC_INT32:
  7546. case AR_BASIC_UINT32:
  7547. case AR_BASIC_FLOAT16:
  7548. warnAboutNarrowing = src == AR_BASIC_FLOAT64;
  7549. break;
  7550. case AR_BASIC_MIN16FLOAT:
  7551. warnAboutNarrowing = (src == AR_BASIC_INT32 || src == AR_BASIC_UINT32 || src == AR_BASIC_FLOAT32 || src == AR_BASIC_FLOAT64);
  7552. break;
  7553. case AR_BASIC_MIN16INT:
  7554. case AR_BASIC_MIN16UINT:
  7555. case AR_BASIC_MIN12INT:
  7556. case AR_BASIC_MIN10FLOAT:
  7557. warnAboutNarrowing = (src == AR_BASIC_INT32 || src == AR_BASIC_UINT32 || src == AR_BASIC_FLOAT32 || src == AR_BASIC_FLOAT64);
  7558. break;
  7559. }
  7560. // fxc errors looked like this:
  7561. // warning X3205: conversion from larger type to smaller, possible loss of data
  7562. if (warnAboutNarrowing) {
  7563. m_sema->Diag(Loc, diag::warn_hlsl_narrowing) << SrcType << DstType;
  7564. AssignOpt(true, Complained);
  7565. }
  7566. }
  7567. void HLSLExternalSource::ReportUnsupportedTypeNesting(SourceLocation loc, QualType type)
  7568. {
  7569. m_sema->Diag(loc, diag::err_hlsl_unsupported_type_nesting) << type;
  7570. }
  7571. bool HLSLExternalSource::TryStaticCastForHLSL(ExprResult &SrcExpr,
  7572. QualType DestType,
  7573. Sema::CheckedConversionKind CCK,
  7574. const SourceRange &OpRange, unsigned &msg,
  7575. CastKind &Kind, CXXCastPath &BasePath,
  7576. bool ListInitialization, bool SuppressWarnings, bool SuppressErrors,
  7577. _Inout_opt_ StandardConversionSequence* standard)
  7578. {
  7579. DXASSERT(!SrcExpr.isInvalid(), "caller should check for invalid expressions and placeholder types");
  7580. bool explicitConversion
  7581. = (CCK == Sema::CCK_CStyleCast || CCK == Sema::CCK_FunctionalCast);
  7582. QualType sourceType = SrcExpr.get()->getType();
  7583. bool suppressWarnings = explicitConversion || SuppressWarnings;
  7584. SourceLocation loc = OpRange.getBegin();
  7585. if (ValidateCast(loc, SrcExpr.get(), DestType, explicitConversion, suppressWarnings, SuppressErrors, standard)) {
  7586. // TODO: LValue to RValue cast was all that CanConvert (ValidateCast) did anyway,
  7587. // so do this here until we figure out why this is needed.
  7588. if (standard && standard->First == ICK_Lvalue_To_Rvalue) {
  7589. SrcExpr.set(CreateLValueToRValueCast(SrcExpr.get()));
  7590. }
  7591. return true;
  7592. }
  7593. // ValidateCast includes its own error messages.
  7594. msg = 0;
  7595. return false;
  7596. }
  7597. /// <summary>
  7598. /// Checks if a subscript index argument can be initialized from the given expression.
  7599. /// </summary>
  7600. /// <param name="SrcExpr">Source expression used as argument.</param>
  7601. /// <param name="DestType">Parameter type to initialize.</param>
  7602. /// <remarks>
  7603. /// Rules for subscript index initialization follow regular implicit casting rules, with the exception that
  7604. /// no changes in arity are allowed (i.e., int2 can become uint2, but uint or uint3 cannot).
  7605. /// </remarks>
  7606. ImplicitConversionSequence
  7607. HLSLExternalSource::TrySubscriptIndexInitialization(_In_ clang::Expr *SrcExpr,
  7608. clang::QualType DestType) {
  7609. DXASSERT_NOMSG(SrcExpr != nullptr);
  7610. DXASSERT_NOMSG(!DestType.isNull());
  7611. unsigned int msg = 0;
  7612. CastKind kind;
  7613. CXXCastPath path;
  7614. ImplicitConversionSequence sequence;
  7615. sequence.setStandard();
  7616. ExprResult sourceExpr(SrcExpr);
  7617. if (GetElementCount(SrcExpr->getType()) != GetElementCount(DestType)) {
  7618. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  7619. SrcExpr->getType(), DestType);
  7620. } else if (!TryStaticCastForHLSL(
  7621. sourceExpr, DestType, Sema::CCK_ImplicitConversion, NoRange,
  7622. msg, kind, path, ListInitializationFalse,
  7623. SuppressWarningsFalse, SuppressErrorsTrue, &sequence.Standard)) {
  7624. sequence.setBad(BadConversionSequence::FailureKind::no_conversion,
  7625. SrcExpr->getType(), DestType);
  7626. }
  7627. return sequence;
  7628. }
  7629. template <typename T>
  7630. static
  7631. bool IsValueInRange(T value, T minValue, T maxValue) {
  7632. return minValue <= value && value <= maxValue;
  7633. }
  7634. #define D3DX_16F_MAX 6.550400e+004 // max value
  7635. #define D3DX_16F_MIN 6.1035156e-5f // min positive value
  7636. static
  7637. void GetFloatLimits(ArBasicKind basicKind, double* minValue, double* maxValue)
  7638. {
  7639. DXASSERT_NOMSG(minValue != nullptr);
  7640. DXASSERT_NOMSG(maxValue != nullptr);
  7641. switch (basicKind) {
  7642. case AR_BASIC_MIN10FLOAT:
  7643. case AR_BASIC_MIN16FLOAT:
  7644. case AR_BASIC_FLOAT16: *minValue = -(D3DX_16F_MIN); *maxValue = D3DX_16F_MAX; return;
  7645. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  7646. case AR_BASIC_FLOAT32: *minValue = -(FLT_MIN); *maxValue = FLT_MAX; return;
  7647. case AR_BASIC_FLOAT64: *minValue = -(DBL_MIN); *maxValue = DBL_MAX; return;
  7648. }
  7649. DXASSERT(false, "unreachable");
  7650. *minValue = 0; *maxValue = 0;
  7651. return;
  7652. }
  7653. static
  7654. void GetUnsignedLimit(ArBasicKind basicKind, uint64_t* maxValue)
  7655. {
  7656. DXASSERT_NOMSG(maxValue != nullptr);
  7657. switch (basicKind) {
  7658. case AR_BASIC_BOOL: *maxValue = 1; return;
  7659. case AR_BASIC_UINT8: *maxValue = UINT8_MAX; return;
  7660. case AR_BASIC_MIN16UINT:
  7661. case AR_BASIC_UINT16: *maxValue = UINT16_MAX; return;
  7662. case AR_BASIC_UINT32: *maxValue = UINT32_MAX; return;
  7663. case AR_BASIC_UINT64: *maxValue = UINT64_MAX; return;
  7664. }
  7665. DXASSERT(false, "unreachable");
  7666. *maxValue = 0;
  7667. return;
  7668. }
  7669. static
  7670. void GetSignedLimits(ArBasicKind basicKind, int64_t* minValue, int64_t* maxValue)
  7671. {
  7672. DXASSERT_NOMSG(minValue != nullptr);
  7673. DXASSERT_NOMSG(maxValue != nullptr);
  7674. switch (basicKind) {
  7675. case AR_BASIC_INT8: *minValue = INT8_MIN; *maxValue = INT8_MAX; return;
  7676. case AR_BASIC_MIN12INT:
  7677. case AR_BASIC_MIN16INT:
  7678. case AR_BASIC_INT16: *minValue = INT16_MIN; *maxValue = INT16_MAX; return;
  7679. case AR_BASIC_INT32: *minValue = INT32_MIN; *maxValue = INT32_MAX; return;
  7680. case AR_BASIC_INT64: *minValue = INT64_MIN; *maxValue = INT64_MAX; return;
  7681. }
  7682. DXASSERT(false, "unreachable");
  7683. *minValue = 0; *maxValue = 0;
  7684. return;
  7685. }
  7686. static
  7687. bool IsValueInBasicRange(ArBasicKind basicKind, const APValue& value)
  7688. {
  7689. if (IS_BASIC_FLOAT(basicKind)) {
  7690. double val;
  7691. if (value.isInt()) {
  7692. val = value.getInt().getLimitedValue();
  7693. } else if (value.isFloat()) {
  7694. llvm::APFloat floatValue = value.getFloat();
  7695. if (!floatValue.isFinite()) {
  7696. return false;
  7697. }
  7698. llvm::APFloat valueFloat = value.getFloat();
  7699. if (&valueFloat.getSemantics() == &llvm::APFloat::IEEEsingle) {
  7700. val = value.getFloat().convertToFloat();
  7701. }
  7702. else {
  7703. val = value.getFloat().convertToDouble();
  7704. }
  7705. } else {
  7706. return false;
  7707. }
  7708. double minValue, maxValue;
  7709. GetFloatLimits(basicKind, &minValue, &maxValue);
  7710. return IsValueInRange(val, minValue, maxValue);
  7711. }
  7712. else if (IS_BASIC_SINT(basicKind)) {
  7713. if (!value.isInt()) {
  7714. return false;
  7715. }
  7716. int64_t val = value.getInt().getSExtValue();
  7717. int64_t minValue, maxValue;
  7718. GetSignedLimits(basicKind, &minValue, &maxValue);
  7719. return IsValueInRange(val, minValue, maxValue);
  7720. }
  7721. else if (IS_BASIC_UINT(basicKind) || IS_BASIC_BOOL(basicKind)) {
  7722. if (!value.isInt()) {
  7723. return false;
  7724. }
  7725. uint64_t val = value.getInt().getLimitedValue();
  7726. uint64_t maxValue;
  7727. GetUnsignedLimit(basicKind, &maxValue);
  7728. return IsValueInRange(val, (uint64_t)0, maxValue);
  7729. }
  7730. else {
  7731. return false;
  7732. }
  7733. }
  7734. static
  7735. bool IsPrecisionLossIrrelevant(ASTContext& Ctx, _In_ const Expr* sourceExpr, QualType targetType, ArBasicKind targetKind)
  7736. {
  7737. DXASSERT_NOMSG(!targetType.isNull());
  7738. DXASSERT_NOMSG(sourceExpr != nullptr);
  7739. Expr::EvalResult evalResult;
  7740. if (sourceExpr->EvaluateAsRValue(evalResult, Ctx)) {
  7741. if (evalResult.Diag == nullptr || evalResult.Diag->empty()) {
  7742. return IsValueInBasicRange(targetKind, evalResult.Val);
  7743. }
  7744. }
  7745. return false;
  7746. }
  7747. bool HLSLExternalSource::ValidateCast(
  7748. SourceLocation OpLoc,
  7749. _In_ Expr* sourceExpr,
  7750. QualType target,
  7751. bool explicitConversion,
  7752. bool suppressWarnings,
  7753. bool suppressErrors,
  7754. _Inout_opt_ StandardConversionSequence* standard)
  7755. {
  7756. DXASSERT_NOMSG(sourceExpr != nullptr);
  7757. QualType source = sourceExpr->getType();
  7758. TYPE_CONVERSION_REMARKS remarks;
  7759. if (!CanConvert(OpLoc, sourceExpr, target, explicitConversion, &remarks, standard))
  7760. {
  7761. const bool IsOutputParameter = false;
  7762. //
  7763. // Check whether the lack of explicit-ness matters.
  7764. //
  7765. // Setting explicitForDiagnostics to true in that case will avoid the message
  7766. // saying anything about the implicit nature of the cast, when adding the
  7767. // explicit cast won't make a difference.
  7768. //
  7769. bool explicitForDiagnostics = explicitConversion;
  7770. if (explicitConversion == false)
  7771. {
  7772. if (!CanConvert(OpLoc, sourceExpr, target, true, &remarks, nullptr))
  7773. {
  7774. // Can't convert either way - implicit/explicit doesn't matter.
  7775. explicitForDiagnostics = true;
  7776. }
  7777. }
  7778. if (!suppressErrors)
  7779. {
  7780. m_sema->Diag(OpLoc, diag::err_hlsl_cannot_convert)
  7781. << explicitForDiagnostics << IsOutputParameter << source << target;
  7782. }
  7783. return false;
  7784. }
  7785. if (!suppressWarnings)
  7786. {
  7787. if (!explicitConversion)
  7788. {
  7789. if ((remarks & TYPE_CONVERSION_PRECISION_LOSS) != 0)
  7790. {
  7791. // This is a much more restricted version of the analysis does
  7792. // StandardConversionSequence::getNarrowingKind
  7793. if (!IsPrecisionLossIrrelevant(*m_context, sourceExpr, target, GetTypeElementKind(target)))
  7794. {
  7795. m_sema->Diag(OpLoc, diag::warn_hlsl_narrowing) << source << target;
  7796. }
  7797. }
  7798. if ((remarks & TYPE_CONVERSION_ELT_TRUNCATION) != 0)
  7799. {
  7800. m_sema->Diag(OpLoc, diag::warn_hlsl_implicit_vector_truncation);
  7801. }
  7802. }
  7803. }
  7804. return true;
  7805. }
  7806. ////////////////////////////////////////////////////////////////////////////////
  7807. // Functions exported from this translation unit. //
  7808. /// <summary>Performs HLSL-specific processing for unary operators.</summary>
  7809. QualType hlsl::CheckUnaryOpForHLSL(Sema& self,
  7810. SourceLocation OpLoc,
  7811. UnaryOperatorKind Opc,
  7812. ExprResult& InputExpr,
  7813. ExprValueKind& VK,
  7814. ExprObjectKind& OK)
  7815. {
  7816. ExternalSemaSource* externalSource = self.getExternalSource();
  7817. if (externalSource == nullptr) {
  7818. return QualType();
  7819. }
  7820. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  7821. return hlsl->CheckUnaryOpForHLSL(OpLoc, Opc, InputExpr, VK, OK);
  7822. }
  7823. /// <summary>Performs HLSL-specific processing for binary operators.</summary>
  7824. void hlsl::CheckBinOpForHLSL(Sema& self,
  7825. SourceLocation OpLoc,
  7826. BinaryOperatorKind Opc,
  7827. ExprResult& LHS,
  7828. ExprResult& RHS,
  7829. QualType& ResultTy,
  7830. QualType& CompLHSTy,
  7831. QualType& CompResultTy)
  7832. {
  7833. ExternalSemaSource* externalSource = self.getExternalSource();
  7834. if (externalSource == nullptr) {
  7835. return;
  7836. }
  7837. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  7838. return hlsl->CheckBinOpForHLSL(OpLoc, Opc, LHS, RHS, ResultTy, CompLHSTy, CompResultTy);
  7839. }
  7840. /// <summary>Performs HLSL-specific processing of template declarations.</summary>
  7841. bool hlsl::CheckTemplateArgumentListForHLSL(Sema& self, TemplateDecl* Template, SourceLocation TemplateLoc, TemplateArgumentListInfo& TemplateArgList)
  7842. {
  7843. DXASSERT_NOMSG(Template != nullptr);
  7844. ExternalSemaSource* externalSource = self.getExternalSource();
  7845. if (externalSource == nullptr) {
  7846. return false;
  7847. }
  7848. HLSLExternalSource* hlsl = reinterpret_cast<HLSLExternalSource*>(externalSource);
  7849. return hlsl->CheckTemplateArgumentListForHLSL(Template, TemplateLoc, TemplateArgList);
  7850. }
  7851. /// <summary>Deduces template arguments on a function call in an HLSL program.</summary>
  7852. Sema::TemplateDeductionResult hlsl::DeduceTemplateArgumentsForHLSL(Sema* self,
  7853. FunctionTemplateDecl *FunctionTemplate,
  7854. TemplateArgumentListInfo *ExplicitTemplateArgs, ArrayRef<Expr *> Args,
  7855. FunctionDecl *&Specialization, TemplateDeductionInfo &Info)
  7856. {
  7857. return HLSLExternalSource::FromSema(self)
  7858. ->DeduceTemplateArgumentsForHLSL(FunctionTemplate, ExplicitTemplateArgs, Args, Specialization, Info);
  7859. }
  7860. void hlsl::DiagnoseAssignmentResultForHLSL(Sema* self,
  7861. Sema::AssignConvertType ConvTy,
  7862. SourceLocation Loc,
  7863. QualType DstType, QualType SrcType,
  7864. Expr *SrcExpr, Sema::AssignmentAction Action,
  7865. bool *Complained)
  7866. {
  7867. return HLSLExternalSource::FromSema(self)
  7868. ->DiagnoseAssignmentResultForHLSL(ConvTy, Loc, DstType, SrcType, SrcExpr, Action, Complained);
  7869. }
  7870. void hlsl::DiagnoseControlFlowConditionForHLSL(Sema *self, Expr *condExpr, StringRef StmtName) {
  7871. while (ImplicitCastExpr *IC = dyn_cast<ImplicitCastExpr>(condExpr)) {
  7872. if (IC->getCastKind() == CastKind::CK_HLSLMatrixTruncationCast ||
  7873. IC->getCastKind() == CastKind::CK_HLSLVectorTruncationCast) {
  7874. self->Diag(condExpr->getLocStart(),
  7875. diag::err_hlsl_control_flow_cond_not_scalar)
  7876. << StmtName;
  7877. return;
  7878. }
  7879. condExpr = IC->getSubExpr();
  7880. }
  7881. }
  7882. static bool ShaderModelsMatch(const StringRef& left, const StringRef& right)
  7883. {
  7884. // TODO: handle shorthand cases.
  7885. return left.size() == 0 || right.size() == 0 || left.equals(right);
  7886. }
  7887. void hlsl::DiagnosePackingOffset(
  7888. clang::Sema* self,
  7889. SourceLocation loc,
  7890. clang::QualType type,
  7891. int componentOffset)
  7892. {
  7893. DXASSERT_NOMSG(0 <= componentOffset && componentOffset <= 3);
  7894. if (componentOffset > 0) {
  7895. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  7896. ArBasicKind element = source->GetTypeElementKind(type);
  7897. ArTypeObjectKind shape = source->GetTypeObjectKind(type);
  7898. // Only perform some simple validation for now.
  7899. if (IsObjectKindPrimitiveAggregate(shape) && IsBasicKindNumeric(element)) {
  7900. int count = GetElementCount(type);
  7901. if (count > (4 - componentOffset)) {
  7902. self->Diag(loc, diag::err_hlsl_register_or_offset_bind_not_valid);
  7903. }
  7904. }
  7905. }
  7906. }
  7907. void hlsl::DiagnoseRegisterType(
  7908. clang::Sema* self,
  7909. clang::SourceLocation loc,
  7910. clang::QualType type,
  7911. char registerType)
  7912. {
  7913. HLSLExternalSource* source = HLSLExternalSource::FromSema(self);
  7914. ArBasicKind element = source->GetTypeElementKind(type);
  7915. StringRef expected("none");
  7916. bool isValid = true;
  7917. bool isWarning = false;
  7918. switch (element)
  7919. {
  7920. case AR_BASIC_BOOL:
  7921. case AR_BASIC_LITERAL_FLOAT:
  7922. case AR_BASIC_FLOAT16:
  7923. case AR_BASIC_FLOAT32_PARTIAL_PRECISION:
  7924. case AR_BASIC_FLOAT32:
  7925. case AR_BASIC_FLOAT64:
  7926. case AR_BASIC_LITERAL_INT:
  7927. case AR_BASIC_INT8:
  7928. case AR_BASIC_UINT8:
  7929. case AR_BASIC_INT16:
  7930. case AR_BASIC_UINT16:
  7931. case AR_BASIC_INT32:
  7932. case AR_BASIC_UINT32:
  7933. case AR_BASIC_INT64:
  7934. case AR_BASIC_UINT64:
  7935. case AR_BASIC_MIN10FLOAT:
  7936. case AR_BASIC_MIN16FLOAT:
  7937. case AR_BASIC_MIN12INT:
  7938. case AR_BASIC_MIN16INT:
  7939. case AR_BASIC_MIN16UINT:
  7940. expected = "'b', 'c', or 'i'";
  7941. isValid = registerType == 'b' || registerType == 'c' || registerType == 'i' ||
  7942. registerType == 'B' || registerType == 'C' || registerType == 'I';
  7943. break;
  7944. case AR_OBJECT_TEXTURE1D:
  7945. case AR_OBJECT_TEXTURE1D_ARRAY:
  7946. case AR_OBJECT_TEXTURE2D:
  7947. case AR_OBJECT_TEXTURE2D_ARRAY:
  7948. case AR_OBJECT_TEXTURE3D:
  7949. case AR_OBJECT_TEXTURECUBE:
  7950. case AR_OBJECT_TEXTURECUBE_ARRAY:
  7951. case AR_OBJECT_TEXTURE2DMS:
  7952. case AR_OBJECT_TEXTURE2DMS_ARRAY:
  7953. expected = "'t' or 's'";
  7954. isValid = registerType == 't' || registerType == 's' ||
  7955. registerType == 'T' || registerType == 'S';
  7956. break;
  7957. case AR_OBJECT_SAMPLER:
  7958. case AR_OBJECT_SAMPLER1D:
  7959. case AR_OBJECT_SAMPLER2D:
  7960. case AR_OBJECT_SAMPLER3D:
  7961. case AR_OBJECT_SAMPLERCUBE:
  7962. case AR_OBJECT_SAMPLERCOMPARISON:
  7963. expected = "'s' or 't'";
  7964. isValid = registerType == 's' || registerType == 't' ||
  7965. registerType == 'S' || registerType == 'T';
  7966. break;
  7967. case AR_OBJECT_BUFFER:
  7968. expected = "'t'";
  7969. isValid = registerType == 't' || registerType == 'T';
  7970. break;
  7971. case AR_OBJECT_POINTSTREAM:
  7972. case AR_OBJECT_LINESTREAM:
  7973. case AR_OBJECT_TRIANGLESTREAM:
  7974. isValid = false;
  7975. isWarning = true;
  7976. break;
  7977. case AR_OBJECT_INPUTPATCH:
  7978. case AR_OBJECT_OUTPUTPATCH:
  7979. isValid = false;
  7980. isWarning = true;
  7981. break;
  7982. case AR_OBJECT_RWTEXTURE1D:
  7983. case AR_OBJECT_RWTEXTURE1D_ARRAY:
  7984. case AR_OBJECT_RWTEXTURE2D:
  7985. case AR_OBJECT_RWTEXTURE2D_ARRAY:
  7986. case AR_OBJECT_RWTEXTURE3D:
  7987. case AR_OBJECT_RWBUFFER:
  7988. expected = "'u'";
  7989. isValid = registerType == 'u' || registerType == 'U';
  7990. break;
  7991. case AR_OBJECT_BYTEADDRESS_BUFFER:
  7992. case AR_OBJECT_STRUCTURED_BUFFER:
  7993. expected = "'t'";
  7994. isValid = registerType == 't' || registerType == 'T';
  7995. break;
  7996. case AR_OBJECT_CONSUME_STRUCTURED_BUFFER:
  7997. case AR_OBJECT_RWBYTEADDRESS_BUFFER:
  7998. case AR_OBJECT_RWSTRUCTURED_BUFFER:
  7999. case AR_OBJECT_RWSTRUCTURED_BUFFER_ALLOC:
  8000. case AR_OBJECT_RWSTRUCTURED_BUFFER_CONSUME:
  8001. case AR_OBJECT_APPEND_STRUCTURED_BUFFER:
  8002. expected = "'u'";
  8003. isValid = registerType == 'u' || registerType == 'U';
  8004. break;
  8005. case AR_OBJECT_CONSTANT_BUFFER:
  8006. expected = "'b'";
  8007. isValid = registerType == 'b' || registerType == 'B';
  8008. break;
  8009. case AR_OBJECT_TEXTURE_BUFFER:
  8010. expected = "'t'";
  8011. isValid = registerType == 't' || registerType == 'T';
  8012. break;
  8013. case AR_OBJECT_ROVBUFFER:
  8014. case AR_OBJECT_ROVBYTEADDRESS_BUFFER:
  8015. case AR_OBJECT_ROVSTRUCTURED_BUFFER:
  8016. case AR_OBJECT_ROVTEXTURE1D:
  8017. case AR_OBJECT_ROVTEXTURE1D_ARRAY:
  8018. case AR_OBJECT_ROVTEXTURE2D:
  8019. case AR_OBJECT_ROVTEXTURE2D_ARRAY:
  8020. case AR_OBJECT_ROVTEXTURE3D:
  8021. expected = "'u'";
  8022. isValid = registerType == 'u' || registerType == 'U';
  8023. break;
  8024. case AR_OBJECT_LEGACY_EFFECT: // Used for all unsupported but ignored legacy effect types
  8025. isWarning = true;
  8026. break; // So we don't care what you tried to bind it to
  8027. };
  8028. // fxc is inconsistent as to when it reports an error and when it ignores invalid bind semantics, so emit
  8029. // a warning instead.
  8030. if (!isValid)
  8031. {
  8032. if (isWarning)
  8033. self->Diag(loc, diag::warn_hlsl_incorrect_bind_semantic) << expected;
  8034. else
  8035. self->Diag(loc, diag::err_hlsl_incorrect_bind_semantic) << expected;
  8036. }
  8037. }
  8038. struct NameLookup {
  8039. FunctionDecl *Found;
  8040. FunctionDecl *Other;
  8041. };
  8042. static NameLookup GetSingleFunctionDeclByName(clang::Sema *self, StringRef Name, bool checkPatch) {
  8043. auto DN = DeclarationName(&self->getASTContext().Idents.get(Name));
  8044. FunctionDecl *pFoundDecl = nullptr;
  8045. for (auto idIter = self->IdResolver.begin(DN), idEnd = self->IdResolver.end(); idIter != idEnd; ++idIter) {
  8046. FunctionDecl *pFnDecl = dyn_cast<FunctionDecl>(*idIter);
  8047. if (!pFnDecl) continue;
  8048. if (checkPatch && !self->getASTContext().IsPatchConstantFunctionDecl(pFnDecl)) continue;
  8049. if (pFoundDecl) {
  8050. return NameLookup{ pFoundDecl, pFnDecl };
  8051. }
  8052. pFoundDecl = pFnDecl;
  8053. }
  8054. return NameLookup{ pFoundDecl, nullptr };
  8055. }
  8056. void hlsl::DiagnoseTranslationUnit(clang::Sema *self) {
  8057. DXASSERT_NOMSG(self != nullptr);
  8058. // Don't bother with global validation if compilation has already failed.
  8059. if (self->getDiagnostics().hasErrorOccurred()) {
  8060. return;
  8061. }
  8062. // Don't check entry function for library.
  8063. if (self->getLangOpts().IsHLSLLibrary) {
  8064. // TODO: validate no recursion start from every function.
  8065. return;
  8066. }
  8067. // TODO: make these error 'real' errors rather than on-the-fly things
  8068. // Validate that the entry point is available.
  8069. ASTContext &Ctx = self->getASTContext();
  8070. DiagnosticsEngine &Diags = self->getDiagnostics();
  8071. FunctionDecl *pEntryPointDecl = nullptr;
  8072. FunctionDecl *pPatchFnDecl = nullptr;
  8073. const std::string &EntryPointName = self->getLangOpts().HLSLEntryFunction;
  8074. if (!EntryPointName.empty()) {
  8075. NameLookup NL = GetSingleFunctionDeclByName(self, EntryPointName, /*checkPatch*/ false);
  8076. if (NL.Found && NL.Other) {
  8077. // NOTE: currently we cannot hit this codepath when CodeGen is enabled, because
  8078. // CodeGenModule::getMangledName will mangle the entry point name into the bare
  8079. // string, and so ambiguous points will produce an error earlier on.
  8080. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8081. "ambiguous entry point function");
  8082. Diags.Report(NL.Found->getSourceRange().getBegin(), id);
  8083. Diags.Report(NL.Other->getLocation(), diag::note_previous_definition);
  8084. return;
  8085. }
  8086. pEntryPointDecl = NL.Found;
  8087. if (!pEntryPointDecl || !pEntryPointDecl->hasBody()) {
  8088. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8089. "missing entry point definition");
  8090. Diags.Report(id);
  8091. return;
  8092. }
  8093. }
  8094. // Validate that there is no recursion; start with the entry function.
  8095. // NOTE: the information gathered here could be used to bypass code generation
  8096. // on functions that are unreachable (as an early form of dead code elimination).
  8097. if (pEntryPointDecl) {
  8098. const auto *shaderModel =
  8099. hlsl::ShaderModel::GetByName(self->getLangOpts().HLSLProfile.c_str());
  8100. if (shaderModel->IsGS()) {
  8101. // Validate that GS has the maxvertexcount attribute
  8102. if (!pEntryPointDecl->hasAttr<HLSLMaxVertexCountAttr>()) {
  8103. self->Diag(pEntryPointDecl->getLocation(),
  8104. diag::err_hlsl_missing_maxvertexcount_attr);
  8105. return;
  8106. }
  8107. } else if (shaderModel->IsHS()) {
  8108. if (const HLSLPatchConstantFuncAttr *Attr =
  8109. pEntryPointDecl->getAttr<HLSLPatchConstantFuncAttr>()) {
  8110. NameLookup NL = GetSingleFunctionDeclByName(
  8111. self, Attr->getFunctionName(), /*checkPatch*/ true);
  8112. if (!NL.Found || !NL.Found->hasBody()) {
  8113. unsigned id =
  8114. Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8115. "missing patch function definition");
  8116. Diags.Report(id);
  8117. return;
  8118. }
  8119. pPatchFnDecl = NL.Found;
  8120. } else {
  8121. self->Diag(pEntryPointDecl->getLocation(),
  8122. diag::err_hlsl_missing_patchconstantfunc_attr);
  8123. return;
  8124. }
  8125. }
  8126. hlsl::CallGraphWithRecurseGuard CG;
  8127. CG.BuildForEntry(pEntryPointDecl);
  8128. Decl *pResult = CG.CheckRecursion(pEntryPointDecl);
  8129. if (pResult) {
  8130. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8131. "recursive functions not allowed");
  8132. Diags.Report(pResult->getSourceRange().getBegin(), id);
  8133. }
  8134. if (pPatchFnDecl) {
  8135. CG.BuildForEntry(pPatchFnDecl);
  8136. Decl *pPatchFnDecl = CG.CheckRecursion(pEntryPointDecl);
  8137. if (pPatchFnDecl) {
  8138. unsigned id = Diags.getCustomDiagID(clang::DiagnosticsEngine::Level::Error,
  8139. "recursive functions not allowed (via patch function)");
  8140. Diags.Report(pPatchFnDecl->getSourceRange().getBegin(), id);
  8141. }
  8142. }
  8143. }
  8144. }
  8145. void hlsl::DiagnoseUnusualAnnotationsForHLSL(
  8146. Sema& S,
  8147. std::vector<hlsl::UnusualAnnotation *>& annotations)
  8148. {
  8149. bool packoffsetOverriddenReported = false;
  8150. auto && iter = annotations.begin();
  8151. auto && end = annotations.end();
  8152. for (; iter != end; ++iter) {
  8153. switch ((*iter)->getKind()) {
  8154. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  8155. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*iter);
  8156. // Check whether this will conflict with other packoffsets. If so, only issue a warning; last one wins.
  8157. if (!packoffsetOverriddenReported) {
  8158. auto newIter = iter;
  8159. ++newIter;
  8160. while (newIter != end) {
  8161. hlsl::ConstantPacking* other = dyn_cast_or_null<hlsl::ConstantPacking>(*newIter);
  8162. if (other != nullptr &&
  8163. (other->Subcomponent != constantPacking->Subcomponent || other->ComponentOffset != constantPacking->ComponentOffset)) {
  8164. S.Diag(constantPacking->Loc, diag::warn_hlsl_packoffset_overridden);
  8165. packoffsetOverriddenReported = true;
  8166. break;
  8167. }
  8168. ++newIter;
  8169. }
  8170. }
  8171. break;
  8172. }
  8173. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  8174. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*iter);
  8175. // Check whether this will conflict with other register assignments of the same type.
  8176. auto newIter = iter;
  8177. ++newIter;
  8178. while (newIter != end) {
  8179. hlsl::RegisterAssignment* other = dyn_cast_or_null<hlsl::RegisterAssignment>(*newIter);
  8180. // Same register bank and profile, but different number.
  8181. if (other != nullptr &&
  8182. ShaderModelsMatch(other->ShaderProfile, registerAssignment->ShaderProfile) &&
  8183. other->RegisterType == registerAssignment->RegisterType &&
  8184. (other->RegisterNumber != registerAssignment->RegisterNumber ||
  8185. other->RegisterOffset != registerAssignment->RegisterOffset)) {
  8186. // Obvious conflict - report it up front.
  8187. S.Diag(registerAssignment->Loc, diag::err_hlsl_register_semantics_conflicting);
  8188. }
  8189. ++newIter;
  8190. }
  8191. break;
  8192. }
  8193. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  8194. // hlsl::SemanticDecl* semanticDecl = cast<hlsl::SemanticDecl>(*iter);
  8195. // No common validation to be performed.
  8196. break;
  8197. }
  8198. }
  8199. }
  8200. }
  8201. clang::OverloadingResult
  8202. hlsl::GetBestViableFunction(clang::Sema &S, clang::SourceLocation Loc,
  8203. clang::OverloadCandidateSet &set,
  8204. clang::OverloadCandidateSet::iterator &Best) {
  8205. return HLSLExternalSource::FromSema(&S)
  8206. ->GetBestViableFunction(Loc, set, Best);
  8207. }
  8208. void hlsl::InitializeInitSequenceForHLSL(Sema *self,
  8209. const InitializedEntity &Entity,
  8210. const InitializationKind &Kind,
  8211. MultiExprArg Args,
  8212. bool TopLevelOfInitList,
  8213. InitializationSequence *initSequence) {
  8214. return HLSLExternalSource::FromSema(self)
  8215. ->InitializeInitSequenceForHLSL(Entity, Kind, Args, TopLevelOfInitList, initSequence);
  8216. }
  8217. static unsigned CaculateInitListSize(HLSLExternalSource *hlslSource,
  8218. const clang::InitListExpr *InitList) {
  8219. unsigned totalSize = 0;
  8220. for (unsigned i = 0; i < InitList->getNumInits(); i++) {
  8221. const clang::Expr *EltInit = InitList->getInit(i);
  8222. QualType EltInitTy = EltInit->getType();
  8223. if (const InitListExpr *EltInitList = dyn_cast<InitListExpr>(EltInit)) {
  8224. totalSize += CaculateInitListSize(hlslSource, EltInitList);
  8225. } else {
  8226. totalSize += hlslSource->GetNumBasicElements(EltInitTy);
  8227. }
  8228. }
  8229. return totalSize;
  8230. }
  8231. unsigned hlsl::CaculateInitListArraySizeForHLSL(
  8232. _In_ clang::Sema* sema,
  8233. _In_ const clang::InitListExpr *InitList,
  8234. _In_ const clang::QualType EltTy) {
  8235. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(sema);
  8236. unsigned totalSize = CaculateInitListSize(hlslSource, InitList);
  8237. unsigned eltSize = hlslSource->GetNumBasicElements(EltTy);
  8238. if (totalSize > 0 && (totalSize % eltSize)==0) {
  8239. return totalSize / eltSize;
  8240. } else {
  8241. return 0;
  8242. }
  8243. }
  8244. bool hlsl::IsConversionToLessOrEqualElements(
  8245. _In_ clang::Sema* self,
  8246. const clang::ExprResult& sourceExpr,
  8247. const clang::QualType& targetType,
  8248. bool explicitConversion)
  8249. {
  8250. return HLSLExternalSource::FromSema(self)
  8251. ->IsConversionToLessOrEqualElements(sourceExpr, targetType, explicitConversion);
  8252. }
  8253. bool hlsl::LookupMatrixMemberExprForHLSL(
  8254. Sema* self,
  8255. Expr& BaseExpr,
  8256. DeclarationName MemberName,
  8257. bool IsArrow,
  8258. SourceLocation OpLoc,
  8259. SourceLocation MemberLoc,
  8260. ExprResult* result)
  8261. {
  8262. return HLSLExternalSource::FromSema(self)
  8263. ->LookupMatrixMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc, result);
  8264. }
  8265. bool hlsl::LookupVectorMemberExprForHLSL(
  8266. Sema* self,
  8267. Expr& BaseExpr,
  8268. DeclarationName MemberName,
  8269. bool IsArrow,
  8270. SourceLocation OpLoc,
  8271. SourceLocation MemberLoc,
  8272. ExprResult* result)
  8273. {
  8274. return HLSLExternalSource::FromSema(self)
  8275. ->LookupVectorMemberExprForHLSL(BaseExpr, MemberName, IsArrow, OpLoc, MemberLoc, result);
  8276. }
  8277. clang::ExprResult hlsl::MaybeConvertScalarToVector(
  8278. _In_ clang::Sema* self,
  8279. _In_ clang::Expr* E)
  8280. {
  8281. return HLSLExternalSource::FromSema(self)->MaybeConvertScalarToVector(E);
  8282. }
  8283. bool hlsl::TryStaticCastForHLSL(_In_ Sema* self, ExprResult &SrcExpr,
  8284. QualType DestType,
  8285. Sema::CheckedConversionKind CCK,
  8286. const SourceRange &OpRange, unsigned &msg,
  8287. CastKind &Kind, CXXCastPath &BasePath,
  8288. bool ListInitialization,
  8289. bool SuppressDiagnostics,
  8290. _Inout_opt_ StandardConversionSequence* standard)
  8291. {
  8292. return HLSLExternalSource::FromSema(self)->TryStaticCastForHLSL(
  8293. SrcExpr, DestType, CCK, OpRange, msg, Kind, BasePath, ListInitialization,
  8294. SuppressDiagnostics, SuppressDiagnostics, standard);
  8295. }
  8296. clang::ExprResult hlsl::PerformHLSLConversion(
  8297. _In_ clang::Sema* self,
  8298. _In_ clang::Expr* From,
  8299. _In_ clang::QualType targetType,
  8300. _In_ const clang::StandardConversionSequence &SCS,
  8301. _In_ clang::Sema::CheckedConversionKind CCK)
  8302. {
  8303. return HLSLExternalSource::FromSema(self)->PerformHLSLConversion(From, targetType, SCS, CCK);
  8304. }
  8305. clang::ImplicitConversionSequence hlsl::TrySubscriptIndexInitialization(
  8306. _In_ clang::Sema* self,
  8307. _In_ clang::Expr* SrcExpr,
  8308. clang::QualType DestType)
  8309. {
  8310. return HLSLExternalSource::FromSema(self)
  8311. ->TrySubscriptIndexInitialization(SrcExpr, DestType);
  8312. }
  8313. /// <summary>Performs HLSL-specific initialization on the specified context.</summary>
  8314. void hlsl::InitializeASTContextForHLSL(ASTContext& context)
  8315. {
  8316. HLSLExternalSource* hlslSource = new HLSLExternalSource();
  8317. IntrusiveRefCntPtr<ExternalASTSource> externalSource(hlslSource);
  8318. if (hlslSource->Initialize(context)) {
  8319. context.setExternalSource(externalSource);
  8320. }
  8321. }
  8322. ////////////////////////////////////////////////////////////////////////////////
  8323. // FlattenedTypeIterator implementation //
  8324. /// <summary>Constructs a FlattenedTypeIterator for the specified type.</summary>
  8325. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, QualType type, HLSLExternalSource& source) :
  8326. m_source(source), m_draining(false), m_springLoaded(false), m_incompleteCount(0), m_typeDepth(0), m_loc(loc)
  8327. {
  8328. if (pushTrackerForType(type, nullptr)) {
  8329. considerLeaf();
  8330. }
  8331. }
  8332. /// <summary>Constructs a FlattenedTypeIterator for the specified expressions.</summary>
  8333. FlattenedTypeIterator::FlattenedTypeIterator(SourceLocation loc, MultiExprArg args, HLSLExternalSource& source) :
  8334. m_source(source), m_draining(false), m_springLoaded(false), m_incompleteCount(0), m_typeDepth(0), m_loc(loc)
  8335. {
  8336. if (!args.empty()) {
  8337. MultiExprArg::iterator ii = args.begin();
  8338. MultiExprArg::iterator ie = args.end();
  8339. DXASSERT(ii != ie, "otherwise empty() returned an incorrect value");
  8340. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  8341. if (!considerLeaf()) {
  8342. m_typeTrackers.clear();
  8343. }
  8344. }
  8345. }
  8346. /// <summary>Gets the current element in the flattened type hierarchy.</summary>
  8347. QualType FlattenedTypeIterator::getCurrentElement() const
  8348. {
  8349. return m_typeTrackers.back().Type;
  8350. }
  8351. /// <summary>Get the number of repeated current elements.</summary>
  8352. unsigned int FlattenedTypeIterator::getCurrentElementSize() const
  8353. {
  8354. const FlattenedTypeTracker& back = m_typeTrackers.back();
  8355. return (back.IterKind == FK_IncompleteArray) ? 1 : back.Count;
  8356. }
  8357. /// <summary>Checks whether the iterator has a current element type to report.</summary>
  8358. bool FlattenedTypeIterator::hasCurrentElement() const
  8359. {
  8360. return m_typeTrackers.size() > 0;
  8361. }
  8362. /// <summary>Consumes count elements on this iterator.</summary>
  8363. void FlattenedTypeIterator::advanceCurrentElement(unsigned int count)
  8364. {
  8365. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  8366. DXASSERT(m_typeTrackers.back().IterKind == FK_IncompleteArray || count <= m_typeTrackers.back().Count, "caller should never exceed currently pending element count");
  8367. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  8368. if (tracker.IterKind == FK_IncompleteArray)
  8369. {
  8370. tracker.Count += count;
  8371. m_springLoaded = true;
  8372. }
  8373. else
  8374. {
  8375. tracker.Count -= count;
  8376. m_springLoaded = false;
  8377. if (m_typeTrackers.back().Count == 0)
  8378. {
  8379. advanceLeafTracker();
  8380. }
  8381. }
  8382. }
  8383. unsigned int FlattenedTypeIterator::countRemaining()
  8384. {
  8385. m_draining = true; // when draining the iterator, incomplete arrays stop functioning as an infinite array
  8386. size_t result = 0;
  8387. while (hasCurrentElement() && !m_springLoaded)
  8388. {
  8389. size_t pending = getCurrentElementSize();
  8390. result += pending;
  8391. advanceCurrentElement(pending);
  8392. }
  8393. return result;
  8394. }
  8395. void FlattenedTypeIterator::advanceLeafTracker()
  8396. {
  8397. DXASSERT(!m_typeTrackers.empty(), "otherwise caller should not be trying to advance to another element");
  8398. for (;;)
  8399. {
  8400. consumeLeaf();
  8401. if (m_typeTrackers.empty()) {
  8402. return;
  8403. }
  8404. if (considerLeaf()) {
  8405. return;
  8406. }
  8407. }
  8408. }
  8409. bool FlattenedTypeIterator::considerLeaf()
  8410. {
  8411. if (m_typeTrackers.empty()) {
  8412. return false;
  8413. }
  8414. m_typeDepth++;
  8415. if (m_typeDepth > MaxTypeDepth) {
  8416. m_source.ReportUnsupportedTypeNesting(m_loc, m_firstType);
  8417. m_typeTrackers.clear();
  8418. m_typeDepth--;
  8419. return false;
  8420. }
  8421. bool result = false;
  8422. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  8423. tracker.IsConsidered = true;
  8424. switch (tracker.IterKind) {
  8425. case FlattenedIterKind::FK_Expressions:
  8426. if (pushTrackerForExpression(tracker.CurrentExpr)) {
  8427. result = considerLeaf();
  8428. }
  8429. break;
  8430. case FlattenedIterKind::FK_Fields:
  8431. if (pushTrackerForType(tracker.CurrentField->getType(), nullptr)) {
  8432. result = considerLeaf();
  8433. } else {
  8434. // Pop empty struct.
  8435. m_typeTrackers.pop_back();
  8436. }
  8437. break;
  8438. case FlattenedIterKind::FK_Bases:
  8439. if (pushTrackerForType(tracker.CurrentBase->getType(), nullptr)) {
  8440. result = considerLeaf();
  8441. } else {
  8442. // Pop empty base.
  8443. m_typeTrackers.pop_back();
  8444. }
  8445. break;
  8446. case FlattenedIterKind::FK_IncompleteArray:
  8447. m_springLoaded = true; // fall through.
  8448. default:
  8449. case FlattenedIterKind::FK_Simple: {
  8450. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(tracker.Type);
  8451. if (objectKind != ArTypeObjectKind::AR_TOBJ_BASIC &&
  8452. objectKind != ArTypeObjectKind::AR_TOBJ_OBJECT) {
  8453. if (pushTrackerForType(tracker.Type, tracker.CurrentExpr)) {
  8454. result = considerLeaf();
  8455. }
  8456. } else {
  8457. result = true;
  8458. }
  8459. }
  8460. }
  8461. m_typeDepth--;
  8462. return result;
  8463. }
  8464. void FlattenedTypeIterator::consumeLeaf()
  8465. {
  8466. bool topConsumed = true; // Tracks whether we're processing the topmost item which we should consume.
  8467. for (;;) {
  8468. if (m_typeTrackers.empty()) {
  8469. return;
  8470. }
  8471. FlattenedTypeTracker& tracker = m_typeTrackers.back();
  8472. // Reach a leaf which is not considered before.
  8473. // Stop here.
  8474. if (!tracker.IsConsidered) {
  8475. break;
  8476. }
  8477. switch (tracker.IterKind) {
  8478. case FlattenedIterKind::FK_Expressions:
  8479. ++tracker.CurrentExpr;
  8480. if (tracker.CurrentExpr == tracker.EndExpr) {
  8481. m_typeTrackers.pop_back();
  8482. topConsumed = false;
  8483. } else {
  8484. return;
  8485. }
  8486. break;
  8487. case FlattenedIterKind::FK_Fields:
  8488. ++tracker.CurrentField;
  8489. if (tracker.CurrentField == tracker.EndField) {
  8490. m_typeTrackers.pop_back();
  8491. topConsumed = false;
  8492. } else {
  8493. return;
  8494. }
  8495. break;
  8496. case FlattenedIterKind::FK_Bases:
  8497. ++tracker.CurrentBase;
  8498. if (tracker.CurrentBase == tracker.EndBase) {
  8499. m_typeTrackers.pop_back();
  8500. topConsumed = false;
  8501. } else {
  8502. return;
  8503. }
  8504. break;
  8505. case FlattenedIterKind::FK_IncompleteArray:
  8506. if (m_draining) {
  8507. DXASSERT(m_typeTrackers.size() == 1, "m_typeTrackers.size() == 1, otherwise incomplete array isn't topmost");
  8508. m_incompleteCount = tracker.Count;
  8509. m_typeTrackers.pop_back();
  8510. }
  8511. return;
  8512. default:
  8513. case FlattenedIterKind::FK_Simple: {
  8514. m_springLoaded = false;
  8515. if (!topConsumed) {
  8516. DXASSERT(tracker.Count > 0, "tracker.Count > 0 - otherwise we shouldn't be on stack");
  8517. --tracker.Count;
  8518. }
  8519. else {
  8520. topConsumed = false;
  8521. }
  8522. if (tracker.Count == 0) {
  8523. m_typeTrackers.pop_back();
  8524. } else {
  8525. return;
  8526. }
  8527. }
  8528. }
  8529. }
  8530. }
  8531. bool FlattenedTypeIterator::pushTrackerForExpression(MultiExprArg::iterator expression)
  8532. {
  8533. Expr* e = *expression;
  8534. Stmt::StmtClass expressionClass = e->getStmtClass();
  8535. if (expressionClass == Stmt::StmtClass::InitListExprClass) {
  8536. InitListExpr* initExpr = dyn_cast<InitListExpr>(e);
  8537. if (initExpr->getNumInits() == 0) {
  8538. return false;
  8539. }
  8540. MultiExprArg inits(initExpr->getInits(), initExpr->getNumInits());
  8541. MultiExprArg::iterator ii = inits.begin();
  8542. MultiExprArg::iterator ie = inits.end();
  8543. DXASSERT(ii != ie, "otherwise getNumInits() returned an incorrect value");
  8544. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(ii, ie));
  8545. return true;
  8546. }
  8547. return pushTrackerForType(e->getType(), expression);
  8548. }
  8549. // TODO: improve this to provide a 'peek' at intermediate types,
  8550. // which should help compare struct foo[1000] to avoid 1000 steps + per-field steps
  8551. bool FlattenedTypeIterator::pushTrackerForType(QualType type, MultiExprArg::iterator expression)
  8552. {
  8553. if (type->isVoidType()) {
  8554. return false;
  8555. }
  8556. if (type->isFunctionType()) {
  8557. return false;
  8558. }
  8559. if (m_firstType.isNull()) {
  8560. m_firstType = type;
  8561. }
  8562. ArTypeObjectKind objectKind = m_source.GetTypeObjectKind(type);
  8563. QualType elementType;
  8564. unsigned int elementCount;
  8565. const RecordType* recordType;
  8566. RecordDecl::field_iterator fi, fe;
  8567. switch (objectKind)
  8568. {
  8569. case ArTypeObjectKind::AR_TOBJ_ARRAY:
  8570. // TODO: handle multi-dimensional arrays
  8571. elementType = type->getAsArrayTypeUnsafe()->getElementType(); // handle arrays of arrays
  8572. elementCount = GetArraySize(type);
  8573. if (elementCount == 0) {
  8574. if (type->isIncompleteArrayType()) {
  8575. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(elementType));
  8576. return true;
  8577. }
  8578. return false;
  8579. }
  8580. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  8581. elementType, elementCount, nullptr));
  8582. return true;
  8583. case ArTypeObjectKind::AR_TOBJ_BASIC:
  8584. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(type, 1, expression));
  8585. return true;
  8586. case ArTypeObjectKind::AR_TOBJ_COMPOUND: {
  8587. recordType = type->getAsStructureType();
  8588. if (recordType == nullptr)
  8589. recordType = dyn_cast<RecordType>(type.getTypePtr());
  8590. fi = recordType->getDecl()->field_begin();
  8591. fe = recordType->getDecl()->field_end();
  8592. bool bAddTracker = false;
  8593. // Skip empty struct.
  8594. if (fi != fe) {
  8595. m_typeTrackers.push_back(
  8596. FlattenedTypeIterator::FlattenedTypeTracker(type, fi, fe));
  8597. type = (*fi)->getType();
  8598. bAddTracker = true;
  8599. }
  8600. if (CXXRecordDecl *cxxRecordDecl =
  8601. dyn_cast<CXXRecordDecl>(recordType->getDecl())) {
  8602. CXXRecordDecl::base_class_iterator bi, be;
  8603. bi = cxxRecordDecl->bases_begin();
  8604. be = cxxRecordDecl->bases_end();
  8605. if (bi != be) {
  8606. // Add type tracker for base.
  8607. // Add base after child to make sure base considered first.
  8608. m_typeTrackers.push_back(
  8609. FlattenedTypeIterator::FlattenedTypeTracker(type, bi, be));
  8610. bAddTracker = true;
  8611. }
  8612. }
  8613. return bAddTracker;
  8614. }
  8615. case ArTypeObjectKind::AR_TOBJ_MATRIX:
  8616. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  8617. m_source.GetMatrixOrVectorElementType(type),
  8618. GetElementCount(type), nullptr));
  8619. return true;
  8620. case ArTypeObjectKind::AR_TOBJ_VECTOR:
  8621. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(
  8622. m_source.GetMatrixOrVectorElementType(type),
  8623. GetHLSLVecSize(type), nullptr));
  8624. return true;
  8625. case ArTypeObjectKind::AR_TOBJ_OBJECT:
  8626. // Object have no sub-types.
  8627. m_typeTrackers.push_back(FlattenedTypeIterator::FlattenedTypeTracker(type.getCanonicalType(), 1, expression));
  8628. return true;
  8629. default:
  8630. DXASSERT(false, "unreachable");
  8631. return false;
  8632. }
  8633. }
  8634. FlattenedTypeIterator::ComparisonResult
  8635. FlattenedTypeIterator::CompareIterators(
  8636. HLSLExternalSource& source,
  8637. SourceLocation loc,
  8638. FlattenedTypeIterator& leftIter,
  8639. FlattenedTypeIterator& rightIter)
  8640. {
  8641. FlattenedTypeIterator::ComparisonResult result;
  8642. result.LeftCount = 0;
  8643. result.RightCount = 0;
  8644. result.AreElementsEqual = true; // Until proven otherwise.
  8645. result.CanConvertElements = true; // Until proven otherwise.
  8646. while (leftIter.hasCurrentElement() && rightIter.hasCurrentElement())
  8647. {
  8648. Expr* actualExpr = rightIter.getExprOrNull();
  8649. bool hasExpr = actualExpr != nullptr;
  8650. StmtExpr scratchExpr(nullptr, rightIter.getCurrentElement(), NoLoc, NoLoc);
  8651. StandardConversionSequence standard;
  8652. ExprResult convertedExpr;
  8653. if (!source.CanConvert(loc,
  8654. hasExpr ? actualExpr : &scratchExpr,
  8655. leftIter.getCurrentElement(),
  8656. ExplicitConversionFalse,
  8657. nullptr,
  8658. &standard)) {
  8659. result.AreElementsEqual = false;
  8660. result.CanConvertElements = false;
  8661. break;
  8662. }
  8663. else if (hasExpr && (standard.First != ICK_Identity || !standard.isIdentityConversion()))
  8664. {
  8665. convertedExpr = source.getSema()->PerformImplicitConversion(actualExpr,
  8666. leftIter.getCurrentElement(),
  8667. standard,
  8668. Sema::AA_Casting,
  8669. Sema::CCK_ImplicitConversion);
  8670. }
  8671. if (rightIter.getCurrentElement()->getCanonicalTypeUnqualified() !=
  8672. leftIter.getCurrentElement()->getCanonicalTypeUnqualified())
  8673. {
  8674. result.AreElementsEqual = false;
  8675. }
  8676. unsigned int advance = std::min(leftIter.getCurrentElementSize(), rightIter.getCurrentElementSize());
  8677. DXASSERT(advance > 0, "otherwise one iterator should report empty");
  8678. // If we need to apply conversions to the expressions, then advance a single element.
  8679. if (hasExpr && convertedExpr.isUsable()) {
  8680. rightIter.replaceExpr(convertedExpr.get());
  8681. advance = 1;
  8682. }
  8683. leftIter.advanceCurrentElement(advance);
  8684. rightIter.advanceCurrentElement(advance);
  8685. result.LeftCount += advance;
  8686. result.RightCount += advance;
  8687. }
  8688. result.LeftCount += leftIter.countRemaining();
  8689. result.RightCount += rightIter.countRemaining();
  8690. return result;
  8691. }
  8692. FlattenedTypeIterator::ComparisonResult
  8693. FlattenedTypeIterator::CompareTypes(
  8694. HLSLExternalSource& source,
  8695. SourceLocation leftLoc, SourceLocation rightLoc,
  8696. QualType left, QualType right)
  8697. {
  8698. FlattenedTypeIterator leftIter(leftLoc, left, source);
  8699. FlattenedTypeIterator rightIter(rightLoc, right, source);
  8700. return CompareIterators(source, leftLoc, leftIter, rightIter);
  8701. }
  8702. FlattenedTypeIterator::ComparisonResult
  8703. FlattenedTypeIterator::CompareTypesForInit(
  8704. HLSLExternalSource& source, QualType left, MultiExprArg args,
  8705. SourceLocation leftLoc, SourceLocation rightLoc)
  8706. {
  8707. FlattenedTypeIterator leftIter(leftLoc, left, source);
  8708. FlattenedTypeIterator rightIter(rightLoc, args, source);
  8709. return CompareIterators(source, leftLoc, leftIter, rightIter);
  8710. }
  8711. ////////////////////////////////////////////////////////////////////////////////
  8712. // Attribute processing support. //
  8713. static int ValidateAttributeIntArg(Sema& S, const AttributeList &Attr, unsigned index = 0)
  8714. {
  8715. int64_t value = 0;
  8716. if (Attr.getNumArgs() > index)
  8717. {
  8718. Expr *E = nullptr;
  8719. if (!Attr.isArgExpr(index)) {
  8720. // For case arg is constant variable.
  8721. IdentifierLoc *loc = Attr.getArgAsIdent(index);
  8722. VarDecl *decl = dyn_cast_or_null<VarDecl>(
  8723. S.LookupSingleName(S.getCurScope(), loc->Ident, loc->Loc,
  8724. Sema::LookupNameKind::LookupOrdinaryName));
  8725. if (!decl) {
  8726. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  8727. return value;
  8728. }
  8729. Expr *init = decl->getInit();
  8730. if (!init) {
  8731. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  8732. return value;
  8733. }
  8734. E = init;
  8735. } else
  8736. E = Attr.getArgAsExpr(index);
  8737. clang::APValue ArgNum;
  8738. bool displayError = false;
  8739. if (E->isTypeDependent() || E->isValueDependent() || !E->isCXX11ConstantExpr(S.Context, &ArgNum))
  8740. {
  8741. displayError = true;
  8742. }
  8743. else
  8744. {
  8745. if (ArgNum.isInt())
  8746. {
  8747. value = ArgNum.getInt().getSExtValue();
  8748. }
  8749. else if (ArgNum.isFloat())
  8750. {
  8751. llvm::APSInt floatInt;
  8752. bool isPrecise;
  8753. if (ArgNum.getFloat().convertToInteger(floatInt, llvm::APFloat::rmTowardZero, &isPrecise) == llvm::APFloat::opStatus::opOK)
  8754. {
  8755. value = floatInt.getSExtValue();
  8756. }
  8757. else
  8758. {
  8759. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  8760. }
  8761. }
  8762. else
  8763. {
  8764. displayError = true;
  8765. }
  8766. if (value < 0)
  8767. {
  8768. S.Diag(Attr.getLoc(), diag::warn_hlsl_attribute_expects_uint_literal) << Attr.getName();
  8769. }
  8770. }
  8771. if (displayError)
  8772. {
  8773. S.Diag(Attr.getLoc(), diag::err_attribute_argument_type)
  8774. << Attr.getName() << AANT_ArgumentIntegerConstant
  8775. << E->getSourceRange();
  8776. }
  8777. }
  8778. return (int)value;
  8779. }
  8780. // TODO: support float arg directly.
  8781. static int ValidateAttributeFloatArg(Sema &S, const AttributeList &Attr,
  8782. unsigned index = 0) {
  8783. int value = 0;
  8784. if (Attr.getNumArgs() > index) {
  8785. Expr *E = Attr.getArgAsExpr(index);
  8786. if (FloatingLiteral *FL = dyn_cast<FloatingLiteral>(E)) {
  8787. llvm::APFloat flV = FL->getValue();
  8788. if (flV.getSizeInBits(flV.getSemantics()) == 64) {
  8789. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToDouble());
  8790. value = intV.getLimitedValue();
  8791. } else {
  8792. llvm::APInt intV = llvm::APInt::floatToBits(flV.convertToFloat());
  8793. value = intV.getLimitedValue();
  8794. }
  8795. } else if (IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
  8796. llvm::APInt intV =
  8797. llvm::APInt::floatToBits((float)IL->getValue().getLimitedValue());
  8798. value = intV.getLimitedValue();
  8799. } else {
  8800. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_float_literal)
  8801. << Attr.getName();
  8802. }
  8803. }
  8804. return value;
  8805. }
  8806. static Stmt* IgnoreParensAndDecay(Stmt* S)
  8807. {
  8808. for (;;)
  8809. {
  8810. switch (S->getStmtClass())
  8811. {
  8812. case Stmt::ParenExprClass:
  8813. S = cast<ParenExpr>(S)->getSubExpr();
  8814. break;
  8815. case Stmt::ImplicitCastExprClass:
  8816. {
  8817. ImplicitCastExpr* castExpr = cast<ImplicitCastExpr>(S);
  8818. if (castExpr->getCastKind() != CK_ArrayToPointerDecay &&
  8819. castExpr->getCastKind() != CK_NoOp &&
  8820. castExpr->getCastKind() != CK_LValueToRValue)
  8821. {
  8822. return S;
  8823. }
  8824. S = castExpr->getSubExpr();
  8825. }
  8826. break;
  8827. default:
  8828. return S;
  8829. }
  8830. }
  8831. }
  8832. static Expr* ValidateClipPlaneArraySubscriptExpr(Sema& S, ArraySubscriptExpr* E)
  8833. {
  8834. DXASSERT_NOMSG(E != nullptr);
  8835. Expr* subscriptExpr = E->getIdx();
  8836. subscriptExpr = dyn_cast<Expr>(subscriptExpr->IgnoreParens());
  8837. if (subscriptExpr == nullptr ||
  8838. subscriptExpr->isTypeDependent() || subscriptExpr->isValueDependent() ||
  8839. !subscriptExpr->isCXX11ConstantExpr(S.Context))
  8840. {
  8841. S.Diag(
  8842. (subscriptExpr == nullptr) ? E->getLocStart() : subscriptExpr->getLocStart(),
  8843. diag::err_hlsl_unsupported_clipplane_argument_subscript_expression);
  8844. return nullptr;
  8845. }
  8846. return E->getBase();
  8847. }
  8848. static bool IsValidClipPlaneDecl(Decl* D)
  8849. {
  8850. Decl::Kind kind = D->getKind();
  8851. if (kind == Decl::Var)
  8852. {
  8853. VarDecl* varDecl = cast<VarDecl>(D);
  8854. if (varDecl->getStorageClass() == StorageClass::SC_Static &&
  8855. varDecl->getType().isConstQualified())
  8856. {
  8857. return false;
  8858. }
  8859. return true;
  8860. }
  8861. else if (kind == Decl::Field)
  8862. {
  8863. return true;
  8864. }
  8865. return false;
  8866. }
  8867. static Expr* ValidateClipPlaneExpr(Sema& S, Expr* E)
  8868. {
  8869. Stmt* cursor = E;
  8870. // clip plane expressions are a linear path, so no need to traverse the tree here.
  8871. while (cursor != nullptr)
  8872. {
  8873. bool supported = true;
  8874. cursor = IgnoreParensAndDecay(cursor);
  8875. switch (cursor->getStmtClass())
  8876. {
  8877. case Stmt::ArraySubscriptExprClass:
  8878. cursor = ValidateClipPlaneArraySubscriptExpr(S, cast<ArraySubscriptExpr>(cursor));
  8879. if (cursor == nullptr)
  8880. {
  8881. // nullptr indicates failure, and the error message has already been printed out
  8882. return nullptr;
  8883. }
  8884. break;
  8885. case Stmt::DeclRefExprClass:
  8886. {
  8887. DeclRefExpr* declRef = cast<DeclRefExpr>(cursor);
  8888. Decl* decl = declRef->getDecl();
  8889. supported = IsValidClipPlaneDecl(decl);
  8890. cursor = supported ? nullptr : cursor;
  8891. }
  8892. break;
  8893. case Stmt::MemberExprClass:
  8894. {
  8895. MemberExpr* member = cast<MemberExpr>(cursor);
  8896. supported = IsValidClipPlaneDecl(member->getMemberDecl());
  8897. cursor = supported ? member->getBase() : cursor;
  8898. }
  8899. break;
  8900. default:
  8901. supported = false;
  8902. break;
  8903. }
  8904. if (!supported)
  8905. {
  8906. DXASSERT(cursor != nullptr, "otherwise it was cleared when the supported flag was set to false");
  8907. S.Diag(cursor->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_expression);
  8908. return nullptr;
  8909. }
  8910. }
  8911. // Validate that the type is a float4.
  8912. QualType expressionType = E->getType();
  8913. HLSLExternalSource* hlslSource = HLSLExternalSource::FromSema(&S);
  8914. if (hlslSource->GetTypeElementKind(expressionType) != ArBasicKind::AR_BASIC_FLOAT32 ||
  8915. hlslSource->GetTypeObjectKind(expressionType) != ArTypeObjectKind::AR_TOBJ_VECTOR)
  8916. {
  8917. S.Diag(E->getLocStart(), diag::err_hlsl_unsupported_clipplane_argument_type) << expressionType;
  8918. return nullptr;
  8919. }
  8920. return E;
  8921. }
  8922. static Attr* HandleClipPlanes(Sema& S, const AttributeList &A)
  8923. {
  8924. Expr* clipExprs[6];
  8925. for (unsigned int index = 0; index < _countof(clipExprs); index++)
  8926. {
  8927. if (A.getNumArgs() <= index)
  8928. {
  8929. clipExprs[index] = nullptr;
  8930. continue;
  8931. }
  8932. Expr *E = A.getArgAsExpr(index);
  8933. clipExprs[index] = ValidateClipPlaneExpr(S, E);
  8934. }
  8935. return ::new (S.Context) HLSLClipPlanesAttr(A.getRange(), S.Context,
  8936. clipExprs[0], clipExprs[1], clipExprs[2], clipExprs[3], clipExprs[4], clipExprs[5],
  8937. A.getAttributeSpellingListIndex());
  8938. }
  8939. static Attr* HandleUnrollAttribute(Sema& S, const AttributeList &Attr)
  8940. {
  8941. int argValue = ValidateAttributeIntArg(S, Attr);
  8942. // Default value is 1.
  8943. if (Attr.getNumArgs() == 0) argValue = 1;
  8944. return ::new (S.Context) HLSLUnrollAttr(Attr.getRange(), S.Context,
  8945. argValue, Attr.getAttributeSpellingListIndex());
  8946. }
  8947. static void ValidateAttributeOnLoop(Sema& S, Stmt* St, const AttributeList &Attr)
  8948. {
  8949. Stmt::StmtClass stClass = St->getStmtClass();
  8950. if (stClass != Stmt::ForStmtClass && stClass != Stmt::WhileStmtClass && stClass != Stmt::DoStmtClass)
  8951. {
  8952. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  8953. << Attr.getName();
  8954. }
  8955. }
  8956. static void ValidateAttributeOnSwitch(Sema& S, Stmt* St, const AttributeList &Attr)
  8957. {
  8958. Stmt::StmtClass stClass = St->getStmtClass();
  8959. if (stClass != Stmt::SwitchStmtClass)
  8960. {
  8961. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  8962. << Attr.getName();
  8963. }
  8964. }
  8965. static void ValidateAttributeOnSwitchOrIf(Sema& S, Stmt* St, const AttributeList &Attr)
  8966. {
  8967. Stmt::StmtClass stClass = St->getStmtClass();
  8968. if (stClass != Stmt::SwitchStmtClass && stClass != Stmt::IfStmtClass)
  8969. {
  8970. S.Diag(Attr.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  8971. << Attr.getName();
  8972. }
  8973. }
  8974. static StringRef ValidateAttributeStringArg(Sema& S, const AttributeList &A, _In_opt_z_ const char* values, unsigned index = 0)
  8975. {
  8976. // values is an optional comma-separated list of potential values.
  8977. if (A.getNumArgs() <= index)
  8978. return StringRef();
  8979. Expr* E = A.getArgAsExpr(index);
  8980. if (E->isTypeDependent() || E->isValueDependent() || E->getStmtClass() != Stmt::StringLiteralClass)
  8981. {
  8982. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal)
  8983. << A.getName();
  8984. return StringRef();
  8985. }
  8986. StringLiteral* sl = cast<StringLiteral>(E);
  8987. StringRef result = sl->getString();
  8988. // Return result with no additional validation.
  8989. if (values == nullptr)
  8990. {
  8991. return result;
  8992. }
  8993. const char* value = values;
  8994. while (*value != '\0')
  8995. {
  8996. DXASSERT_NOMSG(*value != ','); // no leading commas in values
  8997. // Look for a match.
  8998. const char* argData = result.data();
  8999. size_t argDataLen = result.size();
  9000. while (argDataLen != 0 && *argData == *value && *value)
  9001. {
  9002. ++argData;
  9003. ++value;
  9004. --argDataLen;
  9005. }
  9006. // Match found if every input character matched.
  9007. if (argDataLen == 0 && (*value == '\0' || *value == ','))
  9008. {
  9009. return result;
  9010. }
  9011. // Move to next separator.
  9012. while (*value != '\0' && *value != ',')
  9013. {
  9014. ++value;
  9015. }
  9016. // Move to the start of the next item if any.
  9017. if (*value == ',') value++;
  9018. }
  9019. DXASSERT_NOMSG(*value == '\0'); // no other terminating conditions
  9020. // No match found.
  9021. S.Diag(E->getLocStart(), diag::err_hlsl_attribute_expects_string_literal_from_list)
  9022. << A.getName() << values;
  9023. return StringRef();
  9024. }
  9025. static
  9026. bool ValidateAttributeTargetIsFunction(Sema& S, Decl* D, const AttributeList &A)
  9027. {
  9028. if (D->isFunctionOrFunctionTemplate())
  9029. {
  9030. return true;
  9031. }
  9032. S.Diag(A.getLoc(), diag::err_hlsl_attribute_valid_on_function_only);
  9033. return false;
  9034. }
  9035. void hlsl::HandleDeclAttributeForHLSL(Sema &S, Decl *D, const AttributeList &A, bool& Handled)
  9036. {
  9037. DXASSERT_NOMSG(D != nullptr);
  9038. DXASSERT_NOMSG(!A.isInvalid());
  9039. Attr* declAttr = nullptr;
  9040. Handled = true;
  9041. switch (A.getKind())
  9042. {
  9043. case AttributeList::AT_HLSLIn:
  9044. declAttr = ::new (S.Context) HLSLInAttr(A.getRange(), S.Context,
  9045. A.getAttributeSpellingListIndex());
  9046. break;
  9047. case AttributeList::AT_HLSLOut:
  9048. declAttr = ::new (S.Context) HLSLOutAttr(A.getRange(), S.Context,
  9049. A.getAttributeSpellingListIndex());
  9050. break;
  9051. case AttributeList::AT_HLSLInOut:
  9052. declAttr = ::new (S.Context) HLSLInOutAttr(A.getRange(), S.Context,
  9053. A.getAttributeSpellingListIndex());
  9054. break;
  9055. case AttributeList::AT_HLSLNoInterpolation:
  9056. declAttr = ::new (S.Context) HLSLNoInterpolationAttr(A.getRange(), S.Context,
  9057. A.getAttributeSpellingListIndex());
  9058. break;
  9059. case AttributeList::AT_HLSLLinear:
  9060. declAttr = ::new (S.Context) HLSLLinearAttr(A.getRange(), S.Context,
  9061. A.getAttributeSpellingListIndex());
  9062. break;
  9063. case AttributeList::AT_HLSLNoPerspective:
  9064. declAttr = ::new (S.Context) HLSLNoPerspectiveAttr(A.getRange(), S.Context,
  9065. A.getAttributeSpellingListIndex());
  9066. break;
  9067. case AttributeList::AT_HLSLSample:
  9068. declAttr = ::new (S.Context) HLSLSampleAttr(A.getRange(), S.Context,
  9069. A.getAttributeSpellingListIndex());
  9070. break;
  9071. case AttributeList::AT_HLSLCentroid:
  9072. declAttr = ::new (S.Context) HLSLCentroidAttr(A.getRange(), S.Context,
  9073. A.getAttributeSpellingListIndex());
  9074. break;
  9075. case AttributeList::AT_HLSLPrecise:
  9076. declAttr = ::new (S.Context) HLSLPreciseAttr(A.getRange(), S.Context,
  9077. A.getAttributeSpellingListIndex());
  9078. break;
  9079. case AttributeList::AT_HLSLShared:
  9080. declAttr = ::new (S.Context) HLSLSharedAttr(A.getRange(), S.Context,
  9081. A.getAttributeSpellingListIndex());
  9082. break;
  9083. case AttributeList::AT_HLSLGroupShared:
  9084. declAttr = ::new (S.Context) HLSLGroupSharedAttr(A.getRange(), S.Context,
  9085. A.getAttributeSpellingListIndex());
  9086. break;
  9087. case AttributeList::AT_HLSLUniform:
  9088. declAttr = ::new (S.Context) HLSLUniformAttr(A.getRange(), S.Context,
  9089. A.getAttributeSpellingListIndex());
  9090. break;
  9091. case AttributeList::AT_HLSLColumnMajor:
  9092. declAttr = ::new (S.Context) HLSLColumnMajorAttr(A.getRange(), S.Context,
  9093. A.getAttributeSpellingListIndex());
  9094. break;
  9095. case AttributeList::AT_HLSLRowMajor:
  9096. declAttr = ::new (S.Context) HLSLRowMajorAttr(A.getRange(), S.Context,
  9097. A.getAttributeSpellingListIndex());
  9098. break;
  9099. case AttributeList::AT_HLSLUnorm:
  9100. declAttr = ::new (S.Context) HLSLUnormAttr(A.getRange(), S.Context,
  9101. A.getAttributeSpellingListIndex());
  9102. break;
  9103. case AttributeList::AT_HLSLSnorm:
  9104. declAttr = ::new (S.Context) HLSLSnormAttr(A.getRange(), S.Context,
  9105. A.getAttributeSpellingListIndex());
  9106. break;
  9107. case AttributeList::AT_HLSLPoint:
  9108. declAttr = ::new (S.Context) HLSLPointAttr(A.getRange(), S.Context,
  9109. A.getAttributeSpellingListIndex());
  9110. break;
  9111. case AttributeList::AT_HLSLLine:
  9112. declAttr = ::new (S.Context) HLSLLineAttr(A.getRange(), S.Context,
  9113. A.getAttributeSpellingListIndex());
  9114. break;
  9115. case AttributeList::AT_HLSLLineAdj:
  9116. declAttr = ::new (S.Context) HLSLLineAdjAttr(A.getRange(), S.Context,
  9117. A.getAttributeSpellingListIndex());
  9118. break;
  9119. case AttributeList::AT_HLSLTriangle:
  9120. declAttr = ::new (S.Context) HLSLTriangleAttr(A.getRange(), S.Context,
  9121. A.getAttributeSpellingListIndex());
  9122. break;
  9123. case AttributeList::AT_HLSLTriangleAdj:
  9124. declAttr = ::new (S.Context) HLSLTriangleAdjAttr(A.getRange(), S.Context,
  9125. A.getAttributeSpellingListIndex());
  9126. break;
  9127. case AttributeList::AT_HLSLGloballyCoherent:
  9128. declAttr = ::new (S.Context) HLSLGloballyCoherentAttr(
  9129. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9130. break;
  9131. default:
  9132. Handled = false;
  9133. break;
  9134. }
  9135. if (declAttr != nullptr)
  9136. {
  9137. DXASSERT_NOMSG(Handled);
  9138. D->addAttr(declAttr);
  9139. return;
  9140. }
  9141. Handled = true;
  9142. switch (A.getKind())
  9143. {
  9144. // These apply to statements, not declarations. The warning messages clarify this properly.
  9145. case AttributeList::AT_HLSLUnroll:
  9146. case AttributeList::AT_HLSLAllowUAVCondition:
  9147. case AttributeList::AT_HLSLLoop:
  9148. case AttributeList::AT_HLSLFastOpt:
  9149. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_loop_attribute)
  9150. << A.getName();
  9151. return;
  9152. case AttributeList::AT_HLSLBranch:
  9153. case AttributeList::AT_HLSLFlatten:
  9154. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_if_switch_attribute)
  9155. << A.getName();
  9156. return;
  9157. case AttributeList::AT_HLSLForceCase:
  9158. case AttributeList::AT_HLSLCall:
  9159. S.Diag(A.getLoc(), diag::warn_hlsl_unsupported_statement_for_switch_attribute)
  9160. << A.getName();
  9161. return;
  9162. // These are the cases that actually apply to declarations.
  9163. case AttributeList::AT_HLSLClipPlanes:
  9164. declAttr = HandleClipPlanes(S, A);
  9165. break;
  9166. case AttributeList::AT_HLSLDomain:
  9167. declAttr = ::new (S.Context) HLSLDomainAttr(A.getRange(), S.Context,
  9168. ValidateAttributeStringArg(S, A, "tri,quad,isoline"), A.getAttributeSpellingListIndex());
  9169. break;
  9170. case AttributeList::AT_HLSLEarlyDepthStencil:
  9171. declAttr = ::new (S.Context) HLSLEarlyDepthStencilAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9172. break;
  9173. case AttributeList::AT_HLSLInstance:
  9174. declAttr = ::new (S.Context) HLSLInstanceAttr(A.getRange(), S.Context,
  9175. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9176. break;
  9177. case AttributeList::AT_HLSLMaxTessFactor:
  9178. declAttr = ::new (S.Context) HLSLMaxTessFactorAttr(A.getRange(), S.Context,
  9179. ValidateAttributeFloatArg(S, A), A.getAttributeSpellingListIndex());
  9180. break;
  9181. case AttributeList::AT_HLSLNumThreads:
  9182. declAttr = ::new (S.Context) HLSLNumThreadsAttr(A.getRange(), S.Context,
  9183. ValidateAttributeIntArg(S, A), ValidateAttributeIntArg(S, A, 1), ValidateAttributeIntArg(S, A, 2),
  9184. A.getAttributeSpellingListIndex());
  9185. break;
  9186. case AttributeList::AT_HLSLRootSignature:
  9187. declAttr = ::new (S.Context) HLSLRootSignatureAttr(A.getRange(), S.Context,
  9188. ValidateAttributeStringArg(S, A, /*validate strings*/nullptr),
  9189. A.getAttributeSpellingListIndex());
  9190. break;
  9191. case AttributeList::AT_HLSLOutputControlPoints:
  9192. declAttr = ::new (S.Context) HLSLOutputControlPointsAttr(A.getRange(), S.Context,
  9193. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9194. break;
  9195. case AttributeList::AT_HLSLOutputTopology:
  9196. declAttr = ::new (S.Context) HLSLOutputTopologyAttr(A.getRange(), S.Context,
  9197. ValidateAttributeStringArg(S, A, "point,line,triangle,triangle_cw,triangle_ccw"), A.getAttributeSpellingListIndex());
  9198. break;
  9199. case AttributeList::AT_HLSLPartitioning:
  9200. declAttr = ::new (S.Context) HLSLPartitioningAttr(A.getRange(), S.Context,
  9201. ValidateAttributeStringArg(S, A, "integer,fractional_even,fractional_odd,pow2"), A.getAttributeSpellingListIndex());
  9202. break;
  9203. case AttributeList::AT_HLSLPatchConstantFunc:
  9204. declAttr = ::new (S.Context) HLSLPatchConstantFuncAttr(A.getRange(), S.Context,
  9205. ValidateAttributeStringArg(S, A, nullptr), A.getAttributeSpellingListIndex());
  9206. break;
  9207. case AttributeList::AT_HLSLShader:
  9208. declAttr = ::new (S.Context) HLSLShaderAttr(
  9209. A.getRange(), S.Context,
  9210. ValidateAttributeStringArg(S, A,
  9211. "compute,vertex,pixel,hull,domain,geometry"),
  9212. A.getAttributeSpellingListIndex());
  9213. break;
  9214. case AttributeList::AT_HLSLMaxVertexCount:
  9215. declAttr = ::new (S.Context) HLSLMaxVertexCountAttr(A.getRange(), S.Context,
  9216. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9217. break;
  9218. case AttributeList::AT_HLSLExperimental:
  9219. declAttr = ::new (S.Context) HLSLExperimentalAttr(A.getRange(), S.Context,
  9220. ValidateAttributeStringArg(S, A, nullptr, 0), ValidateAttributeStringArg(S, A, nullptr, 1),
  9221. A.getAttributeSpellingListIndex());
  9222. break;
  9223. case AttributeList::AT_NoInline:
  9224. declAttr = ::new (S.Context) NoInlineAttr(A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9225. break;
  9226. default:
  9227. Handled = false;
  9228. break; // SPIRV Change: was return;
  9229. }
  9230. if (declAttr != nullptr)
  9231. {
  9232. DXASSERT_NOMSG(Handled);
  9233. D->addAttr(declAttr);
  9234. // The attribute has been set but will have no effect. Validation will emit a diagnostic
  9235. // and prevent code generation.
  9236. ValidateAttributeTargetIsFunction(S, D, A);
  9237. return; // SPIRV Change
  9238. }
  9239. // SPIRV Change Starts
  9240. Handled = true;
  9241. switch (A.getKind())
  9242. {
  9243. case AttributeList::AT_VKBuiltIn:
  9244. declAttr = ::new (S.Context) VKBuiltInAttr(A.getRange(), S.Context,
  9245. ValidateAttributeStringArg(S, A, "PointSize,HelperInvocation"),
  9246. A.getAttributeSpellingListIndex());
  9247. break;
  9248. case AttributeList::AT_VKLocation:
  9249. declAttr = ::new (S.Context) VKLocationAttr(A.getRange(), S.Context,
  9250. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9251. break;
  9252. case AttributeList::AT_VKBinding:
  9253. declAttr = ::new (S.Context) VKBindingAttr(A.getRange(), S.Context,
  9254. ValidateAttributeIntArg(S, A), ValidateAttributeIntArg(S, A, 1),
  9255. A.getAttributeSpellingListIndex());
  9256. break;
  9257. case AttributeList::AT_VKCounterBinding:
  9258. declAttr = ::new (S.Context) VKCounterBindingAttr(A.getRange(), S.Context,
  9259. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9260. break;
  9261. case AttributeList::AT_VKPushConstant:
  9262. declAttr = ::new (S.Context) VKPushConstantAttr(A.getRange(), S.Context,
  9263. A.getAttributeSpellingListIndex());
  9264. break;
  9265. case AttributeList::AT_VKOffset:
  9266. declAttr = ::new (S.Context) VKOffsetAttr(A.getRange(), S.Context,
  9267. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9268. break;
  9269. case AttributeList::AT_VKInputAttachmentIndex:
  9270. declAttr = ::new (S.Context) VKInputAttachmentIndexAttr(
  9271. A.getRange(), S.Context, ValidateAttributeIntArg(S, A),
  9272. A.getAttributeSpellingListIndex());
  9273. break;
  9274. case AttributeList::AT_VKConstantId:
  9275. declAttr = ::new (S.Context) VKConstantIdAttr(A.getRange(), S.Context,
  9276. ValidateAttributeIntArg(S, A), A.getAttributeSpellingListIndex());
  9277. break;
  9278. default:
  9279. Handled = false;
  9280. return;
  9281. }
  9282. if (declAttr != nullptr)
  9283. {
  9284. DXASSERT_NOMSG(Handled);
  9285. D->addAttr(declAttr);
  9286. }
  9287. // SPIRV Change Ends
  9288. }
  9289. /// <summary>Processes an attribute for a statement.</summary>
  9290. /// <param name="S">Sema with context.</param>
  9291. /// <param name="St">Statement annotated.</param>
  9292. /// <param name="A">Single parsed attribute to process.</param>
  9293. /// <param name="Range">Range of all attribute lists (useful for FixIts to suggest inclusions).</param>
  9294. /// <param name="Handled">After execution, whether this was recognized and handled.</param>
  9295. /// <returns>An attribute instance if processed, nullptr if not recognized or an error was found.</returns>
  9296. Attr *hlsl::ProcessStmtAttributeForHLSL(Sema &S, Stmt *St, const AttributeList &A, SourceRange Range, bool& Handled)
  9297. {
  9298. // | Construct | Allowed Attributes |
  9299. // +------------------+--------------------------------------------+
  9300. // | for, while, do | loop, fastopt, unroll, allow_uav_condition |
  9301. // | if | branch, flatten |
  9302. // | switch | branch, flatten, forcecase, call |
  9303. Attr * result = nullptr;
  9304. Handled = true;
  9305. switch (A.getKind())
  9306. {
  9307. case AttributeList::AT_HLSLUnroll:
  9308. ValidateAttributeOnLoop(S, St, A);
  9309. result = HandleUnrollAttribute(S, A);
  9310. break;
  9311. case AttributeList::AT_HLSLAllowUAVCondition:
  9312. ValidateAttributeOnLoop(S, St, A);
  9313. result = ::new (S.Context) HLSLAllowUAVConditionAttr(
  9314. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9315. break;
  9316. case AttributeList::AT_HLSLLoop:
  9317. ValidateAttributeOnLoop(S, St, A);
  9318. result = ::new (S.Context) HLSLLoopAttr(
  9319. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9320. break;
  9321. case AttributeList::AT_HLSLFastOpt:
  9322. ValidateAttributeOnLoop(S, St, A);
  9323. result = ::new (S.Context) HLSLFastOptAttr(
  9324. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9325. break;
  9326. case AttributeList::AT_HLSLBranch:
  9327. ValidateAttributeOnSwitchOrIf(S, St, A);
  9328. result = ::new (S.Context) HLSLBranchAttr(
  9329. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9330. break;
  9331. case AttributeList::AT_HLSLFlatten:
  9332. ValidateAttributeOnSwitchOrIf(S, St, A);
  9333. result = ::new (S.Context) HLSLFlattenAttr(
  9334. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9335. break;
  9336. case AttributeList::AT_HLSLForceCase:
  9337. ValidateAttributeOnSwitch(S, St, A);
  9338. result = ::new (S.Context) HLSLForceCaseAttr(
  9339. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9340. break;
  9341. case AttributeList::AT_HLSLCall:
  9342. ValidateAttributeOnSwitch(S, St, A);
  9343. result = ::new (S.Context) HLSLCallAttr(
  9344. A.getRange(), S.Context, A.getAttributeSpellingListIndex());
  9345. break;
  9346. default:
  9347. Handled = false;
  9348. break;
  9349. }
  9350. return result;
  9351. }
  9352. ////////////////////////////////////////////////////////////////////////////////
  9353. // Implementation of Sema members. //
  9354. Decl* Sema::ActOnStartHLSLBuffer(
  9355. Scope* bufferScope,
  9356. bool cbuffer, SourceLocation KwLoc,
  9357. IdentifierInfo *Ident, SourceLocation IdentLoc,
  9358. std::vector<hlsl::UnusualAnnotation *>& BufferAttributes,
  9359. SourceLocation LBrace)
  9360. {
  9361. // For anonymous namespace, take the location of the left brace.
  9362. SourceLocation Loc = Ident ? IdentLoc : LBrace;
  9363. DeclContext* lexicalParent = getCurLexicalContext();
  9364. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  9365. Context, lexicalParent, cbuffer, /*isConstantBufferView*/ false, KwLoc,
  9366. Ident, IdentLoc, BufferAttributes, LBrace);
  9367. // Keep track of the currently active buffer.
  9368. HLSLBuffers.push_back(result);
  9369. // Validate unusual annotations and emit diagnostics.
  9370. DiagnoseUnusualAnnotationsForHLSL(*this, BufferAttributes);
  9371. auto && unusualIter = BufferAttributes.begin();
  9372. auto && unusualEnd = BufferAttributes.end();
  9373. char expectedRegisterType = cbuffer ? 'b' : 't';
  9374. for (; unusualIter != unusualEnd; ++unusualIter) {
  9375. switch ((*unusualIter)->getKind()) {
  9376. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  9377. hlsl::ConstantPacking* constantPacking = cast<hlsl::ConstantPacking>(*unusualIter);
  9378. Diag(constantPacking->Loc, diag::err_hlsl_unsupported_buffer_packoffset);
  9379. break;
  9380. }
  9381. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  9382. hlsl::RegisterAssignment* registerAssignment = cast<hlsl::RegisterAssignment>(*unusualIter);
  9383. if (registerAssignment->RegisterType != expectedRegisterType && registerAssignment->RegisterType != toupper(expectedRegisterType)) {
  9384. Diag(registerAssignment->Loc, cbuffer ? diag::err_hlsl_unsupported_cbuffer_register :
  9385. diag::err_hlsl_unsupported_tbuffer_register);
  9386. } else if (registerAssignment->ShaderProfile.size() > 0) {
  9387. Diag(registerAssignment->Loc, diag::err_hlsl_unsupported_buffer_slot_target_specific);
  9388. }
  9389. break;
  9390. }
  9391. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  9392. // Ignore semantic declarations.
  9393. break;
  9394. }
  9395. }
  9396. }
  9397. PushOnScopeChains(result, bufferScope);
  9398. PushDeclContext(bufferScope, result);
  9399. ActOnDocumentableDecl(result);
  9400. return result;
  9401. }
  9402. void Sema::ActOnFinishHLSLBuffer(Decl *Dcl, SourceLocation RBrace)
  9403. {
  9404. DXASSERT_NOMSG(Dcl != nullptr);
  9405. DXASSERT(Dcl == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  9406. dyn_cast<HLSLBufferDecl>(Dcl)->setRBraceLoc(RBrace);
  9407. HLSLBuffers.pop_back();
  9408. PopDeclContext();
  9409. }
  9410. Decl* Sema::getActiveHLSLBuffer() const
  9411. {
  9412. return HLSLBuffers.empty() ? nullptr : HLSLBuffers.back();
  9413. }
  9414. Decl *Sema::ActOnHLSLBufferView(Scope *bufferScope, SourceLocation KwLoc,
  9415. DeclGroupPtrTy &dcl, bool iscbuf) {
  9416. DXASSERT(nullptr == HLSLBuffers.back(), "otherwise push/pop is incorrect");
  9417. HLSLBuffers.pop_back();
  9418. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  9419. Decl *decl = dcl.get().getSingleDecl();
  9420. NamedDecl *namedDecl = cast<NamedDecl>(decl);
  9421. IdentifierInfo *Ident = namedDecl->getIdentifier();
  9422. // No anonymous namespace for ConstantBuffer, take the location of the decl.
  9423. SourceLocation Loc = decl->getLocation();
  9424. // Prevent array type in template. The only way to specify an array in the template type
  9425. // is to use a typedef, so we will strip non-typedef arrays off, since these are the legal
  9426. // array dimensions for the CBV/TBV, and if any array type remains, that is illegal.
  9427. QualType declType = cast<VarDecl>(namedDecl)->getType();
  9428. while (declType->isArrayType() && declType->getTypeClass() != Type::TypeClass::Typedef) {
  9429. const ArrayType *arrayType = declType->getAsArrayTypeUnsafe();
  9430. declType = arrayType->getElementType();
  9431. }
  9432. if (declType->isArrayType()) {
  9433. Diag(Loc, diag::err_hlsl_typeintemplateargument) << "array";
  9434. return nullptr;
  9435. }
  9436. std::vector<hlsl::UnusualAnnotation *> hlslAttrs;
  9437. DeclContext *lexicalParent = getCurLexicalContext();
  9438. clang::HLSLBufferDecl *result = HLSLBufferDecl::Create(
  9439. Context, lexicalParent, iscbuf, /*isConstantBufferView*/ true,
  9440. KwLoc, Ident, Loc, hlslAttrs, Loc);
  9441. // set relation
  9442. namedDecl->setDeclContext(result);
  9443. result->addDecl(namedDecl);
  9444. // move attribute from constant to constant buffer
  9445. result->setUnusualAnnotations(namedDecl->getUnusualAnnotations());
  9446. namedDecl->setUnusualAnnotations(hlslAttrs);
  9447. return result;
  9448. }
  9449. bool Sema::IsOnHLSLBufferView() {
  9450. // nullptr will not pushed for cbuffer.
  9451. return !HLSLBuffers.empty() && getActiveHLSLBuffer() == nullptr;
  9452. }
  9453. void Sema::ActOnStartHLSLBufferView() {
  9454. // Push nullptr to mark HLSLBufferView.
  9455. DXASSERT(HLSLBuffers.empty(), "otherwise push/pop is incorrect");
  9456. HLSLBuffers.emplace_back(nullptr);
  9457. }
  9458. HLSLBufferDecl::HLSLBufferDecl(
  9459. DeclContext *DC, bool cbuffer, bool cbufferView, SourceLocation KwLoc,
  9460. IdentifierInfo *Id, SourceLocation IdLoc,
  9461. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  9462. SourceLocation LBrace)
  9463. : NamedDecl(Decl::HLSLBuffer, DC, IdLoc, DeclarationName(Id)),
  9464. DeclContext(Decl::HLSLBuffer), LBraceLoc(LBrace), KwLoc(KwLoc),
  9465. IsCBuffer(cbuffer), IsConstantBufferView(cbufferView) {
  9466. if (!BufferAttributes.empty()) {
  9467. setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  9468. getASTContext(), BufferAttributes.data(), BufferAttributes.size()));
  9469. }
  9470. }
  9471. HLSLBufferDecl *
  9472. HLSLBufferDecl::Create(ASTContext &C, DeclContext *lexicalParent, bool cbuffer,
  9473. bool constantbuffer, SourceLocation KwLoc,
  9474. IdentifierInfo *Id, SourceLocation IdLoc,
  9475. std::vector<hlsl::UnusualAnnotation *> &BufferAttributes,
  9476. SourceLocation LBrace) {
  9477. DeclContext *DC = C.getTranslationUnitDecl();
  9478. HLSLBufferDecl *result = ::new (C) HLSLBufferDecl(
  9479. DC, cbuffer, constantbuffer, KwLoc, Id, IdLoc, BufferAttributes, LBrace);
  9480. if (DC != lexicalParent) {
  9481. result->setLexicalDeclContext(lexicalParent);
  9482. }
  9483. return result;
  9484. }
  9485. const char *HLSLBufferDecl::getDeclKindName() const {
  9486. static const char *HLSLBufferNames[] = {"tbuffer", "cbuffer", "TextureBuffer",
  9487. "ConstantBuffer"};
  9488. unsigned index = (unsigned ) isCBuffer() | (isConstantBufferView()) << 1;
  9489. return HLSLBufferNames[index];
  9490. }
  9491. void Sema::TransferUnusualAttributes(Declarator &D, NamedDecl *NewDecl) {
  9492. assert(NewDecl != nullptr);
  9493. if (!getLangOpts().HLSL) {
  9494. return;
  9495. }
  9496. if (!D.UnusualAnnotations.empty()) {
  9497. NewDecl->setUnusualAnnotations(UnusualAnnotation::CopyToASTContextArray(
  9498. getASTContext(), D.UnusualAnnotations.data(),
  9499. D.UnusualAnnotations.size()));
  9500. D.UnusualAnnotations.clear();
  9501. }
  9502. }
  9503. /// Checks whether a usage attribute is compatible with those seen so far and
  9504. /// maintains history.
  9505. static bool IsUsageAttributeCompatible(AttributeList::Kind kind, bool &usageIn,
  9506. bool &usageOut) {
  9507. switch (kind) {
  9508. case AttributeList::AT_HLSLIn:
  9509. if (usageIn)
  9510. return false;
  9511. usageIn = true;
  9512. break;
  9513. case AttributeList::AT_HLSLOut:
  9514. if (usageOut)
  9515. return false;
  9516. usageOut = true;
  9517. break;
  9518. default:
  9519. assert(kind == AttributeList::AT_HLSLInOut);
  9520. if (usageOut || usageIn)
  9521. return false;
  9522. usageIn = usageOut = true;
  9523. break;
  9524. }
  9525. return true;
  9526. }
  9527. // Diagnose valid/invalid modifiers for HLSL.
  9528. bool Sema::DiagnoseHLSLDecl(Declarator &D, DeclContext *DC,
  9529. TypeSourceInfo *TInfo, bool isParameter) {
  9530. assert(getLangOpts().HLSL &&
  9531. "otherwise this is called without checking language first");
  9532. // NOTE: some tests may declare templates.
  9533. if (DC->isNamespace() || DC->isDependentContext()) return true;
  9534. DeclSpec::SCS storage = D.getDeclSpec().getStorageClassSpec();
  9535. assert(!DC->isClosure() && "otherwise parser accepted closure syntax instead of failing with a syntax error");
  9536. assert(!DC->isDependentContext() && "otherwise parser accepted a template instead of failing with a syntax error");
  9537. assert(!DC->isNamespace() && "otherwise parser accepted a namespace instead of failing a syntax error");
  9538. bool result = true;
  9539. bool isTypedef = storage == DeclSpec::SCS_typedef;
  9540. bool isFunction = D.isFunctionDeclarator() && !DC->isRecord();
  9541. bool isLocalVar = DC->isFunctionOrMethod() && !isFunction && !isTypedef;
  9542. bool isGlobal = !isParameter && !isTypedef && !isFunction && (DC->isTranslationUnit() || DC->getDeclKind() == Decl::HLSLBuffer);
  9543. bool isMethod = DC->isRecord() && D.isFunctionDeclarator() && !isTypedef;
  9544. bool isField = DC->isRecord() && !D.isFunctionDeclarator() && !isTypedef;
  9545. bool isConst = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_const;
  9546. bool isVolatile = D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ::TQ_volatile;
  9547. bool isStatic = storage == DeclSpec::SCS::SCS_static;
  9548. bool isExtern = storage == DeclSpec::SCS::SCS_extern;
  9549. bool hasSignSpec = D.getDeclSpec().getTypeSpecSign() != DeclSpec::TSS::TSS_unspecified;
  9550. // Function declarations are not allowed in parameter declaration
  9551. // TODO : Remove this check once we support function declarations/pointers in HLSL
  9552. if (isParameter && isFunction) {
  9553. Diag(D.getLocStart(), diag::err_hlsl_func_in_func_decl);
  9554. D.setInvalidType();
  9555. return false;
  9556. }
  9557. assert(
  9558. (1 == (isLocalVar ? 1 : 0) + (isGlobal ? 1 : 0) + (isField ? 1 : 0) +
  9559. (isTypedef ? 1 : 0) + (isFunction ? 1 : 0) + (isMethod ? 1 : 0) +
  9560. (isParameter ? 1 : 0))
  9561. && "exactly one type of declarator is being processed");
  9562. // qt/pType captures either the type being modified, or the return type in the
  9563. // case of a function (or method).
  9564. QualType qt = TInfo->getType();
  9565. const Type* pType = qt.getTypePtrOrNull();
  9566. // Early checks - these are not simple attribution errors, but constructs that
  9567. // are fundamentally unsupported,
  9568. // and so we avoid errors that might indicate they can be repaired.
  9569. if (DC->isRecord()) {
  9570. unsigned int nestedDiagId = 0;
  9571. if (isTypedef) {
  9572. nestedDiagId = diag::err_hlsl_unsupported_nested_typedef;
  9573. }
  9574. if (nestedDiagId) {
  9575. Diag(D.getLocStart(), nestedDiagId);
  9576. D.setInvalidType();
  9577. return false;
  9578. }
  9579. }
  9580. const char* declarationType =
  9581. (isLocalVar) ? "local variable" :
  9582. (isTypedef) ? "typedef" :
  9583. (isFunction) ? "function" :
  9584. (isMethod) ? "method" :
  9585. (isGlobal) ? "global variable" :
  9586. (isParameter) ? "parameter" :
  9587. (isField) ? "field" : "<unknown>";
  9588. if (pType && D.isFunctionDeclarator()) {
  9589. const FunctionProtoType *pFP = pType->getAs<FunctionProtoType>();
  9590. if (pFP) {
  9591. qt = pFP->getReturnType();
  9592. pType = qt.getTypePtrOrNull();
  9593. }
  9594. }
  9595. // Check for deprecated effect object type here, warn, and invalidate decl
  9596. bool bDeprecatedEffectObject = false;
  9597. bool bIsObject = false;
  9598. if (hlsl::IsObjectType(this, qt, &bDeprecatedEffectObject)) {
  9599. bIsObject = true;
  9600. if (bDeprecatedEffectObject) {
  9601. Diag(D.getLocStart(), diag::warn_hlsl_effect_object);
  9602. D.setInvalidType();
  9603. return false;
  9604. }
  9605. // Add methods if not ready.
  9606. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(this);
  9607. hlslSource->AddHLSLObjectMethodsIfNotReady(qt);
  9608. } else if (qt->isArrayType()) {
  9609. QualType eltQt(qt->getArrayElementTypeNoTypeQual(), 0);
  9610. while (eltQt->isArrayType())
  9611. eltQt = QualType(eltQt->getArrayElementTypeNoTypeQual(), 0);
  9612. if (hlsl::IsObjectType(this, eltQt, &bDeprecatedEffectObject)) {
  9613. // Add methods if not ready.
  9614. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(this);
  9615. hlslSource->AddHLSLObjectMethodsIfNotReady(eltQt);
  9616. }
  9617. }
  9618. if (isExtern) {
  9619. if (!(isFunction || isGlobal)) {
  9620. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'extern'"
  9621. << declarationType;
  9622. result = false;
  9623. }
  9624. }
  9625. if (isStatic) {
  9626. if (!(isLocalVar || isGlobal || isFunction || isMethod || isField)) {
  9627. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'static'"
  9628. << declarationType;
  9629. result = false;
  9630. }
  9631. }
  9632. if (isVolatile) {
  9633. if (!(isLocalVar || isTypedef)) {
  9634. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'volatile'"
  9635. << declarationType;
  9636. result = false;
  9637. }
  9638. }
  9639. if (isConst) {
  9640. if (isField && !isStatic) {
  9641. Diag(D.getLocStart(), diag::err_hlsl_varmodifierna) << "'const'"
  9642. << declarationType;
  9643. result = false;
  9644. }
  9645. }
  9646. HLSLExternalSource *hlslSource = HLSLExternalSource::FromSema(this);
  9647. ArBasicKind basicKind = hlslSource->GetTypeElementKind(qt);
  9648. if (hasSignSpec) {
  9649. ArTypeObjectKind objKind = hlslSource->GetTypeObjectKind(qt);
  9650. // vectors or matrices can only have unsigned integer types.
  9651. if (objKind == AR_TOBJ_MATRIX || objKind == AR_TOBJ_VECTOR || objKind == AR_TOBJ_BASIC || objKind == AR_TOBJ_ARRAY) {
  9652. if (!IS_BASIC_UNSIGNABLE(basicKind)) {
  9653. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec)
  9654. << g_ArBasicTypeNames[basicKind];
  9655. result = false;
  9656. }
  9657. }
  9658. else {
  9659. Diag(D.getLocStart(), diag::err_sema_invalid_sign_spec) << g_ArBasicTypeNames[basicKind];
  9660. result = false;
  9661. }
  9662. }
  9663. // Validate attributes
  9664. clang::AttributeList
  9665. *pPrecise = nullptr,
  9666. *pShared = nullptr,
  9667. *pGroupShared = nullptr,
  9668. *pUniform = nullptr,
  9669. *pUsage = nullptr,
  9670. *pNoInterpolation = nullptr,
  9671. *pLinear = nullptr,
  9672. *pNoPerspective = nullptr,
  9673. *pSample = nullptr,
  9674. *pCentroid = nullptr,
  9675. *pAnyLinear = nullptr, // first linear attribute found
  9676. *pTopology = nullptr;
  9677. bool usageIn = false;
  9678. bool usageOut = false;
  9679. for (clang::AttributeList *pAttr = D.getDeclSpec().getAttributes().getList();
  9680. pAttr != NULL; pAttr = pAttr->getNext()) {
  9681. if (pAttr->isInvalid() || pAttr->isUsedAsTypeAttr())
  9682. continue;
  9683. switch (pAttr->getKind()) {
  9684. case AttributeList::AT_HLSLPrecise: // precise is applicable everywhere.
  9685. pPrecise = pAttr;
  9686. break;
  9687. case AttributeList::AT_HLSLShared:
  9688. if (!isGlobal) {
  9689. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9690. << pAttr->getName() << declarationType << pAttr->getRange();
  9691. result = false;
  9692. }
  9693. if (isStatic) {
  9694. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  9695. << "'static'" << pAttr->getName() << declarationType
  9696. << pAttr->getRange();
  9697. result = false;
  9698. }
  9699. pShared = pAttr;
  9700. break;
  9701. case AttributeList::AT_HLSLGroupShared:
  9702. if (!isGlobal) {
  9703. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9704. << pAttr->getName() << declarationType << pAttr->getRange();
  9705. result = false;
  9706. }
  9707. if (isExtern) {
  9708. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  9709. << "'extern'" << pAttr->getName() << declarationType
  9710. << pAttr->getRange();
  9711. result = false;
  9712. }
  9713. pGroupShared = pAttr;
  9714. break;
  9715. case AttributeList::AT_HLSLGloballyCoherent:
  9716. if (!bIsObject) {
  9717. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9718. << pAttr->getName() << "non-UAV type";
  9719. result = false;
  9720. }
  9721. break;
  9722. case AttributeList::AT_HLSLUniform:
  9723. if (!(isGlobal || isParameter)) {
  9724. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9725. << pAttr->getName() << declarationType << pAttr->getRange();
  9726. result = false;
  9727. }
  9728. if (isStatic) {
  9729. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  9730. << "'static'" << pAttr->getName() << declarationType
  9731. << pAttr->getRange();
  9732. result = false;
  9733. }
  9734. pUniform = pAttr;
  9735. break;
  9736. case AttributeList::AT_HLSLIn:
  9737. case AttributeList::AT_HLSLOut:
  9738. case AttributeList::AT_HLSLInOut:
  9739. if (!isParameter) {
  9740. Diag(pAttr->getLoc(), diag::err_hlsl_usage_not_on_parameter)
  9741. << pAttr->getName() << pAttr->getRange();
  9742. result = false;
  9743. }
  9744. if (!IsUsageAttributeCompatible(pAttr->getKind(), usageIn, usageOut)) {
  9745. Diag(pAttr->getLoc(), diag::err_hlsl_duplicate_parameter_usages)
  9746. << pAttr->getName() << pAttr->getRange();
  9747. result = false;
  9748. }
  9749. pUsage = pAttr;
  9750. break;
  9751. case AttributeList::AT_HLSLNoInterpolation:
  9752. if (!(isParameter || isField || isFunction)) {
  9753. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9754. << pAttr->getName() << declarationType << pAttr->getRange();
  9755. result = false;
  9756. }
  9757. if (pNoInterpolation) {
  9758. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  9759. << pAttr->getName() << pAttr->getRange();
  9760. }
  9761. pNoInterpolation = pAttr;
  9762. break;
  9763. case AttributeList::AT_HLSLLinear:
  9764. case AttributeList::AT_HLSLNoPerspective:
  9765. case AttributeList::AT_HLSLSample:
  9766. case AttributeList::AT_HLSLCentroid:
  9767. if (!(isParameter || isField || isFunction)) {
  9768. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9769. << pAttr->getName() << declarationType << pAttr->getRange();
  9770. result = false;
  9771. }
  9772. if (nullptr == pAnyLinear)
  9773. pAnyLinear = pAttr;
  9774. switch (pAttr->getKind()) {
  9775. case AttributeList::AT_HLSLLinear:
  9776. if (pLinear) {
  9777. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  9778. << pAttr->getName() << pAttr->getRange();
  9779. }
  9780. pLinear = pAttr;
  9781. break;
  9782. case AttributeList::AT_HLSLNoPerspective:
  9783. if (pNoPerspective) {
  9784. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  9785. << pAttr->getName() << pAttr->getRange();
  9786. }
  9787. pNoPerspective = pAttr;
  9788. break;
  9789. case AttributeList::AT_HLSLSample:
  9790. if (pSample) {
  9791. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  9792. << pAttr->getName() << pAttr->getRange();
  9793. }
  9794. pSample = pAttr;
  9795. break;
  9796. case AttributeList::AT_HLSLCentroid:
  9797. if (pCentroid) {
  9798. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  9799. << pAttr->getName() << pAttr->getRange();
  9800. }
  9801. pCentroid = pAttr;
  9802. break;
  9803. }
  9804. break;
  9805. case AttributeList::AT_HLSLPoint:
  9806. case AttributeList::AT_HLSLLine:
  9807. case AttributeList::AT_HLSLLineAdj:
  9808. case AttributeList::AT_HLSLTriangle:
  9809. case AttributeList::AT_HLSLTriangleAdj:
  9810. if (!(isParameter)) {
  9811. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifierna)
  9812. << pAttr->getName() << declarationType << pAttr->getRange();
  9813. result = false;
  9814. }
  9815. if (pTopology) {
  9816. if (pTopology->getKind() == pAttr->getKind()) {
  9817. Diag(pAttr->getLoc(), diag::warn_hlsl_duplicate_specifier)
  9818. << pAttr->getName() << pAttr->getRange();
  9819. } else {
  9820. Diag(pAttr->getLoc(), diag::err_hlsl_varmodifiersna)
  9821. << pAttr->getName() << pTopology->getName()
  9822. << declarationType << pAttr->getRange();
  9823. result = false;
  9824. }
  9825. }
  9826. pTopology = pAttr;
  9827. break;
  9828. default:
  9829. break;
  9830. }
  9831. }
  9832. if (pNoInterpolation && pAnyLinear) {
  9833. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  9834. << pNoInterpolation->getName() << pAnyLinear->getName()
  9835. << declarationType << pNoInterpolation->getRange();
  9836. result = false;
  9837. }
  9838. if (pSample && pCentroid) {
  9839. Diag(pCentroid->getLoc(), diag::warn_hlsl_specifier_overridden)
  9840. << pCentroid->getName() << pSample->getName() << pCentroid->getRange();
  9841. }
  9842. clang::AttributeList *pNonUniformAttr = pAnyLinear ? pAnyLinear : (
  9843. pNoInterpolation ? pNoInterpolation : pTopology);
  9844. if (pUniform && pNonUniformAttr) {
  9845. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  9846. << pNonUniformAttr->getName()
  9847. << pUniform->getName() << declarationType << pUniform->getRange();
  9848. result = false;
  9849. }
  9850. if (pAnyLinear && pTopology) {
  9851. Diag(pAnyLinear->getLoc(), diag::err_hlsl_varmodifiersna)
  9852. << pTopology->getName()
  9853. << pAnyLinear->getName() << declarationType << pAnyLinear->getRange();
  9854. result = false;
  9855. }
  9856. if (pNoInterpolation && pTopology) {
  9857. Diag(pNoInterpolation->getLoc(), diag::err_hlsl_varmodifiersna)
  9858. << pTopology->getName()
  9859. << pNoInterpolation->getName() << declarationType << pNoInterpolation->getRange();
  9860. result = false;
  9861. }
  9862. if (pUniform && pUsage) {
  9863. if (pUsage->getKind() != AttributeList::Kind::AT_HLSLIn) {
  9864. Diag(pUniform->getLoc(), diag::err_hlsl_varmodifiersna)
  9865. << pUsage->getName() << pUniform->getName() << declarationType
  9866. << pUniform->getRange();
  9867. result = false;
  9868. }
  9869. }
  9870. // Validate that stream-ouput objects are marked as inout
  9871. if (isParameter && !(usageIn && usageOut) &&
  9872. (basicKind == ArBasicKind::AR_OBJECT_LINESTREAM ||
  9873. basicKind == ArBasicKind::AR_OBJECT_POINTSTREAM ||
  9874. basicKind == ArBasicKind::AR_OBJECT_TRIANGLESTREAM)) {
  9875. Diag(D.getLocStart(), diag::err_hlsl_missing_inout_attr);
  9876. result = false;
  9877. }
  9878. // SPIRV change starts
  9879. #ifdef ENABLE_SPIRV_CODEGEN
  9880. // Validate that Vulkan specific feature is only used when targeting SPIR-V
  9881. if (!getLangOpts().SPIRV) {
  9882. if (basicKind == ArBasicKind::AR_OBJECT_VK_SUBPASS_INPUT ||
  9883. basicKind == ArBasicKind::AR_OBJECT_VK_SUBPASS_INPUT_MS) {
  9884. Diag(D.getLocStart(), diag::err_hlsl_vulkan_specific_feature)
  9885. << g_ArBasicTypeNames[basicKind];
  9886. result = false;
  9887. }
  9888. }
  9889. #endif // ENABLE_SPIRV_CODEGEN
  9890. // SPIRV change ends
  9891. // Validate unusual annotations.
  9892. hlsl::DiagnoseUnusualAnnotationsForHLSL(*this, D.UnusualAnnotations);
  9893. auto && unusualIter = D.UnusualAnnotations.begin();
  9894. auto && unusualEnd = D.UnusualAnnotations.end();
  9895. for (; unusualIter != unusualEnd; ++unusualIter) {
  9896. switch ((*unusualIter)->getKind()) {
  9897. case hlsl::UnusualAnnotation::UA_ConstantPacking: {
  9898. hlsl::ConstantPacking *constantPacking =
  9899. cast<hlsl::ConstantPacking>(*unusualIter);
  9900. if (!isGlobal || HLSLBuffers.size() == 0) {
  9901. Diag(constantPacking->Loc, diag::err_hlsl_packoffset_requires_cbuffer);
  9902. continue;
  9903. }
  9904. if (constantPacking->ComponentOffset > 0) {
  9905. // Validate that this will fit.
  9906. if (!qt.isNull()) {
  9907. hlsl::DiagnosePackingOffset(this, constantPacking->Loc, qt,
  9908. constantPacking->ComponentOffset);
  9909. }
  9910. }
  9911. break;
  9912. }
  9913. case hlsl::UnusualAnnotation::UA_RegisterAssignment: {
  9914. hlsl::RegisterAssignment *registerAssignment =
  9915. cast<hlsl::RegisterAssignment>(*unusualIter);
  9916. if (registerAssignment->IsValid) {
  9917. if (!qt.isNull()) {
  9918. hlsl::DiagnoseRegisterType(this, registerAssignment->Loc, qt,
  9919. registerAssignment->RegisterType);
  9920. }
  9921. }
  9922. break;
  9923. }
  9924. case hlsl::UnusualAnnotation::UA_SemanticDecl: {
  9925. hlsl::SemanticDecl *semanticDecl = cast<hlsl::SemanticDecl>(*unusualIter);
  9926. if (isTypedef || isLocalVar) {
  9927. Diag(semanticDecl->Loc, diag::err_hlsl_varmodifierna)
  9928. << "semantic" << declarationType;
  9929. }
  9930. break;
  9931. }
  9932. }
  9933. }
  9934. if (!result) {
  9935. D.setInvalidType();
  9936. }
  9937. return result;
  9938. }
  9939. // Diagnose HLSL types on lookup
  9940. bool Sema::DiagnoseHLSLLookup(const LookupResult &R) {
  9941. const DeclarationNameInfo declName = R.getLookupNameInfo();
  9942. IdentifierInfo* idInfo = declName.getName().getAsIdentifierInfo();
  9943. if (idInfo) {
  9944. StringRef nameIdentifier = idInfo->getName();
  9945. HLSLScalarType parsedType;
  9946. int rowCount, colCount;
  9947. if (TryParseAny(nameIdentifier.data(), nameIdentifier.size(), &parsedType, &rowCount, &colCount, getLangOpts())) {
  9948. HLSLExternalSource *hlslExternalSource = HLSLExternalSource::FromSema(this);
  9949. hlslExternalSource->WarnMinPrecision(parsedType, R.getNameLoc());
  9950. return hlslExternalSource->DiagnoseHLSLScalarType(parsedType, R.getNameLoc());
  9951. }
  9952. }
  9953. return true;
  9954. }
  9955. static QualType getUnderlyingType(QualType Type)
  9956. {
  9957. while (const TypedefType *TD = dyn_cast<TypedefType>(Type))
  9958. {
  9959. if (const TypedefNameDecl* pDecl = TD->getDecl())
  9960. Type = pDecl->getUnderlyingType();
  9961. else
  9962. break;
  9963. }
  9964. return Type;
  9965. }
  9966. /// <summary>Return HLSL AttributedType objects if they exist on type.</summary>
  9967. /// <param name="self">Sema with context.</param>
  9968. /// <param name="type">QualType to inspect.</param>
  9969. /// <param name="ppMatrixOrientation">Set pointer to column_major/row_major AttributedType if supplied.</param>
  9970. /// <param name="ppNorm">Set pointer to snorm/unorm AttributedType if supplied.</param>
  9971. void hlsl::GetHLSLAttributedTypes(
  9972. _In_ clang::Sema* self,
  9973. clang::QualType type,
  9974. _Inout_opt_ const clang::AttributedType** ppMatrixOrientation,
  9975. _Inout_opt_ const clang::AttributedType** ppNorm)
  9976. {
  9977. if (ppMatrixOrientation)
  9978. *ppMatrixOrientation = nullptr;
  9979. if (ppNorm)
  9980. *ppNorm = nullptr;
  9981. // Note: we clear output pointers once set so we can stop searching
  9982. QualType Desugared = getUnderlyingType(type);
  9983. const AttributedType *AT = dyn_cast<AttributedType>(Desugared);
  9984. while (AT && (ppMatrixOrientation || ppNorm)) {
  9985. AttributedType::Kind Kind = AT->getAttrKind();
  9986. if (Kind == AttributedType::attr_hlsl_row_major ||
  9987. Kind == AttributedType::attr_hlsl_column_major)
  9988. {
  9989. if (ppMatrixOrientation)
  9990. {
  9991. *ppMatrixOrientation = AT;
  9992. ppMatrixOrientation = nullptr;
  9993. }
  9994. }
  9995. else if (Kind == AttributedType::attr_hlsl_unorm ||
  9996. Kind == AttributedType::attr_hlsl_snorm)
  9997. {
  9998. if (ppNorm)
  9999. {
  10000. *ppNorm = AT;
  10001. ppNorm = nullptr;
  10002. }
  10003. }
  10004. Desugared = getUnderlyingType(AT->getEquivalentType());
  10005. AT = dyn_cast<AttributedType>(Desugared);
  10006. }
  10007. // Unwrap component type on vector or matrix and check snorm/unorm
  10008. Desugared = getUnderlyingType(hlsl::GetOriginalElementType(self, Desugared));
  10009. AT = dyn_cast<AttributedType>(Desugared);
  10010. while (AT && ppNorm) {
  10011. AttributedType::Kind Kind = AT->getAttrKind();
  10012. if (Kind == AttributedType::attr_hlsl_unorm ||
  10013. Kind == AttributedType::attr_hlsl_snorm)
  10014. {
  10015. *ppNorm = AT;
  10016. ppNorm = nullptr;
  10017. }
  10018. Desugared = getUnderlyingType(AT->getEquivalentType());
  10019. AT = dyn_cast<AttributedType>(Desugared);
  10020. }
  10021. }
  10022. /// <summary>Returns true if QualType is an HLSL Matrix type.</summary>
  10023. /// <param name="self">Sema with context.</param>
  10024. /// <param name="type">QualType to check.</param>
  10025. bool hlsl::IsMatrixType(
  10026. _In_ clang::Sema* self,
  10027. _In_ clang::QualType type)
  10028. {
  10029. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_MATRIX;
  10030. }
  10031. /// <summary>Returns true if QualType is an HLSL Vector type.</summary>
  10032. /// <param name="self">Sema with context.</param>
  10033. /// <param name="type">QualType to check.</param>
  10034. bool hlsl::IsVectorType(
  10035. _In_ clang::Sema* self,
  10036. _In_ clang::QualType type)
  10037. {
  10038. return HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type) == AR_TOBJ_VECTOR;
  10039. }
  10040. /// <summary>Get element type for an HLSL Matrix or Vector, preserving AttributedType.</summary>
  10041. /// <param name="self">Sema with context.</param>
  10042. /// <param name="type">Matrix or Vector type.</param>
  10043. clang::QualType hlsl::GetOriginalMatrixOrVectorElementType(
  10044. _In_ clang::QualType type)
  10045. {
  10046. // TODO: Determine if this is really the best way to get the matrix/vector specialization
  10047. // without losing the AttributedType on the template parameter
  10048. if (const Type* pType = type.getTypePtrOrNull()) {
  10049. // A non-dependent template specialization type is always "sugar",
  10050. // typically for a RecordType. For example, a class template
  10051. // specialization type of @c vector<int> will refer to a tag type for
  10052. // the instantiation @c std::vector<int, std::allocator<int>>.
  10053. if (const TemplateSpecializationType* pTemplate = pType->getAs<TemplateSpecializationType>()) {
  10054. // If we have enough arguments, pull them from the template directly, rather than doing
  10055. // the extra lookups.
  10056. if (pTemplate->getNumArgs() > 0)
  10057. return pTemplate->getArg(0).getAsType();
  10058. QualType templateRecord = pTemplate->desugar();
  10059. const Type *pTemplateRecordType = templateRecord.getTypePtr();
  10060. if (pTemplateRecordType) {
  10061. const TagType *pTemplateTagType = pTemplateRecordType->getAs<TagType>();
  10062. if (pTemplateTagType) {
  10063. const ClassTemplateSpecializationDecl *specializationDecl =
  10064. dyn_cast_or_null<ClassTemplateSpecializationDecl>(
  10065. pTemplateTagType->getDecl());
  10066. if (specializationDecl) {
  10067. return specializationDecl->getTemplateArgs()[0].getAsType();
  10068. }
  10069. }
  10070. }
  10071. }
  10072. }
  10073. return QualType();
  10074. }
  10075. /// <summary>Get element type, preserving AttributedType, if vector or matrix, otherwise return the type unmodified.</summary>
  10076. /// <param name="self">Sema with context.</param>
  10077. /// <param name="type">Input type.</param>
  10078. clang::QualType hlsl::GetOriginalElementType(
  10079. _In_ clang::Sema* self,
  10080. _In_ clang::QualType type)
  10081. {
  10082. ArTypeObjectKind Kind = HLSLExternalSource::FromSema(self)->GetTypeObjectKind(type);
  10083. if (Kind == AR_TOBJ_MATRIX || Kind == AR_TOBJ_VECTOR) {
  10084. return GetOriginalMatrixOrVectorElementType(type);
  10085. }
  10086. return type;
  10087. }
  10088. void hlsl::CustomPrintHLSLAttr(const clang::Attr *A, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy, unsigned int Indentation) {
  10089. switch (A->getKind()) {
  10090. // Parameter modifiers
  10091. case clang::attr::HLSLIn:
  10092. Out << "in ";
  10093. break;
  10094. case clang::attr::HLSLInOut:
  10095. Out << "inout ";
  10096. break;
  10097. case clang::attr::HLSLOut:
  10098. Out << "out ";
  10099. break;
  10100. // Interpolation modifiers
  10101. case clang::attr::HLSLLinear:
  10102. Out << "linear ";
  10103. break;
  10104. case clang::attr::HLSLCentroid:
  10105. Out << "centroid ";
  10106. break;
  10107. case clang::attr::HLSLNoInterpolation:
  10108. Out << "nointerpolation ";
  10109. break;
  10110. case clang::attr::HLSLNoPerspective:
  10111. Out << "noperspective ";
  10112. break;
  10113. case clang::attr::HLSLSample:
  10114. Out << "sample ";
  10115. break;
  10116. // Function attributes
  10117. case clang::attr::HLSLClipPlanes:
  10118. {
  10119. Attr * noconst = const_cast<Attr*>(A);
  10120. HLSLClipPlanesAttr *ACast = static_cast<HLSLClipPlanesAttr*>(noconst);
  10121. if (!ACast->getClipPlane1())
  10122. break;
  10123. Indent(Indentation, Out);
  10124. Out << "[clipplanes(";
  10125. ACast->getClipPlane1()->printPretty(Out, 0, Policy);
  10126. PrintClipPlaneIfPresent(ACast->getClipPlane2(), Out, Policy);
  10127. PrintClipPlaneIfPresent(ACast->getClipPlane3(), Out, Policy);
  10128. PrintClipPlaneIfPresent(ACast->getClipPlane4(), Out, Policy);
  10129. PrintClipPlaneIfPresent(ACast->getClipPlane5(), Out, Policy);
  10130. PrintClipPlaneIfPresent(ACast->getClipPlane6(), Out, Policy);
  10131. Out << ")]\n";
  10132. break;
  10133. }
  10134. case clang::attr::HLSLDomain:
  10135. {
  10136. Attr * noconst = const_cast<Attr*>(A);
  10137. HLSLDomainAttr *ACast = static_cast<HLSLDomainAttr*>(noconst);
  10138. Indent(Indentation, Out);
  10139. Out << "[domain(\"" << ACast->getDomainType() << "\")]\n";
  10140. break;
  10141. }
  10142. case clang::attr::HLSLEarlyDepthStencil:
  10143. Indent(Indentation, Out);
  10144. Out << "[earlydepthstencil]\n";
  10145. break;
  10146. case clang::attr::HLSLInstance: //TODO - test
  10147. {
  10148. Attr * noconst = const_cast<Attr*>(A);
  10149. HLSLInstanceAttr *ACast = static_cast<HLSLInstanceAttr*>(noconst);
  10150. Indent(Indentation, Out);
  10151. Out << "[instance(" << ACast->getCount() << ")]\n";
  10152. break;
  10153. }
  10154. case clang::attr::HLSLMaxTessFactor: //TODO - test
  10155. {
  10156. Attr * noconst = const_cast<Attr*>(A);
  10157. HLSLMaxTessFactorAttr *ACast = static_cast<HLSLMaxTessFactorAttr*>(noconst);
  10158. Indent(Indentation, Out);
  10159. Out << "[maxtessfactor(" << ACast->getFactor() << ")]\n";
  10160. break;
  10161. }
  10162. case clang::attr::HLSLNumThreads: //TODO - test
  10163. {
  10164. Attr * noconst = const_cast<Attr*>(A);
  10165. HLSLNumThreadsAttr *ACast = static_cast<HLSLNumThreadsAttr*>(noconst);
  10166. Indent(Indentation, Out);
  10167. Out << "[numthreads(" << ACast->getX() << ", " << ACast->getY() << ", " << ACast->getZ() << ")]\n";
  10168. break;
  10169. }
  10170. case clang::attr::HLSLRootSignature:
  10171. {
  10172. Attr * noconst = const_cast<Attr*>(A);
  10173. HLSLRootSignatureAttr *ACast = static_cast<HLSLRootSignatureAttr*>(noconst);
  10174. Indent(Indentation, Out);
  10175. Out << "[RootSignature(" << ACast->getSignatureName() << ")]\n";
  10176. break;
  10177. }
  10178. case clang::attr::HLSLOutputControlPoints:
  10179. {
  10180. Attr * noconst = const_cast<Attr*>(A);
  10181. HLSLOutputControlPointsAttr *ACast = static_cast<HLSLOutputControlPointsAttr*>(noconst);
  10182. Indent(Indentation, Out);
  10183. Out << "[outputcontrolpoints(" << ACast->getCount() << ")]\n";
  10184. break;
  10185. }
  10186. case clang::attr::HLSLOutputTopology:
  10187. {
  10188. Attr * noconst = const_cast<Attr*>(A);
  10189. HLSLOutputTopologyAttr *ACast = static_cast<HLSLOutputTopologyAttr*>(noconst);
  10190. Indent(Indentation, Out);
  10191. Out << "[outputtopology(\"" << ACast->getTopology() << "\")]\n";
  10192. break;
  10193. }
  10194. case clang::attr::HLSLPartitioning:
  10195. {
  10196. Attr * noconst = const_cast<Attr*>(A);
  10197. HLSLPartitioningAttr *ACast = static_cast<HLSLPartitioningAttr*>(noconst);
  10198. Indent(Indentation, Out);
  10199. Out << "[partitioning(\"" << ACast->getScheme() << "\")]\n";
  10200. break;
  10201. }
  10202. case clang::attr::HLSLPatchConstantFunc:
  10203. {
  10204. Attr * noconst = const_cast<Attr*>(A);
  10205. HLSLPatchConstantFuncAttr *ACast = static_cast<HLSLPatchConstantFuncAttr*>(noconst);
  10206. Indent(Indentation, Out);
  10207. Out << "[patchconstantfunc(\"" << ACast->getFunctionName() << "\")]\n";
  10208. break;
  10209. }
  10210. case clang::attr::HLSLShader:
  10211. {
  10212. Attr * noconst = const_cast<Attr*>(A);
  10213. HLSLShaderAttr *ACast = static_cast<HLSLShaderAttr*>(noconst);
  10214. Indent(Indentation, Out);
  10215. Out << "[shader(\"" << ACast->getStage() << "\")]\n";
  10216. break;
  10217. }
  10218. case clang::attr::HLSLExperimental:
  10219. {
  10220. Attr * noconst = const_cast<Attr*>(A);
  10221. HLSLExperimentalAttr *ACast = static_cast<HLSLExperimentalAttr*>(noconst);
  10222. Indent(Indentation, Out);
  10223. Out << "[experimental(\"" << ACast->getName() << "\", \"" << ACast->getValue() << "\")]\n";
  10224. break;
  10225. }
  10226. case clang::attr::HLSLMaxVertexCount:
  10227. {
  10228. Attr * noconst = const_cast<Attr*>(A);
  10229. HLSLMaxVertexCountAttr *ACast = static_cast<HLSLMaxVertexCountAttr*>(noconst);
  10230. Indent(Indentation, Out);
  10231. Out << "[maxvertexcount(" << ACast->getCount() << ")]\n";
  10232. break;
  10233. }
  10234. case clang::attr::NoInline:
  10235. Indent(Indentation, Out);
  10236. Out << "[noinline]\n";
  10237. break;
  10238. // Statement attributes
  10239. case clang::attr::HLSLAllowUAVCondition:
  10240. Indent(Indentation, Out);
  10241. Out << "[allow_uav_condition]\n";
  10242. break;
  10243. case clang::attr::HLSLBranch:
  10244. Indent(Indentation, Out);
  10245. Out << "[branch]\n";
  10246. break;
  10247. case clang::attr::HLSLCall:
  10248. Indent(Indentation, Out);
  10249. Out << "[call]\n";
  10250. break;
  10251. case clang::attr::HLSLFastOpt:
  10252. Indent(Indentation, Out);
  10253. Out << "[fastopt]\n";
  10254. break;
  10255. case clang::attr::HLSLFlatten:
  10256. Indent(Indentation, Out);
  10257. Out << "[flatten]\n";
  10258. break;
  10259. case clang::attr::HLSLForceCase:
  10260. Indent(Indentation, Out);
  10261. Out << "[forcecase]\n";
  10262. break;
  10263. case clang::attr::HLSLLoop:
  10264. Indent(Indentation, Out);
  10265. Out << "[loop]\n";
  10266. break;
  10267. case clang::attr::HLSLUnroll:
  10268. {
  10269. Attr * noconst = const_cast<Attr*>(A);
  10270. HLSLUnrollAttr *ACast = static_cast<HLSLUnrollAttr*>(noconst);
  10271. Indent(Indentation, Out);
  10272. Out << "[unroll(" << ACast->getCount() << ")]\n";
  10273. break;
  10274. }
  10275. // Variable modifiers
  10276. case clang::attr::HLSLGroupShared:
  10277. Out << "groupshared ";
  10278. break;
  10279. case clang::attr::HLSLPrecise:
  10280. Out << "precise ";
  10281. break;
  10282. case clang::attr::HLSLSemantic: // TODO: Consider removing HLSLSemantic attribute
  10283. break;
  10284. case clang::attr::HLSLShared:
  10285. Out << "shared ";
  10286. break;
  10287. case clang::attr::HLSLUniform:
  10288. Out << "uniform ";
  10289. break;
  10290. // These four cases are printed in TypePrinter::printAttributedBefore
  10291. case clang::attr::HLSLColumnMajor:
  10292. case clang::attr::HLSLRowMajor:
  10293. case clang::attr::HLSLSnorm:
  10294. case clang::attr::HLSLUnorm:
  10295. break;
  10296. case clang::attr::HLSLPoint:
  10297. Out << "point ";
  10298. break;
  10299. case clang::attr::HLSLLine:
  10300. Out << "line ";
  10301. break;
  10302. case clang::attr::HLSLLineAdj:
  10303. Out << "lineadj ";
  10304. break;
  10305. case clang::attr::HLSLTriangle:
  10306. Out << "triangle ";
  10307. break;
  10308. case clang::attr::HLSLTriangleAdj:
  10309. Out << "triangleadj ";
  10310. break;
  10311. case clang::attr::HLSLGloballyCoherent:
  10312. Out << "globallycoherent ";
  10313. break;
  10314. default:
  10315. A->printPretty(Out, Policy);
  10316. break;
  10317. }
  10318. }
  10319. bool hlsl::IsHLSLAttr(clang::attr::Kind AttrKind) {
  10320. switch (AttrKind){
  10321. case clang::attr::HLSLAllowUAVCondition:
  10322. case clang::attr::HLSLBranch:
  10323. case clang::attr::HLSLCall:
  10324. case clang::attr::HLSLCentroid:
  10325. case clang::attr::HLSLClipPlanes:
  10326. case clang::attr::HLSLColumnMajor:
  10327. case clang::attr::HLSLDomain:
  10328. case clang::attr::HLSLEarlyDepthStencil:
  10329. case clang::attr::HLSLFastOpt:
  10330. case clang::attr::HLSLFlatten:
  10331. case clang::attr::HLSLForceCase:
  10332. case clang::attr::HLSLGroupShared:
  10333. case clang::attr::HLSLIn:
  10334. case clang::attr::HLSLInOut:
  10335. case clang::attr::HLSLInstance:
  10336. case clang::attr::HLSLLinear:
  10337. case clang::attr::HLSLLoop:
  10338. case clang::attr::HLSLMaxTessFactor:
  10339. case clang::attr::HLSLNoInterpolation:
  10340. case clang::attr::HLSLNoPerspective:
  10341. case clang::attr::HLSLNumThreads:
  10342. case clang::attr::HLSLRootSignature:
  10343. case clang::attr::HLSLOut:
  10344. case clang::attr::HLSLOutputControlPoints:
  10345. case clang::attr::HLSLOutputTopology:
  10346. case clang::attr::HLSLPartitioning:
  10347. case clang::attr::HLSLPatchConstantFunc:
  10348. case clang::attr::HLSLMaxVertexCount:
  10349. case clang::attr::HLSLPrecise:
  10350. case clang::attr::HLSLRowMajor:
  10351. case clang::attr::HLSLSample:
  10352. case clang::attr::HLSLSemantic:
  10353. case clang::attr::HLSLShared:
  10354. case clang::attr::HLSLSnorm:
  10355. case clang::attr::HLSLUniform:
  10356. case clang::attr::HLSLUnorm:
  10357. case clang::attr::HLSLUnroll:
  10358. case clang::attr::HLSLPoint:
  10359. case clang::attr::HLSLLine:
  10360. case clang::attr::HLSLLineAdj:
  10361. case clang::attr::HLSLTriangle:
  10362. case clang::attr::HLSLTriangleAdj:
  10363. case clang::attr::HLSLGloballyCoherent:
  10364. case clang::attr::NoInline:
  10365. return true;
  10366. }
  10367. return false;
  10368. }
  10369. void hlsl::PrintClipPlaneIfPresent(clang::Expr *ClipPlane, llvm::raw_ostream &Out, const clang::PrintingPolicy &Policy) {
  10370. if (ClipPlane) {
  10371. Out << ", ";
  10372. ClipPlane->printPretty(Out, 0, Policy);
  10373. }
  10374. }
  10375. bool hlsl::IsObjectType(
  10376. _In_ clang::Sema* self,
  10377. _In_ clang::QualType type,
  10378. _Inout_opt_ bool *isDeprecatedEffectObject)
  10379. {
  10380. HLSLExternalSource *pExternalSource = HLSLExternalSource::FromSema(self);
  10381. if (pExternalSource && pExternalSource->GetTypeObjectKind(type) == AR_TOBJ_OBJECT) {
  10382. if (isDeprecatedEffectObject)
  10383. *isDeprecatedEffectObject = pExternalSource->GetTypeElementKind(type) == AR_OBJECT_LEGACY_EFFECT;
  10384. return true;
  10385. }
  10386. if (isDeprecatedEffectObject)
  10387. *isDeprecatedEffectObject = false;
  10388. return false;
  10389. }
  10390. bool hlsl::CanConvert(
  10391. _In_ clang::Sema* self,
  10392. clang::SourceLocation loc,
  10393. _In_ clang::Expr* sourceExpr,
  10394. clang::QualType target,
  10395. bool explicitConversion,
  10396. _Inout_opt_ clang::StandardConversionSequence* standard)
  10397. {
  10398. return HLSLExternalSource::FromSema(self)->CanConvert(loc, sourceExpr, target, explicitConversion, nullptr, standard);
  10399. }
  10400. void hlsl::Indent(unsigned int Indentation, llvm::raw_ostream &Out)
  10401. {
  10402. for (unsigned i = 0; i != Indentation; ++i)
  10403. Out << " ";
  10404. }
  10405. void hlsl::RegisterIntrinsicTable(_In_ clang::ExternalSemaSource* self, _In_ IDxcIntrinsicTable* table)
  10406. {
  10407. DXASSERT_NOMSG(self != nullptr);
  10408. DXASSERT_NOMSG(table != nullptr);
  10409. HLSLExternalSource* source = (HLSLExternalSource*)self;
  10410. source->RegisterIntrinsicTable(table);
  10411. }
  10412. clang::QualType hlsl::CheckVectorConditional(
  10413. _In_ clang::Sema* self,
  10414. _In_ clang::ExprResult &Cond,
  10415. _In_ clang::ExprResult &LHS,
  10416. _In_ clang::ExprResult &RHS,
  10417. _In_ clang::SourceLocation QuestionLoc)
  10418. {
  10419. return HLSLExternalSource::FromSema(self)->CheckVectorConditional(Cond, LHS, RHS, QuestionLoc);
  10420. }
  10421. bool IsTypeNumeric(_In_ clang::Sema* self, _In_ clang::QualType &type) {
  10422. UINT count;
  10423. return HLSLExternalSource::FromSema(self)->IsTypeNumeric(type, &count);
  10424. }
  10425. void Sema::CheckHLSLArrayAccess(const Expr *expr) {
  10426. DXASSERT_NOMSG(isa<CXXOperatorCallExpr>(expr));
  10427. const CXXOperatorCallExpr *OperatorCallExpr = cast<CXXOperatorCallExpr>(expr);
  10428. DXASSERT_NOMSG(OperatorCallExpr->getOperator() == OverloadedOperatorKind::OO_Subscript);
  10429. const Expr *RHS = OperatorCallExpr->getArg(1); // first subscript expression
  10430. llvm::APSInt index;
  10431. if (RHS->EvaluateAsInt(index, Context)) {
  10432. int64_t intIndex = index.getLimitedValue();
  10433. const QualType LHSQualType = OperatorCallExpr->getArg(0)->getType();
  10434. if (IsVectorType(this, LHSQualType)) {
  10435. uint32_t vectorSize = GetHLSLVecSize(LHSQualType);
  10436. // If expression is a double two subscript operator for matrix (e.g x[0][1])
  10437. // we also have to check the first subscript oprator by recursively calling
  10438. // this funciton for the first CXXOperatorCallExpr
  10439. if (isa<CXXOperatorCallExpr>(OperatorCallExpr->getArg(0))) {
  10440. CheckHLSLArrayAccess(cast<CXXOperatorCallExpr>(OperatorCallExpr->getArg(0)));
  10441. }
  10442. if (intIndex < 0 || (uint32_t)intIndex >= vectorSize) {
  10443. Diag(RHS->getExprLoc(),
  10444. diag::err_hlsl_vector_element_index_out_of_bounds)
  10445. << (int)intIndex;
  10446. }
  10447. }
  10448. else if (IsMatrixType(this, LHSQualType)) {
  10449. uint32_t rowCount, colCount;
  10450. GetHLSLMatRowColCount(LHSQualType, rowCount, colCount);
  10451. if (intIndex < 0 || (uint32_t)intIndex >= rowCount) {
  10452. Diag(RHS->getExprLoc(), diag::err_hlsl_matrix_row_index_out_of_bounds)
  10453. << (int)intIndex;
  10454. }
  10455. }
  10456. }
  10457. }
  10458. clang::QualType ApplyTypeSpecSignToParsedType(
  10459. _In_ clang::Sema* self,
  10460. _In_ clang::QualType &type,
  10461. _In_ clang::TypeSpecifierSign TSS,
  10462. _In_ clang::SourceLocation Loc
  10463. )
  10464. {
  10465. return HLSLExternalSource::FromSema(self)->ApplyTypeSpecSignToParsedType(type, TSS, Loc);
  10466. }