SemaHLSL.cpp 363 KB

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