SemaHLSL.cpp 399 KB

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