DeclResultIdMapper.cpp 147 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822
  1. //===--- DeclResultIdMapper.cpp - DeclResultIdMapper impl --------*- C++ -*-==//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. #include "DeclResultIdMapper.h"
  10. #include <sstream>
  11. #include "dxc/DXIL/DxilConstants.h"
  12. #include "dxc/DXIL/DxilTypeSystem.h"
  13. #include "clang/AST/Expr.h"
  14. #include "clang/AST/HlslTypes.h"
  15. #include "clang/SPIRV/AstTypeProbe.h"
  16. #include "llvm/ADT/SmallBitVector.h"
  17. #include "llvm/ADT/StringMap.h"
  18. #include "llvm/ADT/StringSet.h"
  19. #include "llvm/Support/Casting.h"
  20. #include "AlignmentSizeCalculator.h"
  21. #include "SpirvEmitter.h"
  22. namespace clang {
  23. namespace spirv {
  24. namespace {
  25. uint32_t getVkBindingAttrSet(const VKBindingAttr *attr, uint32_t defaultSet) {
  26. // If the [[vk::binding(x)]] attribute is provided without the descriptor set,
  27. // we should use the default descriptor set.
  28. if (attr->getSet() == INT_MIN) {
  29. return defaultSet;
  30. }
  31. return attr->getSet();
  32. }
  33. /// Returns the :packoffset() annotation on the given decl. Returns nullptr if
  34. /// the decl does not have one.
  35. hlsl::ConstantPacking *getPackOffset(const clang::NamedDecl *decl) {
  36. for (auto *annotation : decl->getUnusualAnnotations())
  37. if (auto *packing = llvm::dyn_cast<hlsl::ConstantPacking>(annotation))
  38. return packing;
  39. return nullptr;
  40. }
  41. /// Returns the number of binding numbers that are used up by the given type.
  42. /// An array of size N consumes N*M binding numbers where M is the number of
  43. /// binding numbers used by each array element.
  44. /// The number of binding numbers used by a structure is the sum of binding
  45. /// numbers used by its members.
  46. uint32_t getNumBindingsUsedByResourceType(QualType type) {
  47. // For custom-generated types that have SpirvType but no QualType.
  48. if (type.isNull())
  49. return 1;
  50. // For every array dimension, the number of bindings needed should be
  51. // multiplied by the array size. For example: an array of two Textures should
  52. // use 2 binding slots.
  53. uint32_t arrayFactor = 1;
  54. while (auto constArrayType = dyn_cast<ConstantArrayType>(type)) {
  55. arrayFactor *=
  56. static_cast<uint32_t>(constArrayType->getSize().getZExtValue());
  57. type = constArrayType->getElementType();
  58. }
  59. // Once we remove the arrayness, we expect the given type to be either a
  60. // resource OR a structure that only contains resources.
  61. assert(isResourceType(type) || isResourceOnlyStructure(type));
  62. // In the case of a resource, each resource takes 1 binding slot, so in total
  63. // it consumes: 1 * arrayFactor.
  64. if (isResourceType(type))
  65. return arrayFactor;
  66. // In the case of a struct of resources, we need to sum up the number of
  67. // bindings for the struct members. So in total it consumes:
  68. // sum(bindings of struct members) * arrayFactor.
  69. if (isResourceOnlyStructure(type)) {
  70. uint32_t sumOfMemberBindings = 0;
  71. const auto *structDecl = type->getAs<RecordType>()->getDecl();
  72. assert(structDecl);
  73. for (const auto *field : structDecl->fields())
  74. sumOfMemberBindings += getNumBindingsUsedByResourceType(field->getType());
  75. return sumOfMemberBindings * arrayFactor;
  76. }
  77. llvm_unreachable(
  78. "getNumBindingsUsedByResourceType was called with unknown resource type");
  79. }
  80. QualType getUintTypeWithSourceComponents(const ASTContext &astContext,
  81. QualType sourceType) {
  82. if (isScalarType(sourceType)) {
  83. return astContext.UnsignedIntTy;
  84. }
  85. uint32_t elemCount = 0;
  86. if (isVectorType(sourceType, nullptr, &elemCount)) {
  87. return astContext.getExtVectorType(astContext.UnsignedIntTy, elemCount);
  88. }
  89. llvm_unreachable("only scalar and vector types are supported in "
  90. "getUintTypeWithSourceComponents");
  91. }
  92. uint32_t getLocationCount(const ASTContext &astContext, QualType type) {
  93. // See Vulkan spec 14.1.4. Location Assignment for the complete set of rules.
  94. const auto canonicalType = type.getCanonicalType();
  95. if (canonicalType != type)
  96. return getLocationCount(astContext, canonicalType);
  97. // Inputs and outputs of the following types consume a single interface
  98. // location:
  99. // * 16-bit scalar and vector types, and
  100. // * 32-bit scalar and vector types, and
  101. // * 64-bit scalar and 2-component vector types.
  102. // 64-bit three- and four- component vectors consume two consecutive
  103. // locations.
  104. // Primitive types
  105. if (isScalarType(type))
  106. return 1;
  107. // Vector types
  108. {
  109. QualType elemType = {};
  110. uint32_t elemCount = {};
  111. if (isVectorType(type, &elemType, &elemCount)) {
  112. const auto *builtinType = elemType->getAs<BuiltinType>();
  113. switch (builtinType->getKind()) {
  114. case BuiltinType::Double:
  115. case BuiltinType::LongLong:
  116. case BuiltinType::ULongLong:
  117. if (elemCount >= 3)
  118. return 2;
  119. default:
  120. // Filter switch only interested in types occupying 2 locations.
  121. break;
  122. }
  123. return 1;
  124. }
  125. }
  126. // If the declared input or output is an n * m 16- , 32- or 64- bit matrix,
  127. // it will be assigned multiple locations starting with the location
  128. // specified. The number of locations assigned for each matrix will be the
  129. // same as for an n-element array of m-component vectors.
  130. // Matrix types
  131. {
  132. QualType elemType = {};
  133. uint32_t rowCount = 0, colCount = 0;
  134. if (isMxNMatrix(type, &elemType, &rowCount, &colCount))
  135. return getLocationCount(astContext,
  136. astContext.getExtVectorType(elemType, colCount)) *
  137. rowCount;
  138. }
  139. // Typedefs
  140. if (const auto *typedefType = type->getAs<TypedefType>())
  141. return getLocationCount(astContext, typedefType->desugar());
  142. // Reference types
  143. if (const auto *refType = type->getAs<ReferenceType>())
  144. return getLocationCount(astContext, refType->getPointeeType());
  145. // Pointer types
  146. if (const auto *ptrType = type->getAs<PointerType>())
  147. return getLocationCount(astContext, ptrType->getPointeeType());
  148. // If a declared input or output is an array of size n and each element takes
  149. // m locations, it will be assigned m * n consecutive locations starting with
  150. // the location specified.
  151. // Array types
  152. if (const auto *arrayType = astContext.getAsConstantArrayType(type))
  153. return getLocationCount(astContext, arrayType->getElementType()) *
  154. static_cast<uint32_t>(arrayType->getSize().getZExtValue());
  155. // Struct type
  156. if (type->getAs<RecordType>()) {
  157. assert(false && "all structs should already be flattened");
  158. return 0;
  159. }
  160. llvm_unreachable(
  161. "calculating number of occupied locations for type unimplemented");
  162. return 0;
  163. }
  164. bool shouldSkipInStructLayout(const Decl *decl) {
  165. // Ignore implicit generated struct declarations/constructors/destructors
  166. if (decl->isImplicit())
  167. return true;
  168. // Ignore embedded type decls
  169. if (isa<TypeDecl>(decl))
  170. return true;
  171. // Ignore embeded function decls
  172. if (isa<FunctionDecl>(decl))
  173. return true;
  174. // Ignore empty decls
  175. if (isa<EmptyDecl>(decl))
  176. return true;
  177. // For the $Globals cbuffer, we only care about externally-visible
  178. // non-resource-type variables. The rest should be filtered out.
  179. const auto *declContext = decl->getDeclContext();
  180. // $Globals' "struct" is the TranslationUnit, so we should ignore resources
  181. // in the TranslationUnit "struct" and its child namespaces.
  182. if (declContext->isTranslationUnit() || declContext->isNamespace()) {
  183. // External visibility
  184. if (const auto *declDecl = dyn_cast<DeclaratorDecl>(decl))
  185. if (!declDecl->hasExternalFormalLinkage())
  186. return true;
  187. // cbuffer/tbuffer
  188. if (isa<HLSLBufferDecl>(decl))
  189. return true;
  190. // 'groupshared' variables should not be placed in $Globals cbuffer.
  191. if (decl->hasAttr<HLSLGroupSharedAttr>())
  192. return true;
  193. // Other resource types
  194. if (const auto *valueDecl = dyn_cast<ValueDecl>(decl)) {
  195. const auto declType = valueDecl->getType();
  196. if (isResourceType(declType) || isResourceOnlyStructure(declType))
  197. return true;
  198. }
  199. }
  200. return false;
  201. }
  202. void collectDeclsInField(const Decl *field,
  203. llvm::SmallVector<const Decl *, 4> *decls) {
  204. // Case of nested namespaces.
  205. if (const auto *nsDecl = dyn_cast<NamespaceDecl>(field)) {
  206. for (const auto *decl : nsDecl->decls()) {
  207. collectDeclsInField(decl, decls);
  208. }
  209. }
  210. if (shouldSkipInStructLayout(field))
  211. return;
  212. if (!isa<DeclaratorDecl>(field)) {
  213. return;
  214. }
  215. decls->push_back(field);
  216. }
  217. llvm::SmallVector<const Decl *, 4>
  218. collectDeclsInDeclContext(const DeclContext *declContext) {
  219. llvm::SmallVector<const Decl *, 4> decls;
  220. for (const auto *field : declContext->decls()) {
  221. collectDeclsInField(field, &decls);
  222. }
  223. return decls;
  224. }
  225. /// \brief Returns true if the given decl is a boolean stage I/O variable.
  226. /// Returns false if the type is not boolean, or the decl is a built-in stage
  227. /// variable.
  228. bool isBooleanStageIOVar(const NamedDecl *decl, QualType type,
  229. const hlsl::DXIL::SemanticKind semanticKind,
  230. const hlsl::SigPoint::Kind sigPointKind) {
  231. // [[vk::builtin(...)]] makes the decl a built-in stage variable.
  232. // IsFrontFace (if used as PSIn) is the only known boolean built-in stage
  233. // variable.
  234. const bool isBooleanBuiltin =
  235. (decl->getAttr<VKBuiltInAttr>() != nullptr) ||
  236. (semanticKind == hlsl::Semantic::Kind::IsFrontFace &&
  237. sigPointKind == hlsl::SigPoint::Kind::PSIn);
  238. // TODO: support boolean matrix stage I/O variable if needed.
  239. QualType elemType = {};
  240. const bool isBooleanType =
  241. ((isScalarType(type, &elemType) || isVectorType(type, &elemType)) &&
  242. elemType->isBooleanType());
  243. return isBooleanType && !isBooleanBuiltin;
  244. }
  245. /// \brief Returns the stage variable's register assignment for the given Decl.
  246. const hlsl::RegisterAssignment *getResourceBinding(const NamedDecl *decl) {
  247. for (auto *annotation : decl->getUnusualAnnotations()) {
  248. if (auto *reg = dyn_cast<hlsl::RegisterAssignment>(annotation)) {
  249. return reg;
  250. }
  251. }
  252. return nullptr;
  253. }
  254. /// \brief Returns the stage variable's 'register(c#) assignment for the given
  255. /// Decl. Return nullptr if the given variable does not have such assignment.
  256. const hlsl::RegisterAssignment *getRegisterCAssignment(const NamedDecl *decl) {
  257. const auto *regAssignment = getResourceBinding(decl);
  258. if (regAssignment)
  259. return regAssignment->RegisterType == 'c' ? regAssignment : nullptr;
  260. return nullptr;
  261. }
  262. /// \brief Returns true if the given declaration has a primitive type qualifier.
  263. /// Returns false otherwise.
  264. inline bool hasGSPrimitiveTypeQualifier(const Decl *decl) {
  265. return decl->hasAttr<HLSLTriangleAttr>() ||
  266. decl->hasAttr<HLSLTriangleAdjAttr>() ||
  267. decl->hasAttr<HLSLPointAttr>() || decl->hasAttr<HLSLLineAttr>() ||
  268. decl->hasAttr<HLSLLineAdjAttr>();
  269. }
  270. /// \brief Deduces the parameter qualifier for the given decl.
  271. hlsl::DxilParamInputQual deduceParamQual(const DeclaratorDecl *decl,
  272. bool asInput) {
  273. const auto type = decl->getType();
  274. if (hlsl::IsHLSLInputPatchType(type))
  275. return hlsl::DxilParamInputQual::InputPatch;
  276. if (hlsl::IsHLSLOutputPatchType(type))
  277. return hlsl::DxilParamInputQual::OutputPatch;
  278. // TODO: Add support for multiple output streams.
  279. if (hlsl::IsHLSLStreamOutputType(type))
  280. return hlsl::DxilParamInputQual::OutStream0;
  281. // The inputs to the geometry shader that have a primitive type qualifier
  282. // must use 'InputPrimitive'.
  283. if (hasGSPrimitiveTypeQualifier(decl))
  284. return hlsl::DxilParamInputQual::InputPrimitive;
  285. if (decl->hasAttr<HLSLIndicesAttr>())
  286. return hlsl::DxilParamInputQual::OutIndices;
  287. if (decl->hasAttr<HLSLVerticesAttr>())
  288. return hlsl::DxilParamInputQual::OutVertices;
  289. if (decl->hasAttr<HLSLPrimitivesAttr>())
  290. return hlsl::DxilParamInputQual::OutPrimitives;
  291. if (decl->hasAttr<HLSLPayloadAttr>())
  292. return hlsl::DxilParamInputQual::InPayload;
  293. return asInput ? hlsl::DxilParamInputQual::In : hlsl::DxilParamInputQual::Out;
  294. }
  295. /// \brief Deduces the HLSL SigPoint for the given decl appearing in the given
  296. /// shader model.
  297. const hlsl::SigPoint *deduceSigPoint(const DeclaratorDecl *decl, bool asInput,
  298. const hlsl::ShaderModel::Kind kind,
  299. bool forPCF) {
  300. return hlsl::SigPoint::GetSigPoint(hlsl::SigPointFromInputQual(
  301. deduceParamQual(decl, asInput), kind, forPCF));
  302. }
  303. /// Returns the type of the given decl. If the given decl is a FunctionDecl,
  304. /// returns its result type.
  305. inline QualType getTypeOrFnRetType(const DeclaratorDecl *decl) {
  306. if (const auto *funcDecl = dyn_cast<FunctionDecl>(decl)) {
  307. return funcDecl->getReturnType();
  308. }
  309. return decl->getType();
  310. }
  311. /// Returns the number of base classes if this type is a derived class/struct.
  312. /// Returns zero otherwise.
  313. inline uint32_t getNumBaseClasses(QualType type) {
  314. if (const auto *cxxDecl = type->getAsCXXRecordDecl())
  315. return cxxDecl->getNumBases();
  316. return 0;
  317. }
  318. /// Returns the appropriate storage class for an extern variable of the given
  319. /// type.
  320. spv::StorageClass getStorageClassForExternVar(QualType type,
  321. bool hasGroupsharedAttr) {
  322. // For CS groupshared variables
  323. if (hasGroupsharedAttr)
  324. return spv::StorageClass::Workgroup;
  325. if (isAKindOfStructuredOrByteBuffer(type))
  326. return spv::StorageClass::Uniform;
  327. return spv::StorageClass::UniformConstant;
  328. }
  329. /// Returns the appropriate layout rule for an extern variable of the given
  330. /// type.
  331. SpirvLayoutRule getLayoutRuleForExternVar(QualType type,
  332. const SpirvCodeGenOptions &opts) {
  333. if (isAKindOfStructuredOrByteBuffer(type))
  334. return opts.sBufferLayoutRule;
  335. return SpirvLayoutRule::Void;
  336. }
  337. spv::ImageFormat getSpvImageFormat(const VKImageFormatAttr *imageFormatAttr) {
  338. if (imageFormatAttr == nullptr)
  339. return spv::ImageFormat::Unknown;
  340. switch (imageFormatAttr->getImageFormat()) {
  341. case VKImageFormatAttr::unknown:
  342. return spv::ImageFormat::Unknown;
  343. case VKImageFormatAttr::rgba32f:
  344. return spv::ImageFormat::Rgba32f;
  345. case VKImageFormatAttr::rgba16f:
  346. return spv::ImageFormat::Rgba16f;
  347. case VKImageFormatAttr::r32f:
  348. return spv::ImageFormat::R32f;
  349. case VKImageFormatAttr::rgba8:
  350. return spv::ImageFormat::Rgba8;
  351. case VKImageFormatAttr::rgba8snorm:
  352. return spv::ImageFormat::Rgba8Snorm;
  353. case VKImageFormatAttr::rg32f:
  354. return spv::ImageFormat::Rg32f;
  355. case VKImageFormatAttr::rg16f:
  356. return spv::ImageFormat::Rg16f;
  357. case VKImageFormatAttr::r11g11b10f:
  358. return spv::ImageFormat::R11fG11fB10f;
  359. case VKImageFormatAttr::r16f:
  360. return spv::ImageFormat::R16f;
  361. case VKImageFormatAttr::rgba16:
  362. return spv::ImageFormat::Rgba16;
  363. case VKImageFormatAttr::rgb10a2:
  364. return spv::ImageFormat::Rgb10A2;
  365. case VKImageFormatAttr::rg16:
  366. return spv::ImageFormat::Rg16;
  367. case VKImageFormatAttr::rg8:
  368. return spv::ImageFormat::Rg8;
  369. case VKImageFormatAttr::r16:
  370. return spv::ImageFormat::R16;
  371. case VKImageFormatAttr::r8:
  372. return spv::ImageFormat::R8;
  373. case VKImageFormatAttr::rgba16snorm:
  374. return spv::ImageFormat::Rgba16Snorm;
  375. case VKImageFormatAttr::rg16snorm:
  376. return spv::ImageFormat::Rg16Snorm;
  377. case VKImageFormatAttr::rg8snorm:
  378. return spv::ImageFormat::Rg8Snorm;
  379. case VKImageFormatAttr::r16snorm:
  380. return spv::ImageFormat::R16Snorm;
  381. case VKImageFormatAttr::r8snorm:
  382. return spv::ImageFormat::R8Snorm;
  383. case VKImageFormatAttr::rgba32i:
  384. return spv::ImageFormat::Rgba32i;
  385. case VKImageFormatAttr::rgba16i:
  386. return spv::ImageFormat::Rgba16i;
  387. case VKImageFormatAttr::rgba8i:
  388. return spv::ImageFormat::Rgba8i;
  389. case VKImageFormatAttr::r32i:
  390. return spv::ImageFormat::R32i;
  391. case VKImageFormatAttr::rg32i:
  392. return spv::ImageFormat::Rg32i;
  393. case VKImageFormatAttr::rg16i:
  394. return spv::ImageFormat::Rg16i;
  395. case VKImageFormatAttr::rg8i:
  396. return spv::ImageFormat::Rg8i;
  397. case VKImageFormatAttr::r16i:
  398. return spv::ImageFormat::R16i;
  399. case VKImageFormatAttr::r8i:
  400. return spv::ImageFormat::R8i;
  401. case VKImageFormatAttr::rgba32ui:
  402. return spv::ImageFormat::Rgba32ui;
  403. case VKImageFormatAttr::rgba16ui:
  404. return spv::ImageFormat::Rgba16ui;
  405. case VKImageFormatAttr::rgba8ui:
  406. return spv::ImageFormat::Rgba8ui;
  407. case VKImageFormatAttr::r32ui:
  408. return spv::ImageFormat::R32ui;
  409. case VKImageFormatAttr::rgb10a2ui:
  410. return spv::ImageFormat::Rgb10a2ui;
  411. case VKImageFormatAttr::rg32ui:
  412. return spv::ImageFormat::Rg32ui;
  413. case VKImageFormatAttr::rg16ui:
  414. return spv::ImageFormat::Rg16ui;
  415. case VKImageFormatAttr::rg8ui:
  416. return spv::ImageFormat::Rg8ui;
  417. case VKImageFormatAttr::r16ui:
  418. return spv::ImageFormat::R16ui;
  419. case VKImageFormatAttr::r8ui:
  420. return spv::ImageFormat::R8ui;
  421. case VKImageFormatAttr::r64ui:
  422. return spv::ImageFormat::R64ui;
  423. case VKImageFormatAttr::r64i:
  424. return spv::ImageFormat::R64i;
  425. }
  426. return spv::ImageFormat::Unknown;
  427. }
  428. } // anonymous namespace
  429. std::string StageVar::getSemanticStr() const {
  430. // A special case for zero index, which is equivalent to no index.
  431. // Use what is in the source code.
  432. // TODO: this looks like a hack to make the current tests happy.
  433. // Should consider remove it and fix all tests.
  434. if (semanticInfo.index == 0)
  435. return semanticInfo.str;
  436. std::ostringstream ss;
  437. ss << semanticInfo.name.str() << semanticInfo.index;
  438. return ss.str();
  439. }
  440. SpirvInstruction *CounterIdAliasPair::get(SpirvBuilder &builder,
  441. SpirvContext &spvContext) const {
  442. if (isAlias) {
  443. const auto *counterType = spvContext.getACSBufferCounterType();
  444. const auto *counterVarType =
  445. spvContext.getPointerType(counterType, spv::StorageClass::Uniform);
  446. return builder.createLoad(counterVarType, counterVar,
  447. /* SourceLocation */ {});
  448. }
  449. return counterVar;
  450. }
  451. const CounterIdAliasPair *
  452. CounterVarFields::get(const llvm::SmallVectorImpl<uint32_t> &indices) const {
  453. for (const auto &field : fields)
  454. if (field.indices == indices)
  455. return &field.counterVar;
  456. return nullptr;
  457. }
  458. bool CounterVarFields::assign(const CounterVarFields &srcFields,
  459. SpirvBuilder &builder,
  460. SpirvContext &context) const {
  461. for (const auto &field : fields) {
  462. const auto *srcField = srcFields.get(field.indices);
  463. if (!srcField)
  464. return false;
  465. field.counterVar.assign(*srcField, builder, context);
  466. }
  467. return true;
  468. }
  469. bool CounterVarFields::assign(const CounterVarFields &srcFields,
  470. const llvm::SmallVector<uint32_t, 4> &dstPrefix,
  471. const llvm::SmallVector<uint32_t, 4> &srcPrefix,
  472. SpirvBuilder &builder,
  473. SpirvContext &context) const {
  474. if (dstPrefix.empty() && srcPrefix.empty())
  475. return assign(srcFields, builder, context);
  476. llvm::SmallVector<uint32_t, 4> srcIndices = srcPrefix;
  477. // If whole has the given prefix, appends all elements after the prefix in
  478. // whole to srcIndices.
  479. const auto applyDiff =
  480. [&srcIndices](const llvm::SmallVector<uint32_t, 4> &whole,
  481. const llvm::SmallVector<uint32_t, 4> &prefix) -> bool {
  482. uint32_t i = 0;
  483. for (; i < prefix.size(); ++i)
  484. if (whole[i] != prefix[i]) {
  485. break;
  486. }
  487. if (i == prefix.size()) {
  488. for (; i < whole.size(); ++i)
  489. srcIndices.push_back(whole[i]);
  490. return true;
  491. }
  492. return false;
  493. };
  494. for (const auto &field : fields)
  495. if (applyDiff(field.indices, dstPrefix)) {
  496. const auto *srcField = srcFields.get(srcIndices);
  497. if (!srcField)
  498. return false;
  499. field.counterVar.assign(*srcField, builder, context);
  500. for (uint32_t i = srcPrefix.size(); i < srcIndices.size(); ++i)
  501. srcIndices.pop_back();
  502. }
  503. return true;
  504. }
  505. SemanticInfo DeclResultIdMapper::getStageVarSemantic(const NamedDecl *decl) {
  506. for (auto *annotation : decl->getUnusualAnnotations()) {
  507. if (auto *sema = dyn_cast<hlsl::SemanticDecl>(annotation)) {
  508. llvm::StringRef semanticStr = sema->SemanticName;
  509. llvm::StringRef semanticName;
  510. uint32_t index = 0;
  511. hlsl::Semantic::DecomposeNameAndIndex(semanticStr, &semanticName, &index);
  512. const auto *semantic = hlsl::Semantic::GetByName(semanticName);
  513. return {semanticStr, semantic, semanticName, index, sema->Loc};
  514. }
  515. }
  516. return {};
  517. }
  518. bool DeclResultIdMapper::createStageOutputVar(const DeclaratorDecl *decl,
  519. SpirvInstruction *storedValue,
  520. bool forPCF) {
  521. QualType type = getTypeOrFnRetType(decl);
  522. uint32_t arraySize = 0;
  523. // Output stream types (PointStream, LineStream, TriangleStream) are
  524. // translated as their underlying struct types.
  525. if (hlsl::IsHLSLStreamOutputType(type))
  526. type = hlsl::GetHLSLResourceResultType(type);
  527. if (decl->hasAttr<HLSLIndicesAttr>() || decl->hasAttr<HLSLVerticesAttr>() ||
  528. decl->hasAttr<HLSLPrimitivesAttr>()) {
  529. const auto *typeDecl = astContext.getAsConstantArrayType(type);
  530. type = typeDecl->getElementType();
  531. arraySize = static_cast<uint32_t>(typeDecl->getSize().getZExtValue());
  532. if (decl->hasAttr<HLSLIndicesAttr>()) {
  533. // create SPIR-V builtin array PrimitiveIndicesNV of type
  534. // "uint [MaxPrimitiveCount * verticesPerPrim]"
  535. uint32_t verticesPerPrim = 1;
  536. if (!isVectorType(type, nullptr, &verticesPerPrim)) {
  537. assert(isScalarType(type));
  538. }
  539. arraySize = arraySize * verticesPerPrim;
  540. QualType arrayType = astContext.getConstantArrayType(
  541. astContext.UnsignedIntTy, llvm::APInt(32, arraySize),
  542. clang::ArrayType::Normal, 0);
  543. stageVarInstructions[cast<DeclaratorDecl>(decl)] = getBuiltinVar(
  544. spv::BuiltIn::PrimitiveIndicesNV, arrayType, decl->getLocation());
  545. return true;
  546. }
  547. }
  548. const auto *sigPoint = deduceSigPoint(
  549. decl, /*asInput=*/false, spvContext.getCurrentShaderModelKind(), forPCF);
  550. // HS output variables are created using the other overload. For the rest,
  551. // none of them should be created as arrays.
  552. assert(sigPoint->GetKind() != hlsl::DXIL::SigPointKind::HSCPOut);
  553. SemanticInfo inheritSemantic = {};
  554. // If storedValue is 0, it means this parameter in the original source code is
  555. // not used at all. Avoid writing back.
  556. //
  557. // Write back of stage output variables in GS is manually controlled by
  558. // .Append() intrinsic method, implemented in writeBackOutputStream(). So
  559. // ignoreValue should be set to true for GS.
  560. const bool noWriteBack =
  561. storedValue == nullptr || spvContext.isGS() || spvContext.isMS();
  562. return createStageVars(sigPoint, decl, /*asInput=*/false, type, arraySize,
  563. "out.var", llvm::None, &storedValue, noWriteBack,
  564. &inheritSemantic);
  565. }
  566. bool DeclResultIdMapper::createStageOutputVar(const DeclaratorDecl *decl,
  567. uint32_t arraySize,
  568. SpirvInstruction *invocationId,
  569. SpirvInstruction *storedValue) {
  570. assert(spvContext.isHS());
  571. QualType type = getTypeOrFnRetType(decl);
  572. const auto *sigPoint =
  573. hlsl::SigPoint::GetSigPoint(hlsl::DXIL::SigPointKind::HSCPOut);
  574. SemanticInfo inheritSemantic = {};
  575. return createStageVars(sigPoint, decl, /*asInput=*/false, type, arraySize,
  576. "out.var", invocationId, &storedValue,
  577. /*noWriteBack=*/false, &inheritSemantic);
  578. }
  579. bool DeclResultIdMapper::createStageInputVar(const ParmVarDecl *paramDecl,
  580. SpirvInstruction **loadedValue,
  581. bool forPCF) {
  582. uint32_t arraySize = 0;
  583. QualType type = paramDecl->getType();
  584. // Deprive the outermost arrayness for HS/DS/GS and use arraySize
  585. // to convey that information
  586. if (hlsl::IsHLSLInputPatchType(type)) {
  587. arraySize = hlsl::GetHLSLInputPatchCount(type);
  588. type = hlsl::GetHLSLInputPatchElementType(type);
  589. } else if (hlsl::IsHLSLOutputPatchType(type)) {
  590. arraySize = hlsl::GetHLSLOutputPatchCount(type);
  591. type = hlsl::GetHLSLOutputPatchElementType(type);
  592. }
  593. if (hasGSPrimitiveTypeQualifier(paramDecl)) {
  594. const auto *typeDecl = astContext.getAsConstantArrayType(type);
  595. arraySize = static_cast<uint32_t>(typeDecl->getSize().getZExtValue());
  596. type = typeDecl->getElementType();
  597. }
  598. const auto *sigPoint =
  599. deduceSigPoint(paramDecl, /*asInput=*/true,
  600. spvContext.getCurrentShaderModelKind(), forPCF);
  601. SemanticInfo inheritSemantic = {};
  602. if (paramDecl->hasAttr<HLSLPayloadAttr>()) {
  603. spv::StorageClass sc = getStorageClassForSigPoint(sigPoint);
  604. return createPayloadStageVars(sigPoint, sc, paramDecl, /*asInput=*/true,
  605. type, "in.var", loadedValue);
  606. } else {
  607. return createStageVars(sigPoint, paramDecl, /*asInput=*/true, type,
  608. arraySize, "in.var", llvm::None, loadedValue,
  609. /*noWriteBack=*/false, &inheritSemantic);
  610. }
  611. }
  612. const DeclResultIdMapper::DeclSpirvInfo *
  613. DeclResultIdMapper::getDeclSpirvInfo(const ValueDecl *decl) const {
  614. auto it = astDecls.find(decl);
  615. if (it != astDecls.end())
  616. return &it->second;
  617. return nullptr;
  618. }
  619. SpirvInstruction *DeclResultIdMapper::getDeclEvalInfo(const ValueDecl *decl,
  620. SourceLocation loc) {
  621. const DeclSpirvInfo *info = getDeclSpirvInfo(decl);
  622. // If DeclSpirvInfo is not found for this decl, it might be because it is an
  623. // implicit VarDecl. All implicit VarDecls are lazily created in order to
  624. // avoid creating large number of unused variables/constants/enums.
  625. if (!info) {
  626. tryToCreateImplicitConstVar(decl);
  627. info = getDeclSpirvInfo(decl);
  628. }
  629. if (info) {
  630. if (info->indexInCTBuffer >= 0) {
  631. // If this is a VarDecl inside a HLSLBufferDecl, we need to do an extra
  632. // OpAccessChain to get the pointer to the variable since we created
  633. // a single variable for the whole buffer object.
  634. // Should only have VarDecls in a HLSLBufferDecl.
  635. QualType valueType = cast<VarDecl>(decl)->getType();
  636. return spvBuilder.createAccessChain(
  637. valueType, info->instr,
  638. {spvBuilder.getConstantInt(
  639. astContext.IntTy, llvm::APInt(32, info->indexInCTBuffer, true))},
  640. loc);
  641. } else if (auto *type = info->instr->getResultType()) {
  642. const auto *ptrTy = dyn_cast<HybridPointerType>(type);
  643. // If it is a local variable or function parameter with a bindless
  644. // array of an opaque type, we have to load it because we pass a
  645. // pointer of a global variable that has the bindless opaque array.
  646. if (ptrTy != nullptr && isBindlessOpaqueArray(decl->getType())) {
  647. auto *load = spvBuilder.createLoad(ptrTy, info->instr, loc);
  648. load->setRValue(false);
  649. return load;
  650. } else {
  651. return *info;
  652. }
  653. } else {
  654. return *info;
  655. }
  656. }
  657. emitFatalError("found unregistered decl", decl->getLocation())
  658. << decl->getName();
  659. emitNote("please file a bug report on "
  660. "https://github.com/Microsoft/DirectXShaderCompiler/issues with "
  661. "source code if possible",
  662. {});
  663. return 0;
  664. }
  665. SpirvFunctionParameter *
  666. DeclResultIdMapper::createFnParam(const ParmVarDecl *param,
  667. uint32_t dbgArgNumber) {
  668. const auto type = getTypeOrFnRetType(param);
  669. const auto loc = param->getLocation();
  670. const auto name = param->getName();
  671. SpirvFunctionParameter *fnParamInstr = spvBuilder.addFnParam(
  672. type, param->hasAttr<HLSLPreciseAttr>(), loc, param->getName());
  673. bool isAlias = false;
  674. (void)getTypeAndCreateCounterForPotentialAliasVar(param, &isAlias);
  675. fnParamInstr->setContainsAliasComponent(isAlias);
  676. assert(astDecls[param].instr == nullptr);
  677. astDecls[param].instr = fnParamInstr;
  678. if (spirvOptions.debugInfoRich) {
  679. // Add DebugLocalVariable information
  680. const auto &sm = astContext.getSourceManager();
  681. const uint32_t line = sm.getPresumedLineNumber(loc);
  682. const uint32_t column = sm.getPresumedColumnNumber(loc);
  683. const auto *info = theEmitter.getOrCreateRichDebugInfo(loc);
  684. // TODO: replace this with FlagIsLocal enum.
  685. uint32_t flags = 1 << 2;
  686. auto *debugLocalVar = spvBuilder.createDebugLocalVariable(
  687. type, name, info->source, line, column, info->scopeStack.back(), flags,
  688. dbgArgNumber);
  689. spvBuilder.createDebugDeclare(debugLocalVar, fnParamInstr);
  690. }
  691. return fnParamInstr;
  692. }
  693. void DeclResultIdMapper::createCounterVarForDecl(const DeclaratorDecl *decl) {
  694. const QualType declType = getTypeOrFnRetType(decl);
  695. if (!counterVars.count(decl) && isRWAppendConsumeSBuffer(declType)) {
  696. createCounterVar(decl, /*declId=*/0, /*isAlias=*/true);
  697. } else if (!fieldCounterVars.count(decl) && declType->isStructureType() &&
  698. // Exclude other resource types which are represented as structs
  699. !hlsl::IsHLSLResourceType(declType)) {
  700. createFieldCounterVars(decl);
  701. }
  702. }
  703. SpirvVariable *
  704. DeclResultIdMapper::createFnVar(const VarDecl *var,
  705. llvm::Optional<SpirvInstruction *> init) {
  706. const auto type = getTypeOrFnRetType(var);
  707. const auto loc = var->getLocation();
  708. const auto name = var->getName();
  709. const bool isPrecise = var->hasAttr<HLSLPreciseAttr>();
  710. SpirvVariable *varInstr = spvBuilder.addFnVar(
  711. type, loc, name, isPrecise, init.hasValue() ? init.getValue() : nullptr);
  712. bool isAlias = false;
  713. (void)getTypeAndCreateCounterForPotentialAliasVar(var, &isAlias);
  714. varInstr->setContainsAliasComponent(isAlias);
  715. assert(astDecls[var].instr == nullptr);
  716. astDecls[var].instr = varInstr;
  717. return varInstr;
  718. }
  719. SpirvDebugGlobalVariable *DeclResultIdMapper::createDebugGlobalVariable(
  720. SpirvVariable *var, const QualType &type, const SourceLocation &loc,
  721. const StringRef &name) {
  722. if (spirvOptions.debugInfoRich) {
  723. // Add DebugGlobalVariable information
  724. const auto &sm = astContext.getSourceManager();
  725. const uint32_t line = sm.getPresumedLineNumber(loc);
  726. const uint32_t column = sm.getPresumedColumnNumber(loc);
  727. const auto *info = theEmitter.getOrCreateRichDebugInfo(loc);
  728. // TODO: replace this with FlagIsDefinition enum.
  729. uint32_t flags = 1 << 3;
  730. // TODO: update linkageName correctly.
  731. auto *dbgGlobalVar = spvBuilder.createDebugGlobalVariable(
  732. type, name, info->source, line, column, info->scopeStack.back(),
  733. /* linkageName */ name, var, flags);
  734. dbgGlobalVar->setDebugSpirvType(var->getResultType());
  735. dbgGlobalVar->setLayoutRule(var->getLayoutRule());
  736. return dbgGlobalVar;
  737. }
  738. return nullptr;
  739. }
  740. SpirvVariable *
  741. DeclResultIdMapper::createFileVar(const VarDecl *var,
  742. llvm::Optional<SpirvInstruction *> init) {
  743. const auto type = getTypeOrFnRetType(var);
  744. const auto loc = var->getLocation();
  745. const auto name = var->getName();
  746. SpirvVariable *varInstr =
  747. spvBuilder.addModuleVar(type, spv::StorageClass::Private,
  748. var->hasAttr<HLSLPreciseAttr>(), name, init, loc);
  749. bool isAlias = false;
  750. (void)getTypeAndCreateCounterForPotentialAliasVar(var, &isAlias);
  751. varInstr->setContainsAliasComponent(isAlias);
  752. assert(astDecls[var].instr == nullptr);
  753. astDecls[var].instr = varInstr;
  754. createDebugGlobalVariable(varInstr, type, loc, name);
  755. return varInstr;
  756. }
  757. SpirvVariable *DeclResultIdMapper::createExternVar(const VarDecl *var) {
  758. const auto type = var->getType();
  759. const bool isGroupShared = var->hasAttr<HLSLGroupSharedAttr>();
  760. const bool isACRWSBuffer = isRWAppendConsumeSBuffer(type);
  761. const auto storageClass = getStorageClassForExternVar(type, isGroupShared);
  762. const auto rule = getLayoutRuleForExternVar(type, spirvOptions);
  763. const auto loc = var->getLocation();
  764. if (!isGroupShared && !isResourceType(type) &&
  765. !isResourceOnlyStructure(type)) {
  766. // We currently cannot support global structures that contain both resources
  767. // and non-resources. That would require significant work in manipulating
  768. // structure field decls, manipulating QualTypes, as well as inserting
  769. // non-resources into the Globals cbuffer which changes offset decorations
  770. // for it.
  771. if (isStructureContainingMixOfResourcesAndNonResources(type)) {
  772. emitError("global structures containing both resources and non-resources "
  773. "are not supported",
  774. loc);
  775. return nullptr;
  776. }
  777. // This is a stand-alone externally-visiable non-resource-type variable.
  778. // They should be grouped into the $Globals cbuffer. We create that cbuffer
  779. // and record all variables inside it upon seeing the first such variable.
  780. if (astDecls.count(var) == 0)
  781. createGlobalsCBuffer(var);
  782. auto *varInstr = astDecls[var].instr;
  783. return varInstr ? cast<SpirvVariable>(varInstr) : nullptr;
  784. }
  785. if (isResourceOnlyStructure(type)) {
  786. // We currently do not support global structures that contain buffers.
  787. // Supporting global structures that contain buffers has two complications:
  788. //
  789. // 1- Buffers have the Uniform storage class, whereas Textures/Samplers have
  790. // UniformConstant storage class. As a result, if a struct contains both
  791. // textures and buffers, it is not clear what storage class should be used
  792. // for the struct. Also legalization cannot deduce the proper storage class
  793. // for struct members based on the structure's storage class.
  794. //
  795. // 2- Any kind of structured buffer has associated counters. The current DXC
  796. // code is not written in a way to place associated counters inside a
  797. // structure. Changing this behavior is non-trivial. There's also
  798. // significant work to be done both in DXC (to properly generate binding
  799. // numbers for the resource and its associated counters at correct offsets)
  800. // and in spirv-opt (to flatten such strcutures and modify the binding
  801. // numbers accordingly).
  802. if (isStructureContainingAnyKindOfBuffer(type)) {
  803. emitError("global structures containing buffers are not supported", loc);
  804. return nullptr;
  805. }
  806. needsFlatteningCompositeResources = true;
  807. }
  808. const auto name = var->getName();
  809. SpirvVariable *varInstr = spvBuilder.addModuleVar(
  810. type, storageClass, var->hasAttr<HLSLPreciseAttr>(), name, llvm::None,
  811. loc);
  812. varInstr->setLayoutRule(rule);
  813. // If this variable has [[vk::image_format("..")]] attribute, we have to keep
  814. // it in the SpirvContext and use it when we lower the QualType to SpirvType.
  815. auto spvImageFormat = getSpvImageFormat(var->getAttr<VKImageFormatAttr>());
  816. if (spvImageFormat != spv::ImageFormat::Unknown)
  817. spvContext.registerImageFormatForSpirvVariable(varInstr, spvImageFormat);
  818. astDecls[var] = createDeclSpirvInfo(varInstr);
  819. createDebugGlobalVariable(varInstr, type, loc, name);
  820. // Variables in Workgroup do not need descriptor decorations.
  821. if (storageClass == spv::StorageClass::Workgroup)
  822. return varInstr;
  823. const auto *regAttr = getResourceBinding(var);
  824. const auto *bindingAttr = var->getAttr<VKBindingAttr>();
  825. const auto *counterBindingAttr = var->getAttr<VKCounterBindingAttr>();
  826. resourceVars.emplace_back(varInstr, var, loc, regAttr, bindingAttr,
  827. counterBindingAttr);
  828. if (const auto *inputAttachment = var->getAttr<VKInputAttachmentIndexAttr>())
  829. spvBuilder.decorateInputAttachmentIndex(varInstr,
  830. inputAttachment->getIndex(), loc);
  831. if (isACRWSBuffer) {
  832. // For {Append|Consume|RW}StructuredBuffer, we need to always create another
  833. // variable for its associated counter.
  834. createCounterVar(var, varInstr, /*isAlias=*/false);
  835. }
  836. return varInstr;
  837. }
  838. SpirvInstruction *
  839. DeclResultIdMapper::createOrUpdateStringVar(const VarDecl *var) {
  840. assert(hlsl::IsStringType(var->getType()) ||
  841. hlsl::IsStringLiteralType(var->getType()));
  842. // If the string variable is not initialized to a string literal, we cannot
  843. // generate an OpString for it.
  844. if (!var->hasInit()) {
  845. emitError("Found uninitialized string variable.", var->getLocation());
  846. return nullptr;
  847. }
  848. const StringLiteral *stringLiteral =
  849. dyn_cast<StringLiteral>(var->getInit()->IgnoreParenCasts());
  850. SpirvString *init = spvBuilder.getString(stringLiteral->getString());
  851. astDecls[var] = createDeclSpirvInfo(init);
  852. return init;
  853. }
  854. SpirvVariable *DeclResultIdMapper::createStructOrStructArrayVarOfExplicitLayout(
  855. const DeclContext *decl, int arraySize, const ContextUsageKind usageKind,
  856. llvm::StringRef typeName, llvm::StringRef varName) {
  857. // cbuffers are translated into OpTypeStruct with Block decoration.
  858. // tbuffers are translated into OpTypeStruct with BufferBlock decoration.
  859. // Push constants are translated into OpTypeStruct with Block decoration.
  860. //
  861. // Both cbuffers and tbuffers have the SPIR-V Uniform storage class.
  862. // Push constants have the SPIR-V PushConstant storage class.
  863. const bool forCBuffer = usageKind == ContextUsageKind::CBuffer;
  864. const bool forTBuffer = usageKind == ContextUsageKind::TBuffer;
  865. const bool forGlobals = usageKind == ContextUsageKind::Globals;
  866. const bool forPC = usageKind == ContextUsageKind::PushConstant;
  867. const bool forShaderRecordNV =
  868. usageKind == ContextUsageKind::ShaderRecordBufferNV;
  869. const bool forShaderRecordEXT =
  870. usageKind == ContextUsageKind::ShaderRecordBufferEXT;
  871. const auto &declGroup = collectDeclsInDeclContext(decl);
  872. // Collect the type and name for each field
  873. llvm::SmallVector<HybridStructType::FieldInfo, 4> fields;
  874. for (const auto *subDecl : declGroup) {
  875. // The field can only be FieldDecl (for normal structs) or VarDecl (for
  876. // HLSLBufferDecls).
  877. assert(isa<VarDecl>(subDecl) || isa<FieldDecl>(subDecl));
  878. const auto *declDecl = cast<DeclaratorDecl>(subDecl);
  879. // In case 'register(c#)' annotation is placed on a global variable.
  880. const hlsl::RegisterAssignment *registerC =
  881. forGlobals ? getRegisterCAssignment(declDecl) : nullptr;
  882. // All fields are qualified with const. It will affect the debug name.
  883. // We don't need it here.
  884. auto varType = declDecl->getType();
  885. varType.removeLocalConst();
  886. HybridStructType::FieldInfo info(varType, declDecl->getName(),
  887. declDecl->getAttr<VKOffsetAttr>(),
  888. getPackOffset(declDecl), registerC,
  889. declDecl->hasAttr<HLSLPreciseAttr>());
  890. fields.push_back(info);
  891. }
  892. // Get the type for the whole struct
  893. // tbuffer/TextureBuffers are non-writable SSBOs.
  894. const SpirvType *resultType = spvContext.getHybridStructType(
  895. fields, typeName, /*isReadOnly*/ forTBuffer,
  896. forTBuffer ? StructInterfaceType::StorageBuffer
  897. : StructInterfaceType::UniformBuffer);
  898. // Make an array if requested.
  899. if (arraySize > 0) {
  900. resultType = spvContext.getArrayType(resultType, arraySize,
  901. /*ArrayStride*/ llvm::None);
  902. } else if (arraySize == -1) {
  903. resultType =
  904. spvContext.getRuntimeArrayType(resultType, /*ArrayStride*/ llvm::None);
  905. }
  906. // Register the <type-id> for this decl
  907. ctBufferPCTypes[decl] = resultType;
  908. const auto sc = forPC ? spv::StorageClass::PushConstant
  909. : forShaderRecordNV
  910. ? spv::StorageClass::ShaderRecordBufferNV
  911. : forShaderRecordEXT
  912. ? spv::StorageClass::ShaderRecordBufferKHR
  913. : spv::StorageClass::Uniform;
  914. // Create the variable for the whole struct / struct array.
  915. // The fields may be 'precise', but the structure itself is not.
  916. SpirvVariable *var =
  917. spvBuilder.addModuleVar(resultType, sc, /*isPrecise*/ false, varName);
  918. const SpirvLayoutRule layoutRule =
  919. (forCBuffer || forGlobals)
  920. ? spirvOptions.cBufferLayoutRule
  921. : (forTBuffer ? spirvOptions.tBufferLayoutRule
  922. : spirvOptions.sBufferLayoutRule);
  923. var->setHlslUserType(forCBuffer ? "cbuffer" : forTBuffer ? "tbuffer" : "");
  924. var->setLayoutRule(layoutRule);
  925. return var;
  926. }
  927. void DeclResultIdMapper::createEnumConstant(const EnumConstantDecl *decl) {
  928. const auto *valueDecl = dyn_cast<ValueDecl>(decl);
  929. const auto enumConstant =
  930. spvBuilder.getConstantInt(astContext.IntTy, decl->getInitVal());
  931. SpirvVariable *varInstr = spvBuilder.addModuleVar(
  932. astContext.IntTy, spv::StorageClass::Private, /*isPrecise*/ false,
  933. decl->getName(), enumConstant, decl->getLocation());
  934. astDecls[valueDecl] = createDeclSpirvInfo(varInstr);
  935. }
  936. SpirvVariable *DeclResultIdMapper::createCTBuffer(const HLSLBufferDecl *decl) {
  937. // This function handles creation of cbuffer or tbuffer.
  938. const auto usageKind =
  939. decl->isCBuffer() ? ContextUsageKind::CBuffer : ContextUsageKind::TBuffer;
  940. const std::string structName = "type." + decl->getName().str();
  941. // The front-end does not allow arrays of cbuffer/tbuffer.
  942. SpirvVariable *bufferVar = createStructOrStructArrayVarOfExplicitLayout(
  943. decl, /*arraySize*/ 0, usageKind, structName, decl->getName());
  944. // We still register all VarDecls seperately here. All the VarDecls are
  945. // mapped to the <result-id> of the buffer object, which means when querying
  946. // querying the <result-id> for a certain VarDecl, we need to do an extra
  947. // OpAccessChain.
  948. int index = 0;
  949. for (const auto *subDecl : decl->decls()) {
  950. if (shouldSkipInStructLayout(subDecl))
  951. continue;
  952. const auto *varDecl = cast<VarDecl>(subDecl);
  953. astDecls[varDecl] = createDeclSpirvInfo(bufferVar, index++);
  954. }
  955. resourceVars.emplace_back(
  956. bufferVar, decl, decl->getLocation(), getResourceBinding(decl),
  957. decl->getAttr<VKBindingAttr>(), decl->getAttr<VKCounterBindingAttr>());
  958. auto *dbgGlobalVar = createDebugGlobalVariable(
  959. bufferVar, QualType(), decl->getLocation(), decl->getName());
  960. if (dbgGlobalVar != nullptr) {
  961. // C/TBuffer needs HLSLBufferDecl for debug type lowering.
  962. spvContext.registerStructDeclForSpirvType(bufferVar->getResultType(), decl);
  963. }
  964. return bufferVar;
  965. }
  966. SpirvVariable *DeclResultIdMapper::createCTBuffer(const VarDecl *decl) {
  967. // This function handles creation of ConstantBuffer<T> or TextureBuffer<T>.
  968. // The way this is represented in the AST is as follows:
  969. //
  970. // |-VarDecl MyCbuffer 'ConstantBuffer<T>':'ConstantBuffer<T>'
  971. // |-CXXRecordDecl referenced struct T definition
  972. // |-CXXRecordDecl implicit struct T
  973. // |-FieldDecl
  974. // |-...
  975. // |-FieldDecl
  976. const QualType type = decl->getType();
  977. assert(isConstantTextureBuffer(type));
  978. const RecordType *recordType = nullptr;
  979. const RecordType *templatedType = nullptr;
  980. int arraySize = 0;
  981. // In case we have an array of ConstantBuffer/TextureBuffer:
  982. if (const auto *arrayType = type->getAsArrayTypeUnsafe()) {
  983. const QualType elemType = arrayType->getElementType();
  984. recordType = elemType->getAs<RecordType>();
  985. templatedType =
  986. hlsl::GetHLSLResourceResultType(elemType)->getAs<RecordType>();
  987. if (const auto *caType = astContext.getAsConstantArrayType(type)) {
  988. arraySize = static_cast<uint32_t>(caType->getSize().getZExtValue());
  989. } else {
  990. arraySize = -1;
  991. }
  992. } else {
  993. recordType = type->getAs<RecordType>();
  994. templatedType = hlsl::GetHLSLResourceResultType(type)->getAs<RecordType>();
  995. }
  996. if (!recordType) {
  997. emitError("constant/texture buffer type %0 unimplemented",
  998. decl->getLocStart())
  999. << type;
  1000. return nullptr;
  1001. }
  1002. if (!templatedType) {
  1003. emitError(
  1004. "the underlying type for constant/texture buffer must be a struct",
  1005. decl->getLocStart())
  1006. << type;
  1007. return nullptr;
  1008. }
  1009. const bool isConstBuffer = isConstantBuffer(type);
  1010. const auto usageKind =
  1011. isConstBuffer ? ContextUsageKind::CBuffer : ContextUsageKind::TBuffer;
  1012. const std::string structName = "type." +
  1013. recordType->getDecl()->getName().str() + "." +
  1014. templatedType->getDecl()->getName().str();
  1015. SpirvVariable *bufferVar = createStructOrStructArrayVarOfExplicitLayout(
  1016. templatedType->getDecl(), arraySize, usageKind, structName,
  1017. decl->getName());
  1018. // We register the VarDecl here.
  1019. astDecls[decl] = createDeclSpirvInfo(bufferVar);
  1020. resourceVars.emplace_back(
  1021. bufferVar, decl, decl->getLocation(), getResourceBinding(decl),
  1022. decl->getAttr<VKBindingAttr>(), decl->getAttr<VKCounterBindingAttr>());
  1023. return bufferVar;
  1024. }
  1025. SpirvVariable *DeclResultIdMapper::createPushConstant(const VarDecl *decl) {
  1026. // The front-end errors out if non-struct type push constant is used.
  1027. const QualType type = decl->getType();
  1028. const auto *recordType = type->getAs<RecordType>();
  1029. if (isConstantBuffer(type)) {
  1030. // Get the templated type for ConstantBuffer.
  1031. recordType = hlsl::GetHLSLResourceResultType(type)->getAs<RecordType>();
  1032. }
  1033. assert(recordType);
  1034. const std::string structName =
  1035. "type.PushConstant." + recordType->getDecl()->getName().str();
  1036. SpirvVariable *var = createStructOrStructArrayVarOfExplicitLayout(
  1037. recordType->getDecl(), /*arraySize*/ 0, ContextUsageKind::PushConstant,
  1038. structName, decl->getName());
  1039. // Register the VarDecl
  1040. astDecls[decl] = createDeclSpirvInfo(var);
  1041. // Do not push this variable into resourceVars since it does not need
  1042. // descriptor set.
  1043. return var;
  1044. }
  1045. SpirvVariable *
  1046. DeclResultIdMapper::createShaderRecordBuffer(const VarDecl *decl,
  1047. ContextUsageKind kind) {
  1048. const auto *recordType =
  1049. hlsl::GetHLSLResourceResultType(decl->getType())->getAs<RecordType>();
  1050. assert(recordType);
  1051. assert(kind == ContextUsageKind::ShaderRecordBufferEXT ||
  1052. kind == ContextUsageKind::ShaderRecordBufferNV);
  1053. const auto typeName = kind == ContextUsageKind::ShaderRecordBufferEXT
  1054. ? "type.ShaderRecordBufferEXT."
  1055. : "type.ShaderRecordBufferNV.";
  1056. const std::string structName =
  1057. typeName + recordType->getDecl()->getName().str();
  1058. SpirvVariable *var = createStructOrStructArrayVarOfExplicitLayout(
  1059. recordType->getDecl(), /*arraySize*/ 0,
  1060. kind, structName, decl->getName());
  1061. // Register the VarDecl
  1062. astDecls[decl] = createDeclSpirvInfo(var);
  1063. // Do not push this variable into resourceVars since it does not need
  1064. // descriptor set.
  1065. return var;
  1066. }
  1067. SpirvVariable *
  1068. DeclResultIdMapper::createShaderRecordBuffer(const HLSLBufferDecl *decl,
  1069. ContextUsageKind kind) {
  1070. assert(kind == ContextUsageKind::ShaderRecordBufferEXT ||
  1071. kind == ContextUsageKind::ShaderRecordBufferNV);
  1072. const auto typeName = kind == ContextUsageKind::ShaderRecordBufferEXT
  1073. ? "type.ShaderRecordBufferEXT."
  1074. : "type.ShaderRecordBufferNV.";
  1075. const std::string structName =
  1076. typeName + decl->getName().str();
  1077. // The front-end does not allow arrays of cbuffer/tbuffer.
  1078. SpirvVariable *bufferVar = createStructOrStructArrayVarOfExplicitLayout(
  1079. decl, /*arraySize*/ 0, kind, structName,
  1080. decl->getName());
  1081. // We still register all VarDecls seperately here. All the VarDecls are
  1082. // mapped to the <result-id> of the buffer object, which means when
  1083. // querying the <result-id> for a certain VarDecl, we need to do an extra
  1084. // OpAccessChain.
  1085. int index = 0;
  1086. for (const auto *subDecl : decl->decls()) {
  1087. if (shouldSkipInStructLayout(subDecl))
  1088. continue;
  1089. const auto *varDecl = cast<VarDecl>(subDecl);
  1090. astDecls[varDecl] = createDeclSpirvInfo(bufferVar, index++);
  1091. }
  1092. return bufferVar;
  1093. }
  1094. void DeclResultIdMapper::createGlobalsCBuffer(const VarDecl *var) {
  1095. if (astDecls.count(var) != 0)
  1096. return;
  1097. const auto *context = var->getTranslationUnitDecl();
  1098. SpirvVariable *globals = createStructOrStructArrayVarOfExplicitLayout(
  1099. context, /*arraySize*/ 0, ContextUsageKind::Globals, "type.$Globals",
  1100. "$Globals");
  1101. resourceVars.emplace_back(globals, /*decl*/ nullptr, SourceLocation(),
  1102. nullptr, nullptr, nullptr, /*isCounterVar*/ false,
  1103. /*isGlobalsCBuffer*/ true);
  1104. uint32_t index = 0;
  1105. for (const auto *decl : collectDeclsInDeclContext(context)) {
  1106. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  1107. if (!spirvOptions.noWarnIgnoredFeatures) {
  1108. if (const auto *init = varDecl->getInit())
  1109. emitWarning(
  1110. "variable '%0' will be placed in $Globals so initializer ignored",
  1111. init->getExprLoc())
  1112. << var->getName() << init->getSourceRange();
  1113. }
  1114. if (const auto *attr = varDecl->getAttr<VKBindingAttr>()) {
  1115. emitError("variable '%0' will be placed in $Globals so cannot have "
  1116. "vk::binding attribute",
  1117. attr->getLocation())
  1118. << var->getName();
  1119. return;
  1120. }
  1121. astDecls[varDecl] = createDeclSpirvInfo(globals, index++);
  1122. }
  1123. }
  1124. }
  1125. SpirvFunction *DeclResultIdMapper::getOrRegisterFn(const FunctionDecl *fn) {
  1126. // Return it if it's already been created.
  1127. auto it = astFunctionDecls.find(fn);
  1128. if (it != astFunctionDecls.end()) {
  1129. return it->second;
  1130. }
  1131. bool isAlias = false;
  1132. (void)getTypeAndCreateCounterForPotentialAliasVar(fn, &isAlias);
  1133. const bool isPrecise = fn->hasAttr<HLSLPreciseAttr>();
  1134. const bool isNoInline = fn->hasAttr<NoInlineAttr>();
  1135. // Note: we do not need to worry about function parameter types at this point
  1136. // as this is used when function declarations are seen. When function
  1137. // definition is seen, the parameter types will be set properly and take into
  1138. // account whether the function is a member function of a class/struct (in
  1139. // which case a 'this' parameter is added at the beginnig).
  1140. SpirvFunction *spirvFunction =
  1141. spvBuilder.createSpirvFunction(fn->getReturnType(), fn->getLocation(),
  1142. fn->getName(), isPrecise, isNoInline);
  1143. // No need to dereference to get the pointer. Function returns that are
  1144. // stand-alone aliases are already pointers to values. All other cases should
  1145. // be normal rvalues.
  1146. if (!isAlias || !isAKindOfStructuredOrByteBuffer(fn->getReturnType()))
  1147. spirvFunction->setRValue();
  1148. spirvFunction->setConstainsAliasComponent(isAlias);
  1149. astFunctionDecls[fn] = spirvFunction;
  1150. return spirvFunction;
  1151. }
  1152. const CounterIdAliasPair *DeclResultIdMapper::getCounterIdAliasPair(
  1153. const DeclaratorDecl *decl, const llvm::SmallVector<uint32_t, 4> *indices) {
  1154. if (!decl)
  1155. return nullptr;
  1156. if (indices) {
  1157. // Indices are provided. Walk through the fields of the decl.
  1158. const auto counter = fieldCounterVars.find(decl);
  1159. if (counter != fieldCounterVars.end())
  1160. return counter->second.get(*indices);
  1161. } else {
  1162. // No indices. Check the stand-alone entities.
  1163. const auto counter = counterVars.find(decl);
  1164. if (counter != counterVars.end())
  1165. return &counter->second;
  1166. }
  1167. return nullptr;
  1168. }
  1169. const CounterVarFields *
  1170. DeclResultIdMapper::getCounterVarFields(const DeclaratorDecl *decl) {
  1171. if (!decl)
  1172. return nullptr;
  1173. const auto found = fieldCounterVars.find(decl);
  1174. if (found != fieldCounterVars.end())
  1175. return &found->second;
  1176. return nullptr;
  1177. }
  1178. void DeclResultIdMapper::registerSpecConstant(const VarDecl *decl,
  1179. SpirvInstruction *specConstant) {
  1180. specConstant->setRValue();
  1181. astDecls[decl] = createDeclSpirvInfo(specConstant);
  1182. }
  1183. void DeclResultIdMapper::createCounterVar(
  1184. const DeclaratorDecl *decl, SpirvInstruction *declInstr, bool isAlias,
  1185. const llvm::SmallVector<uint32_t, 4> *indices) {
  1186. std::string counterName = "counter.var." + decl->getName().str();
  1187. if (indices) {
  1188. // Append field indices to the name
  1189. for (const auto index : *indices)
  1190. counterName += "." + std::to_string(index);
  1191. }
  1192. const SpirvType *counterType = spvContext.getACSBufferCounterType();
  1193. // {RW|Append|Consume}StructuredBuffer are all in Uniform storage class.
  1194. // Alias counter variables should be created into the Private storage class.
  1195. const spv::StorageClass sc =
  1196. isAlias ? spv::StorageClass::Private : spv::StorageClass::Uniform;
  1197. if (isAlias) {
  1198. // Apply an extra level of pointer for alias counter variable
  1199. counterType =
  1200. spvContext.getPointerType(counterType, spv::StorageClass::Uniform);
  1201. }
  1202. SpirvVariable *counterInstr = spvBuilder.addModuleVar(
  1203. counterType, sc, /*isPrecise*/ false, counterName);
  1204. if (!isAlias) {
  1205. // Non-alias counter variables should be put in to resourceVars so that
  1206. // descriptors can be allocated for them.
  1207. resourceVars.emplace_back(counterInstr, decl, decl->getLocation(),
  1208. getResourceBinding(decl),
  1209. decl->getAttr<VKBindingAttr>(),
  1210. decl->getAttr<VKCounterBindingAttr>(), true);
  1211. assert(declInstr);
  1212. spvBuilder.decorateCounterBuffer(declInstr, counterInstr,
  1213. decl->getLocation());
  1214. }
  1215. if (indices)
  1216. fieldCounterVars[decl].append(*indices, counterInstr);
  1217. else
  1218. counterVars[decl] = {counterInstr, isAlias};
  1219. }
  1220. void DeclResultIdMapper::createFieldCounterVars(
  1221. const DeclaratorDecl *rootDecl, const DeclaratorDecl *decl,
  1222. llvm::SmallVector<uint32_t, 4> *indices) {
  1223. const QualType type = getTypeOrFnRetType(decl);
  1224. const auto *recordType = type->getAs<RecordType>();
  1225. assert(recordType);
  1226. const auto *recordDecl = recordType->getDecl();
  1227. for (const auto *field : recordDecl->fields()) {
  1228. // Build up the index chain
  1229. indices->push_back(getNumBaseClasses(type) + field->getFieldIndex());
  1230. const QualType fieldType = field->getType();
  1231. if (isRWAppendConsumeSBuffer(fieldType))
  1232. createCounterVar(rootDecl, /*declId=*/0, /*isAlias=*/true, indices);
  1233. else if (fieldType->isStructureType() &&
  1234. !hlsl::IsHLSLResourceType(fieldType))
  1235. // Go recursively into all nested structs
  1236. createFieldCounterVars(rootDecl, field, indices);
  1237. indices->pop_back();
  1238. }
  1239. }
  1240. const SpirvType *
  1241. DeclResultIdMapper::getCTBufferPushConstantType(const DeclContext *decl) {
  1242. const auto found = ctBufferPCTypes.find(decl);
  1243. assert(found != ctBufferPCTypes.end());
  1244. return found->second;
  1245. }
  1246. std::vector<SpirvVariable *> DeclResultIdMapper::collectStageVars() const {
  1247. std::vector<SpirvVariable *> vars;
  1248. for (auto var : glPerVertex.getStageInVars())
  1249. vars.push_back(var);
  1250. for (auto var : glPerVertex.getStageOutVars())
  1251. vars.push_back(var);
  1252. llvm::DenseSet<SpirvInstruction *> seenVars;
  1253. for (const auto &var : stageVars) {
  1254. auto *instr = var.getSpirvInstr();
  1255. if (seenVars.count(instr) == 0) {
  1256. vars.push_back(instr);
  1257. seenVars.insert(instr);
  1258. }
  1259. }
  1260. return vars;
  1261. }
  1262. namespace {
  1263. /// A class for managing stage input/output locations to avoid duplicate uses of
  1264. /// the same location.
  1265. class LocationSet {
  1266. public:
  1267. /// Maximum number of indices supported
  1268. const static uint32_t kMaxIndex = 2;
  1269. /// Maximum number of locations supported
  1270. // Typically we won't have that many stage input or output variables.
  1271. // Using 64 should be fine here.
  1272. const static uint32_t kMaxLoc = 64;
  1273. LocationSet() {
  1274. for (uint32_t i = 0; i < kMaxIndex; ++i) {
  1275. usedLocs[i].resize(kMaxLoc);
  1276. nextLoc[i] = 0;
  1277. }
  1278. }
  1279. /// Uses the given location.
  1280. void useLoc(uint32_t loc, uint32_t index = 0) {
  1281. assert(index < kMaxIndex);
  1282. usedLocs[index].set(loc);
  1283. }
  1284. /// Uses the next |count| available location.
  1285. int useNextLocs(uint32_t count, uint32_t index = 0) {
  1286. assert(index < kMaxIndex);
  1287. auto &locs = usedLocs[index];
  1288. auto &next = nextLoc[index];
  1289. while (locs[next])
  1290. next++;
  1291. int toUse = next;
  1292. for (uint32_t i = 0; i < count; ++i) {
  1293. assert(!locs[next]);
  1294. locs.set(next++);
  1295. }
  1296. return toUse;
  1297. }
  1298. /// Returns true if the given location number is already used.
  1299. bool isLocUsed(uint32_t loc, uint32_t index = 0) {
  1300. assert(index < kMaxIndex);
  1301. return usedLocs[index][loc];
  1302. }
  1303. private:
  1304. llvm::SmallBitVector usedLocs[kMaxIndex]; ///< All previously used locations
  1305. uint32_t nextLoc[kMaxIndex]; ///< Next available location
  1306. };
  1307. /// A class for managing resource bindings to avoid duplicate uses of the same
  1308. /// set and binding number.
  1309. class BindingSet {
  1310. public:
  1311. /// Uses the given set and binding number. Returns false if the binding number
  1312. /// was already occupied in the set, and returns true otherwise.
  1313. bool useBinding(uint32_t binding, uint32_t set) {
  1314. bool inserted = false;
  1315. std::tie(std::ignore, inserted) = usedBindings[set].insert(binding);
  1316. return inserted;
  1317. }
  1318. /// Uses the next available binding number in |set|. If more than one binding
  1319. /// number is to be occupied, it finds the next available chunk that can fit
  1320. /// |numBindingsToUse| in the |set|.
  1321. uint32_t useNextBinding(uint32_t set, uint32_t numBindingsToUse = 1,
  1322. uint32_t bindingShift = 0) {
  1323. uint32_t bindingNoStart =
  1324. getNextBindingChunk(set, numBindingsToUse, bindingShift);
  1325. auto &binding = usedBindings[set];
  1326. for (uint32_t i = 0; i < numBindingsToUse; ++i)
  1327. binding.insert(bindingNoStart + i);
  1328. return bindingNoStart;
  1329. }
  1330. /// Returns the first available binding number in the |set| for which |n|
  1331. /// consecutive binding numbers are unused starting at |bindingShift|.
  1332. uint32_t getNextBindingChunk(uint32_t set, uint32_t n,
  1333. uint32_t bindingShift) {
  1334. auto &existingBindings = usedBindings[set];
  1335. // There were no bindings in this set. Can start at binding zero.
  1336. if (existingBindings.empty())
  1337. return bindingShift;
  1338. // Check whether the chunk of |n| binding numbers can be fitted at the
  1339. // very beginning of the list (start at binding 0 in the current set).
  1340. uint32_t curBinding = *existingBindings.begin();
  1341. if (curBinding >= (n + bindingShift))
  1342. return bindingShift;
  1343. auto iter = std::next(existingBindings.begin());
  1344. while (iter != existingBindings.end()) {
  1345. // There exists a next binding number that is used. Check to see if the
  1346. // gap between current binding number and next binding number is large
  1347. // enough to accommodate |n|.
  1348. uint32_t nextBinding = *iter;
  1349. if ((bindingShift > 0) && (curBinding < (bindingShift - 1)))
  1350. curBinding = bindingShift - 1;
  1351. if (curBinding < nextBinding && n <= nextBinding - curBinding - 1)
  1352. return curBinding + 1;
  1353. curBinding = nextBinding;
  1354. // Peek at the next binding that has already been used (if any).
  1355. ++iter;
  1356. }
  1357. // |curBinding| was the last binding that was used in this set. The next
  1358. // chunk of |n| bindings can start at |curBinding|+1.
  1359. return std::max(curBinding + 1, bindingShift);
  1360. }
  1361. private:
  1362. ///< set number -> set of used binding number
  1363. llvm::DenseMap<uint32_t, std::set<uint32_t>> usedBindings;
  1364. };
  1365. } // namespace
  1366. bool DeclResultIdMapper::checkSemanticDuplication(bool forInput) {
  1367. llvm::StringSet<> seenSemantics;
  1368. bool success = true;
  1369. for (const auto &var : stageVars) {
  1370. auto s = var.getSemanticStr();
  1371. if (s.empty()) {
  1372. // We translate WaveGetLaneCount(), WaveGetLaneIndex() and 'payload' param
  1373. // block declaration into builtin variables. Those variables are inserted
  1374. // into the normal stage IO processing pipeline, but with the semantics as
  1375. // empty strings.
  1376. assert(var.isSpirvBuitin());
  1377. continue;
  1378. }
  1379. // Allow builtin variables to alias each other. We already have uniqify
  1380. // mechanism in SpirvBuilder.
  1381. if (var.isSpirvBuitin())
  1382. continue;
  1383. if (forInput && var.getSigPoint()->IsInput()) {
  1384. if (seenSemantics.count(s)) {
  1385. emitError("input semantic '%0' used more than once", {}) << s;
  1386. success = false;
  1387. }
  1388. seenSemantics.insert(s);
  1389. } else if (!forInput && var.getSigPoint()->IsOutput()) {
  1390. if (seenSemantics.count(s)) {
  1391. emitError("output semantic '%0' used more than once", {}) << s;
  1392. success = false;
  1393. }
  1394. seenSemantics.insert(s);
  1395. }
  1396. }
  1397. return success;
  1398. }
  1399. bool DeclResultIdMapper::finalizeStageIOLocations(bool forInput) {
  1400. if (!checkSemanticDuplication(forInput))
  1401. return false;
  1402. // Returns false if the given StageVar is an input/output variable without
  1403. // explicit location assignment. Otherwise, returns true.
  1404. const auto locAssigned = [forInput, this](const StageVar &v) {
  1405. if (forInput == isInputStorageClass(v))
  1406. // No need to assign location for builtins. Treat as assigned.
  1407. return v.isSpirvBuitin() || v.getLocationAttr() != nullptr;
  1408. // For the ones we don't care, treat as assigned.
  1409. return true;
  1410. };
  1411. // If we have explicit location specified for all input/output variables,
  1412. // use them instead assign by ourselves.
  1413. if (std::all_of(stageVars.begin(), stageVars.end(), locAssigned)) {
  1414. LocationSet locSet;
  1415. bool noError = true;
  1416. for (const auto &var : stageVars) {
  1417. // Skip builtins & those stage variables we are not handling for this call
  1418. if (var.isSpirvBuitin() || forInput != isInputStorageClass(var))
  1419. continue;
  1420. const auto *attr = var.getLocationAttr();
  1421. const auto loc = attr->getNumber();
  1422. const auto attrLoc = attr->getLocation(); // Attr source code location
  1423. const auto idx = var.getIndexAttr() ? var.getIndexAttr()->getNumber() : 0;
  1424. if ((const unsigned)loc >= LocationSet::kMaxLoc) {
  1425. emitError("stage %select{output|input}0 location #%1 too large",
  1426. attrLoc)
  1427. << forInput << loc;
  1428. return false;
  1429. }
  1430. // Make sure the same location is not assigned more than once
  1431. if (locSet.isLocUsed(loc, idx)) {
  1432. emitError("stage %select{output|input}0 location #%1 already assigned",
  1433. attrLoc)
  1434. << forInput << loc;
  1435. noError = false;
  1436. }
  1437. locSet.useLoc(loc, idx);
  1438. spvBuilder.decorateLocation(var.getSpirvInstr(), loc);
  1439. if (var.getIndexAttr())
  1440. spvBuilder.decorateIndex(var.getSpirvInstr(), idx,
  1441. var.getSemanticInfo().loc);
  1442. }
  1443. return noError;
  1444. }
  1445. std::vector<const StageVar *> vars;
  1446. LocationSet locSet;
  1447. for (const auto &var : stageVars) {
  1448. if (var.isSpirvBuitin() || forInput != isInputStorageClass(var))
  1449. continue;
  1450. if (var.getLocationAttr()) {
  1451. // We have checked that not all of the stage variables have explicit
  1452. // location assignment.
  1453. emitError("partial explicit stage %select{output|input}0 location "
  1454. "assignment via vk::location(X) unsupported",
  1455. {})
  1456. << forInput;
  1457. return false;
  1458. }
  1459. const auto &semaInfo = var.getSemanticInfo();
  1460. // We should special rules for SV_Target: the location number comes from the
  1461. // semantic string index.
  1462. if (semaInfo.isTarget()) {
  1463. spvBuilder.decorateLocation(var.getSpirvInstr(), semaInfo.index);
  1464. locSet.useLoc(semaInfo.index);
  1465. } else {
  1466. vars.push_back(&var);
  1467. }
  1468. }
  1469. // If alphabetical ordering was requested, sort by semantic string.
  1470. // Since HS includes 2 sets of outputs (patch-constant output and
  1471. // OutputPatch), running into location mismatches between HS and DS is very
  1472. // likely. In order to avoid location mismatches between HS and DS, use
  1473. // alphabetical ordering.
  1474. if (spirvOptions.stageIoOrder == "alpha" ||
  1475. (!forInput && spvContext.isHS()) || (forInput && spvContext.isDS())) {
  1476. // Sort stage input/output variables alphabetically
  1477. std::sort(vars.begin(), vars.end(),
  1478. [](const StageVar *a, const StageVar *b) {
  1479. return a->getSemanticStr() < b->getSemanticStr();
  1480. });
  1481. }
  1482. for (const auto *var : vars)
  1483. spvBuilder.decorateLocation(var->getSpirvInstr(),
  1484. locSet.useNextLocs(var->getLocationCount()));
  1485. return true;
  1486. }
  1487. namespace {
  1488. /// A class for maintaining the binding number shift requested for descriptor
  1489. /// sets.
  1490. class BindingShiftMapper {
  1491. public:
  1492. explicit BindingShiftMapper(const llvm::SmallVectorImpl<int32_t> &shifts)
  1493. : masterShift(0) {
  1494. assert(shifts.size() % 2 == 0);
  1495. if (shifts.size() == 2 && shifts[1] == -1) {
  1496. masterShift = shifts[0];
  1497. } else {
  1498. for (uint32_t i = 0; i < shifts.size(); i += 2)
  1499. perSetShift[shifts[i + 1]] = shifts[i];
  1500. }
  1501. }
  1502. /// Returns the shift amount for the given set.
  1503. int32_t getShiftForSet(int32_t set) const {
  1504. const auto found = perSetShift.find(set);
  1505. if (found != perSetShift.end())
  1506. return found->second;
  1507. return masterShift;
  1508. }
  1509. private:
  1510. uint32_t masterShift; /// Shift amount applies to all sets.
  1511. llvm::DenseMap<int32_t, int32_t> perSetShift;
  1512. };
  1513. /// A class for maintaining the mapping from source code register attributes to
  1514. /// descriptor set and number settings.
  1515. class RegisterBindingMapper {
  1516. public:
  1517. /// Takes in the relation between register attributes and descriptor settings.
  1518. /// Each relation is represented by four strings:
  1519. /// <register-type-number> <space> <descriptor-binding> <set>
  1520. bool takeInRelation(const std::vector<std::string> &relation,
  1521. std::string *error) {
  1522. assert(relation.size() % 4 == 0);
  1523. mapping.clear();
  1524. for (uint32_t i = 0; i < relation.size(); i += 4) {
  1525. int32_t spaceNo = -1, setNo = -1, bindNo = -1;
  1526. if (StringRef(relation[i + 1]).getAsInteger(10, spaceNo) || spaceNo < 0) {
  1527. *error = "space number: " + relation[i + 1];
  1528. return false;
  1529. }
  1530. if (StringRef(relation[i + 2]).getAsInteger(10, bindNo) || bindNo < 0) {
  1531. *error = "binding number: " + relation[i + 2];
  1532. return false;
  1533. }
  1534. if (StringRef(relation[i + 3]).getAsInteger(10, setNo) || setNo < 0) {
  1535. *error = "set number: " + relation[i + 3];
  1536. return false;
  1537. }
  1538. mapping[relation[i + 1] + relation[i]] = std::make_pair(setNo, bindNo);
  1539. }
  1540. return true;
  1541. }
  1542. /// Returns true and set the correct set and binding number if we can find a
  1543. /// descriptor setting for the given register. False otherwise.
  1544. bool getSetBinding(const hlsl::RegisterAssignment *regAttr,
  1545. uint32_t defaultSpace, int *setNo, int *bindNo) const {
  1546. std::ostringstream iss;
  1547. iss << regAttr->RegisterSpace.getValueOr(defaultSpace)
  1548. << regAttr->RegisterType << regAttr->RegisterNumber;
  1549. auto found = mapping.find(iss.str());
  1550. if (found != mapping.end()) {
  1551. *setNo = found->second.first;
  1552. *bindNo = found->second.second;
  1553. return true;
  1554. }
  1555. return false;
  1556. }
  1557. private:
  1558. llvm::StringMap<std::pair<int, int>> mapping;
  1559. };
  1560. } // namespace
  1561. bool DeclResultIdMapper::decorateResourceBindings() {
  1562. // For normal resource, we support 4 approaches of setting binding numbers:
  1563. // - m1: [[vk::binding(...)]]
  1564. // - m2: :register(xX, spaceY)
  1565. // - m3: None
  1566. // - m4: :register(spaceY)
  1567. //
  1568. // For associated counters, we support 2 approaches:
  1569. // - c1: [[vk::counter_binding(...)]
  1570. // - c2: None
  1571. //
  1572. // In combination, we need to handle 12 cases:
  1573. // - 4 cases for nomral resoures (m1, m2, m3, m4)
  1574. // - 8 cases for associated counters (mX * cY)
  1575. //
  1576. // In the following order:
  1577. // - m1, mX * c1
  1578. // - m2
  1579. // - m3, m4, mX * c2
  1580. // The "-auto-binding-space" command line option can be used to specify a
  1581. // certain space as default. UINT_MAX means the user has not provided this
  1582. // option. If not provided, the SPIR-V backend uses space "0" as default.
  1583. auto defaultSpaceOpt =
  1584. theEmitter.getCompilerInstance().getCodeGenOpts().HLSLDefaultSpace;
  1585. uint32_t defaultSpace = (defaultSpaceOpt == UINT_MAX) ? 0 : defaultSpaceOpt;
  1586. const bool bindGlobals = !spirvOptions.bindGlobals.empty();
  1587. int32_t globalsBindNo = -1, globalsSetNo = -1;
  1588. if (bindGlobals) {
  1589. assert(spirvOptions.bindGlobals.size() == 2);
  1590. if (StringRef(spirvOptions.bindGlobals[0])
  1591. .getAsInteger(10, globalsBindNo) ||
  1592. globalsBindNo < 0) {
  1593. emitError("invalid -fvk-bind-globals binding number: %0", {})
  1594. << spirvOptions.bindGlobals[0];
  1595. return false;
  1596. }
  1597. if (StringRef(spirvOptions.bindGlobals[1]).getAsInteger(10, globalsSetNo) ||
  1598. globalsSetNo < 0) {
  1599. emitError("invalid -fvk-bind-globals set number: %0", {})
  1600. << spirvOptions.bindGlobals[1];
  1601. return false;
  1602. }
  1603. }
  1604. // Special handling of -fvk-bind-register, which requires
  1605. // * All resources are annoated with :register() in the source code
  1606. // * -fvk-bind-register is specified for every resource
  1607. if (!spirvOptions.bindRegister.empty()) {
  1608. RegisterBindingMapper bindingMapper;
  1609. std::string error;
  1610. if (!bindingMapper.takeInRelation(spirvOptions.bindRegister, &error)) {
  1611. emitError("invalid -fvk-bind-register %0", {}) << error;
  1612. return false;
  1613. }
  1614. for (const auto &var : resourceVars)
  1615. if (const auto *regAttr = var.getRegister()) {
  1616. if (var.isCounter()) {
  1617. emitError("-fvk-bind-register for RW/Append/Consume StructuredBuffer "
  1618. "unimplemented",
  1619. var.getSourceLocation());
  1620. } else {
  1621. int setNo = 0, bindNo = 0;
  1622. if (!bindingMapper.getSetBinding(regAttr, defaultSpace, &setNo,
  1623. &bindNo)) {
  1624. emitError("missing -fvk-bind-register for resource",
  1625. var.getSourceLocation());
  1626. return false;
  1627. }
  1628. spvBuilder.decorateDSetBinding(var.getSpirvInstr(), setNo, bindNo);
  1629. }
  1630. } else if (bindGlobals && var.isGlobalsBuffer()) {
  1631. spvBuilder.decorateDSetBinding(var.getSpirvInstr(), globalsSetNo,
  1632. globalsBindNo);
  1633. } else {
  1634. emitError(
  1635. "-fvk-bind-register requires register annotations on all resources",
  1636. var.getSourceLocation());
  1637. return false;
  1638. }
  1639. return true;
  1640. }
  1641. BindingSet bindingSet;
  1642. // Decorates the given varId of the given category with set number
  1643. // setNo, binding number bindingNo. Ignores overlaps.
  1644. const auto tryToDecorate = [this, &bindingSet](const ResourceVar &var,
  1645. const uint32_t setNo,
  1646. const uint32_t bindingNo) {
  1647. // By default we use one binding number per resource, and an array of
  1648. // resources also gets only one binding number. However, for array of
  1649. // resources (e.g. array of textures), DX uses one binding number per array
  1650. // element. We can match this behavior via a command line option.
  1651. uint32_t numBindingsToUse = 1;
  1652. if (spirvOptions.flattenResourceArrays || needsFlatteningCompositeResources)
  1653. numBindingsToUse = getNumBindingsUsedByResourceType(
  1654. var.getSpirvInstr()->getAstResultType());
  1655. for (uint32_t i = 0; i < numBindingsToUse; ++i) {
  1656. bool success = bindingSet.useBinding(bindingNo + i, setNo);
  1657. // We will not emit an error if we find a set/binding overlap because it
  1658. // is possible that the optimizer optimizes away a resource which resolves
  1659. // the overlap.
  1660. (void)success;
  1661. }
  1662. // No need to decorate multiple binding numbers for arrays. It will be done
  1663. // by legalization/optimization.
  1664. spvBuilder.decorateDSetBinding(var.getSpirvInstr(), setNo, bindingNo);
  1665. };
  1666. for (const auto &var : resourceVars) {
  1667. if (var.isCounter()) {
  1668. if (const auto *vkCBinding = var.getCounterBinding()) {
  1669. // Process mX * c1
  1670. uint32_t set = defaultSpace;
  1671. if (const auto *vkBinding = var.getBinding())
  1672. set = getVkBindingAttrSet(vkBinding, defaultSpace);
  1673. else if (const auto *reg = var.getRegister())
  1674. set = reg->RegisterSpace.getValueOr(defaultSpace);
  1675. tryToDecorate(var, set, vkCBinding->getBinding());
  1676. }
  1677. } else {
  1678. if (const auto *vkBinding = var.getBinding()) {
  1679. // Process m1
  1680. tryToDecorate(var, getVkBindingAttrSet(vkBinding, defaultSpace),
  1681. vkBinding->getBinding());
  1682. }
  1683. }
  1684. }
  1685. BindingShiftMapper bShiftMapper(spirvOptions.bShift);
  1686. BindingShiftMapper tShiftMapper(spirvOptions.tShift);
  1687. BindingShiftMapper sShiftMapper(spirvOptions.sShift);
  1688. BindingShiftMapper uShiftMapper(spirvOptions.uShift);
  1689. // Process m2
  1690. for (const auto &var : resourceVars)
  1691. if (!var.isCounter() && !var.getBinding())
  1692. if (const auto *reg = var.getRegister()) {
  1693. // Skip space-only register() annotations
  1694. if (reg->isSpaceOnly())
  1695. continue;
  1696. const uint32_t set = reg->RegisterSpace.getValueOr(defaultSpace);
  1697. uint32_t binding = reg->RegisterNumber;
  1698. switch (reg->RegisterType) {
  1699. case 'b':
  1700. binding += bShiftMapper.getShiftForSet(set);
  1701. break;
  1702. case 't':
  1703. binding += tShiftMapper.getShiftForSet(set);
  1704. break;
  1705. case 's':
  1706. binding += sShiftMapper.getShiftForSet(set);
  1707. break;
  1708. case 'u':
  1709. binding += uShiftMapper.getShiftForSet(set);
  1710. break;
  1711. case 'c':
  1712. // For setting packing offset. Does not affect binding.
  1713. break;
  1714. default:
  1715. llvm_unreachable("unknown register type found");
  1716. }
  1717. tryToDecorate(var, set, binding);
  1718. }
  1719. for (const auto &var : resourceVars) {
  1720. // By default we use one binding number per resource, and an array of
  1721. // resources also gets only one binding number. However, for array of
  1722. // resources (e.g. array of textures), DX uses one binding number per array
  1723. // element. We can match this behavior via a command line option.
  1724. uint32_t numBindingsToUse = 1;
  1725. if (spirvOptions.flattenResourceArrays || needsFlatteningCompositeResources)
  1726. numBindingsToUse = getNumBindingsUsedByResourceType(
  1727. var.getSpirvInstr()->getAstResultType());
  1728. BindingShiftMapper *bindingShiftMapper = nullptr;
  1729. if (spirvOptions.autoShiftBindings) {
  1730. char registerType = '\0';
  1731. if (getImplicitRegisterType(var, &registerType)) {
  1732. switch (registerType) {
  1733. case 'b':
  1734. bindingShiftMapper = &bShiftMapper;
  1735. break;
  1736. case 't':
  1737. bindingShiftMapper = &tShiftMapper;
  1738. break;
  1739. case 's':
  1740. bindingShiftMapper = &sShiftMapper;
  1741. break;
  1742. case 'u':
  1743. bindingShiftMapper = &uShiftMapper;
  1744. break;
  1745. default:
  1746. llvm_unreachable("unknown register type found");
  1747. }
  1748. }
  1749. }
  1750. if (var.isCounter()) {
  1751. if (!var.getCounterBinding()) {
  1752. // Process mX * c2
  1753. uint32_t set = defaultSpace;
  1754. if (const auto *vkBinding = var.getBinding())
  1755. set = getVkBindingAttrSet(vkBinding, defaultSpace);
  1756. else if (const auto *reg = var.getRegister())
  1757. set = reg->RegisterSpace.getValueOr(defaultSpace);
  1758. uint32_t bindingShift = 0;
  1759. if (bindingShiftMapper)
  1760. bindingShift = bindingShiftMapper->getShiftForSet(set);
  1761. spvBuilder.decorateDSetBinding(
  1762. var.getSpirvInstr(), set,
  1763. bindingSet.useNextBinding(set, numBindingsToUse, bindingShift));
  1764. }
  1765. } else if (!var.getBinding()) {
  1766. const auto *reg = var.getRegister();
  1767. if (reg && reg->isSpaceOnly()) {
  1768. const uint32_t set = reg->RegisterSpace.getValueOr(defaultSpace);
  1769. uint32_t bindingShift = 0;
  1770. if (bindingShiftMapper)
  1771. bindingShift = bindingShiftMapper->getShiftForSet(set);
  1772. spvBuilder.decorateDSetBinding(
  1773. var.getSpirvInstr(), set,
  1774. bindingSet.useNextBinding(set, numBindingsToUse, bindingShift));
  1775. } else if (!reg) {
  1776. // Process m3 (no 'vk::binding' and no ':register' assignment)
  1777. // There is a special case for the $Globals cbuffer. The $Globals buffer
  1778. // doesn't have either 'vk::binding' or ':register', but the user may
  1779. // ask for a specific binding for it via command line options.
  1780. if (bindGlobals && var.isGlobalsBuffer()) {
  1781. uint32_t bindingShift = 0;
  1782. if (bindingShiftMapper)
  1783. bindingShift = bindingShiftMapper->getShiftForSet(globalsSetNo);
  1784. spvBuilder.decorateDSetBinding(var.getSpirvInstr(), globalsSetNo,
  1785. globalsBindNo + bindingShift);
  1786. }
  1787. // The normal case
  1788. else {
  1789. uint32_t bindingShift = 0;
  1790. if (bindingShiftMapper)
  1791. bindingShift = bindingShiftMapper->getShiftForSet(defaultSpace);
  1792. spvBuilder.decorateDSetBinding(
  1793. var.getSpirvInstr(), defaultSpace,
  1794. bindingSet.useNextBinding(defaultSpace, numBindingsToUse,
  1795. bindingShift));
  1796. }
  1797. }
  1798. }
  1799. }
  1800. return true;
  1801. }
  1802. bool DeclResultIdMapper::decorateResourceCoherent() {
  1803. for (const auto &var : resourceVars) {
  1804. if (const auto *decl = var.getDeclaration()) {
  1805. if (decl->getAttr<HLSLGloballyCoherentAttr>()) {
  1806. spvBuilder.decorateCoherent(var.getSpirvInstr(),
  1807. var.getSourceLocation());
  1808. }
  1809. }
  1810. }
  1811. return true;
  1812. }
  1813. bool DeclResultIdMapper::createStageVars(
  1814. const hlsl::SigPoint *sigPoint, const NamedDecl *decl, bool asInput,
  1815. QualType type, uint32_t arraySize, const llvm::StringRef namePrefix,
  1816. llvm::Optional<SpirvInstruction *> invocationId, SpirvInstruction **value,
  1817. bool noWriteBack, SemanticInfo *inheritSemantic) {
  1818. assert(value);
  1819. // invocationId should only be used for handling HS per-vertex output.
  1820. if (invocationId.hasValue()) {
  1821. assert(spvContext.isHS() && arraySize != 0 && !asInput);
  1822. }
  1823. assert(inheritSemantic);
  1824. if (type->isVoidType()) {
  1825. // No stage variables will be created for void type.
  1826. return true;
  1827. }
  1828. // The type the variable is evaluated as for SPIR-V.
  1829. QualType evalType = type;
  1830. // We have several cases regarding HLSL semantics to handle here:
  1831. // * If the currrent decl inherits a semantic from some enclosing entity,
  1832. // use the inherited semantic no matter whether there is a semantic
  1833. // attached to the current decl.
  1834. // * If there is no semantic to inherit,
  1835. // * If the current decl is a struct,
  1836. // * If the current decl has a semantic, all its members inhert this
  1837. // decl's semantic, with the index sequentially increasing;
  1838. // * If the current decl does not have a semantic, all its members
  1839. // should have semantics attached;
  1840. // * If the current decl is not a struct, it should have semantic attached.
  1841. auto thisSemantic = getStageVarSemantic(decl);
  1842. // Which semantic we should use for this decl
  1843. auto *semanticToUse = &thisSemantic;
  1844. // Enclosing semantics override internal ones
  1845. if (inheritSemantic->isValid()) {
  1846. if (thisSemantic.isValid()) {
  1847. emitWarning(
  1848. "internal semantic '%0' overridden by enclosing semantic '%1'",
  1849. thisSemantic.loc)
  1850. << thisSemantic.str << inheritSemantic->str;
  1851. }
  1852. semanticToUse = inheritSemantic;
  1853. }
  1854. const auto loc = decl->getLocation();
  1855. if (semanticToUse->isValid() &&
  1856. // Structs with attached semantics will be handled later.
  1857. !type->isStructureType()) {
  1858. // Found semantic attached directly to this Decl. This means we need to
  1859. // map this decl to a single stage variable.
  1860. if (!validateVKAttributes(decl))
  1861. return false;
  1862. const auto semanticKind = semanticToUse->getKind();
  1863. const auto sigPointKind = sigPoint->GetKind();
  1864. // Error out when the given semantic is invalid in this shader model
  1865. if (hlsl::SigPoint::GetInterpretation(semanticKind, sigPointKind,
  1866. spvContext.getMajorVersion(),
  1867. spvContext.getMinorVersion()) ==
  1868. hlsl::DXIL::SemanticInterpretationKind::NA) {
  1869. // Special handle MSIn/ASIn allowing VK-only builtin "DrawIndex".
  1870. switch (sigPointKind) {
  1871. case hlsl::SigPoint::Kind::MSIn:
  1872. case hlsl::SigPoint::Kind::ASIn:
  1873. if (const auto *builtinAttr = decl->getAttr<VKBuiltInAttr>()) {
  1874. const llvm::StringRef builtin = builtinAttr->getBuiltIn();
  1875. if (builtin == "DrawIndex") {
  1876. break;
  1877. }
  1878. }
  1879. // fall through
  1880. default:
  1881. emitError("invalid usage of semantic '%0' in shader profile %1", loc)
  1882. << semanticToUse->str
  1883. << hlsl::ShaderModel::GetKindName(
  1884. spvContext.getCurrentShaderModelKind());
  1885. return false;
  1886. }
  1887. }
  1888. if (!validateVKBuiltins(decl, sigPoint))
  1889. return false;
  1890. const auto *builtinAttr = decl->getAttr<VKBuiltInAttr>();
  1891. // Special handling of certain mappings between HLSL semantics and
  1892. // SPIR-V builtins:
  1893. // * SV_CullDistance/SV_ClipDistance are outsourced to GlPerVertex.
  1894. // * SV_DomainLocation can refer to a float2, whereas TessCoord is a float3.
  1895. // To ensure SPIR-V validity, we must create a float3 and extract a
  1896. // float2 from it before passing it to the main function.
  1897. // * SV_TessFactor is an array of size 2 for isoline patch, array of size 3
  1898. // for tri patch, and array of size 4 for quad patch, but it must always
  1899. // be an array of size 4 in SPIR-V for Vulkan.
  1900. // * SV_InsideTessFactor is a single float for tri patch, and an array of
  1901. // size 2 for a quad patch, but it must always be an array of size 2 in
  1902. // SPIR-V for Vulkan.
  1903. // * SV_Coverage is an uint value, but the builtin it corresponds to,
  1904. // SampleMask, must be an array of integers.
  1905. // * SV_InnerCoverage is an uint value, but the corresponding builtin,
  1906. // FullyCoveredEXT, must be an boolean value.
  1907. // * SV_DispatchThreadID, SV_GroupThreadID, and SV_GroupID are allowed to be
  1908. // uint, uint2, or uint3, but the corresponding builtins
  1909. // (GlobalInvocationId, LocalInvocationId, WorkgroupId) must be a uint3.
  1910. if (glPerVertex.tryToAccess(sigPointKind, semanticKind,
  1911. semanticToUse->index, invocationId, value,
  1912. noWriteBack, /*vecComponent=*/nullptr, loc))
  1913. return true;
  1914. switch (semanticKind) {
  1915. case hlsl::Semantic::Kind::DomainLocation:
  1916. evalType = astContext.getExtVectorType(astContext.FloatTy, 3);
  1917. break;
  1918. case hlsl::Semantic::Kind::TessFactor:
  1919. evalType = astContext.getConstantArrayType(
  1920. astContext.FloatTy, llvm::APInt(32, 4), clang::ArrayType::Normal, 0);
  1921. break;
  1922. case hlsl::Semantic::Kind::InsideTessFactor:
  1923. evalType = astContext.getConstantArrayType(
  1924. astContext.FloatTy, llvm::APInt(32, 2), clang::ArrayType::Normal, 0);
  1925. break;
  1926. case hlsl::Semantic::Kind::Coverage:
  1927. evalType = astContext.getConstantArrayType(astContext.UnsignedIntTy,
  1928. llvm::APInt(32, 1),
  1929. clang::ArrayType::Normal, 0);
  1930. break;
  1931. case hlsl::Semantic::Kind::InnerCoverage:
  1932. if (!type->isSpecificBuiltinType(BuiltinType::UInt)) {
  1933. emitError("SV_InnerCoverage must be of uint type.", loc);
  1934. return false;
  1935. }
  1936. evalType = astContext.BoolTy;
  1937. break;
  1938. case hlsl::Semantic::Kind::Barycentrics:
  1939. evalType = astContext.getExtVectorType(astContext.FloatTy, 2);
  1940. break;
  1941. case hlsl::Semantic::Kind::DispatchThreadID:
  1942. case hlsl::Semantic::Kind::GroupThreadID:
  1943. case hlsl::Semantic::Kind::GroupID:
  1944. // Keep the original integer signedness
  1945. evalType = astContext.getExtVectorType(
  1946. hlsl::IsHLSLVecType(type) ? hlsl::GetHLSLVecElementType(type) : type,
  1947. 3);
  1948. break;
  1949. default:
  1950. // Only the semantic kinds mentioned above are handled.
  1951. break;
  1952. }
  1953. // Boolean stage I/O variables must be represented as unsigned integers.
  1954. // Boolean built-in variables are represented as bool.
  1955. if (isBooleanStageIOVar(decl, type, semanticKind, sigPointKind)) {
  1956. evalType = getUintTypeWithSourceComponents(astContext, type);
  1957. }
  1958. // Handle the extra arrayness
  1959. if (arraySize != 0) {
  1960. evalType = astContext.getConstantArrayType(
  1961. evalType, llvm::APInt(32, arraySize), clang::ArrayType::Normal, 0);
  1962. }
  1963. StageVar stageVar(
  1964. sigPoint, *semanticToUse, builtinAttr, evalType,
  1965. // For HS/DS/GS, we have already stripped the outmost arrayness on type.
  1966. getLocationCount(astContext, type));
  1967. const auto name = namePrefix.str() + "." + stageVar.getSemanticStr();
  1968. SpirvVariable *varInstr =
  1969. createSpirvStageVar(&stageVar, decl, name, semanticToUse->loc);
  1970. if (!varInstr)
  1971. return false;
  1972. stageVar.setSpirvInstr(varInstr);
  1973. stageVar.setLocationAttr(decl->getAttr<VKLocationAttr>());
  1974. stageVar.setIndexAttr(decl->getAttr<VKIndexAttr>());
  1975. stageVars.push_back(stageVar);
  1976. // Emit OpDecorate* instructions to link this stage variable with the HLSL
  1977. // semantic it is created for
  1978. spvBuilder.decorateHlslSemantic(varInstr, stageVar.getSemanticStr());
  1979. // We have semantics attached to this decl, which means it must be a
  1980. // function/parameter/variable. All are DeclaratorDecls.
  1981. stageVarInstructions[cast<DeclaratorDecl>(decl)] = varInstr;
  1982. // Special case: The DX12 SV_InstanceID always counts from 0, even if the
  1983. // StartInstanceLocation parameter is non-zero. gl_InstanceIndex, however,
  1984. // starts from firstInstance. Thus it doesn't emulate actual DX12 shader
  1985. // behavior. To make it equivalent, SPIR-V codegen should emit:
  1986. // SV_InstanceID = gl_InstanceIndex - gl_BaseInstance
  1987. // Unfortunately, this means that there is no 1-to-1 mapping of the HLSL
  1988. // semantic to the SPIR-V builtin. As a result, we have to manually create
  1989. // a second stage variable for this specific case.
  1990. //
  1991. // According to the Vulkan spec on builtin variables:
  1992. // www.khronos.org/registry/vulkan/specs/1.1-extensions/html/vkspec.html#interfaces-builtin-variables
  1993. //
  1994. // InstanceIndex:
  1995. // Decorating a variable in a vertex shader with the InstanceIndex
  1996. // built-in decoration will make that variable contain the index of the
  1997. // instance that is being processed by the current vertex shader
  1998. // invocation. InstanceIndex begins at the firstInstance.
  1999. // BaseInstance
  2000. // Decorating a variable with the BaseInstance built-in will make that
  2001. // variable contain the integer value corresponding to the first instance
  2002. // that was passed to the command that invoked the current vertex shader
  2003. // invocation. BaseInstance is the firstInstance parameter to a direct
  2004. // drawing command or the firstInstance member of a structure consumed by
  2005. // an indirect drawing command.
  2006. if (spirvOptions.supportNonzeroBaseInstance && asInput &&
  2007. semanticKind == hlsl::Semantic::Kind::InstanceID &&
  2008. sigPointKind == hlsl::SigPoint::Kind::VSIn) {
  2009. // The above call to createSpirvStageVar creates the gl_InstanceIndex.
  2010. // We should now manually create the gl_BaseInstance variable and do the
  2011. // subtraction.
  2012. auto *instanceIndexVar = varInstr;
  2013. auto *baseInstanceVar = spvBuilder.addStageBuiltinVar(
  2014. type, spv::StorageClass::Input, spv::BuiltIn::BaseInstance,
  2015. decl->hasAttr<HLSLPreciseAttr>(), semanticToUse->loc);
  2016. StageVar stageVar2(sigPoint, *semanticToUse, builtinAttr, evalType,
  2017. getLocationCount(astContext, type));
  2018. stageVar2.setSpirvInstr(baseInstanceVar);
  2019. stageVar2.setLocationAttr(decl->getAttr<VKLocationAttr>());
  2020. stageVar2.setIndexAttr(decl->getAttr<VKIndexAttr>());
  2021. stageVar2.setIsSpirvBuiltin();
  2022. stageVars.push_back(stageVar2);
  2023. // SPIR-V code fore 'SV_InstanceID = gl_InstanceIndex - gl_BaseInstance'
  2024. auto *instanceIdVar =
  2025. spvBuilder.addFnVar(type, semanticToUse->loc, "SV_InstanceID");
  2026. auto *instanceIndexValue =
  2027. spvBuilder.createLoad(type, instanceIndexVar, semanticToUse->loc);
  2028. auto *baseInstanceValue =
  2029. spvBuilder.createLoad(type, baseInstanceVar, semanticToUse->loc);
  2030. auto *instanceIdValue =
  2031. spvBuilder.createBinaryOp(spv::Op::OpISub, type, instanceIndexValue,
  2032. baseInstanceValue, semanticToUse->loc);
  2033. spvBuilder.createStore(instanceIdVar, instanceIdValue,
  2034. semanticToUse->loc);
  2035. stageVarInstructions[cast<DeclaratorDecl>(decl)] = instanceIdVar;
  2036. varInstr = instanceIdVar;
  2037. }
  2038. // Mark that we have used one index for this semantic
  2039. ++semanticToUse->index;
  2040. // TODO: the following may not be correct?
  2041. if (sigPoint->GetSignatureKind() ==
  2042. hlsl::DXIL::SignatureKind::PatchConstOrPrim) {
  2043. if (sigPointKind == hlsl::SigPoint::Kind::MSPOut) {
  2044. // Decorate with PerPrimitiveNV for per-primitive out variables.
  2045. spvBuilder.decoratePerPrimitiveNV(varInstr,
  2046. varInstr->getSourceLocation());
  2047. } else {
  2048. spvBuilder.decoratePatch(varInstr, varInstr->getSourceLocation());
  2049. }
  2050. }
  2051. // Decorate with interpolation modes for pixel shader input variables
  2052. // or vertex shader output variables.
  2053. if (((spvContext.isPS() && sigPoint->IsInput()) ||
  2054. (spvContext.isVS() && sigPoint->IsOutput())) &&
  2055. // BaryCoord*AMD buitins already encode the interpolation mode.
  2056. semanticKind != hlsl::Semantic::Kind::Barycentrics)
  2057. decorateInterpolationMode(decl, type, varInstr);
  2058. if (asInput) {
  2059. *value = spvBuilder.createLoad(evalType, varInstr, loc);
  2060. // Fix ups for corner cases
  2061. // Special handling of SV_TessFactor DS patch constant input.
  2062. // TessLevelOuter is always an array of size 4 in SPIR-V, but
  2063. // SV_TessFactor could be an array of size 2, 3, or 4 in HLSL. Only the
  2064. // relevant indexes must be loaded.
  2065. if (semanticKind == hlsl::Semantic::Kind::TessFactor &&
  2066. hlsl::GetArraySize(type) != 4) {
  2067. llvm::SmallVector<SpirvInstruction *, 4> components;
  2068. const auto tessFactorSize = hlsl::GetArraySize(type);
  2069. const auto arrType = astContext.getConstantArrayType(
  2070. astContext.FloatTy, llvm::APInt(32, tessFactorSize),
  2071. clang::ArrayType::Normal, 0);
  2072. for (uint32_t i = 0; i < tessFactorSize; ++i)
  2073. components.push_back(spvBuilder.createCompositeExtract(
  2074. astContext.FloatTy, *value, {i}, thisSemantic.loc));
  2075. *value = spvBuilder.createCompositeConstruct(arrType, components,
  2076. thisSemantic.loc);
  2077. }
  2078. // Special handling of SV_InsideTessFactor DS patch constant input.
  2079. // TessLevelInner is always an array of size 2 in SPIR-V, but
  2080. // SV_InsideTessFactor could be an array of size 1 (scalar) or size 2 in
  2081. // HLSL. If SV_InsideTessFactor is a scalar, only extract index 0 of
  2082. // TessLevelInner.
  2083. else if (semanticKind == hlsl::Semantic::Kind::InsideTessFactor &&
  2084. // Some developers use float[1] instead of a scalar float.
  2085. (!type->isArrayType() || hlsl::GetArraySize(type) == 1)) {
  2086. *value = spvBuilder.createCompositeExtract(astContext.FloatTy, *value,
  2087. {0}, thisSemantic.loc);
  2088. if (type->isArrayType()) { // float[1]
  2089. const auto arrType = astContext.getConstantArrayType(
  2090. astContext.FloatTy, llvm::APInt(32, 1), clang::ArrayType::Normal,
  2091. 0);
  2092. *value = spvBuilder.createCompositeConstruct(arrType, {*value},
  2093. thisSemantic.loc);
  2094. }
  2095. }
  2096. // SV_DomainLocation can refer to a float2 or a float3, whereas TessCoord
  2097. // is always a float3. To ensure SPIR-V validity, a float3 stage variable
  2098. // is created, and we must extract a float2 from it before passing it to
  2099. // the main function.
  2100. else if (semanticKind == hlsl::Semantic::Kind::DomainLocation &&
  2101. hlsl::GetHLSLVecSize(type) != 3) {
  2102. const auto domainLocSize = hlsl::GetHLSLVecSize(type);
  2103. *value = spvBuilder.createVectorShuffle(
  2104. astContext.getExtVectorType(astContext.FloatTy, domainLocSize),
  2105. *value, *value, {0, 1}, thisSemantic.loc);
  2106. }
  2107. // Special handling of SV_Coverage, which is an uint value. We need to
  2108. // read SampleMask and extract its first element.
  2109. else if (semanticKind == hlsl::Semantic::Kind::Coverage) {
  2110. *value = spvBuilder.createCompositeExtract(type, *value, {0},
  2111. thisSemantic.loc);
  2112. }
  2113. // Special handling of SV_InnerCoverage, which is an uint value. We need
  2114. // to read FullyCoveredEXT, which is a boolean value, and convert it to an
  2115. // uint value. According to D3D12 "Conservative Rasterization" doc: "The
  2116. // Pixel Shader has a 32-bit scalar integer System Generate Value
  2117. // available: InnerCoverage. This is a bit-field that has bit 0 from the
  2118. // LSB set to 1 for a given conservatively rasterized pixel, only when
  2119. // that pixel is guaranteed to be entirely inside the current primitive.
  2120. // All other input register bits must be set to 0 when bit 0 is not set,
  2121. // but are undefined when bit 0 is set to 1 (essentially, this bit-field
  2122. // represents a Boolean value where false must be exactly 0, but true can
  2123. // be any odd (i.e. bit 0 set) non-zero value)."
  2124. else if (semanticKind == hlsl::Semantic::Kind::InnerCoverage) {
  2125. const auto constOne = spvBuilder.getConstantInt(
  2126. astContext.UnsignedIntTy, llvm::APInt(32, 1));
  2127. const auto constZero = spvBuilder.getConstantInt(
  2128. astContext.UnsignedIntTy, llvm::APInt(32, 0));
  2129. *value = spvBuilder.createSelect(astContext.UnsignedIntTy, *value,
  2130. constOne, constZero, thisSemantic.loc);
  2131. }
  2132. // Special handling of SV_Barycentrics, which is a float3, but the
  2133. // underlying stage input variable is a float2 (only provides the first
  2134. // two components). Calculate the third element.
  2135. else if (semanticKind == hlsl::Semantic::Kind::Barycentrics) {
  2136. const auto x = spvBuilder.createCompositeExtract(
  2137. astContext.FloatTy, *value, {0}, thisSemantic.loc);
  2138. const auto y = spvBuilder.createCompositeExtract(
  2139. astContext.FloatTy, *value, {1}, thisSemantic.loc);
  2140. const auto xy = spvBuilder.createBinaryOp(
  2141. spv::Op::OpFAdd, astContext.FloatTy, x, y, thisSemantic.loc);
  2142. const auto z = spvBuilder.createBinaryOp(
  2143. spv::Op::OpFSub, astContext.FloatTy,
  2144. spvBuilder.getConstantFloat(astContext.FloatTy,
  2145. llvm::APFloat(1.0f)),
  2146. xy, thisSemantic.loc);
  2147. *value = spvBuilder.createCompositeConstruct(
  2148. astContext.getExtVectorType(astContext.FloatTy, 3), {x, y, z},
  2149. thisSemantic.loc);
  2150. }
  2151. // Special handling of SV_DispatchThreadID and SV_GroupThreadID, which may
  2152. // be a uint or uint2, but the underlying stage input variable is a uint3.
  2153. // The last component(s) should be discarded in needed.
  2154. else if ((semanticKind == hlsl::Semantic::Kind::DispatchThreadID ||
  2155. semanticKind == hlsl::Semantic::Kind::GroupThreadID ||
  2156. semanticKind == hlsl::Semantic::Kind::GroupID) &&
  2157. (!hlsl::IsHLSLVecType(type) ||
  2158. hlsl::GetHLSLVecSize(type) != 3)) {
  2159. const auto srcVecElemType = hlsl::IsHLSLVecType(type)
  2160. ? hlsl::GetHLSLVecElementType(type)
  2161. : type;
  2162. const auto vecSize =
  2163. hlsl::IsHLSLVecType(type) ? hlsl::GetHLSLVecSize(type) : 1;
  2164. if (vecSize == 1)
  2165. *value = spvBuilder.createCompositeExtract(srcVecElemType, *value,
  2166. {0}, thisSemantic.loc);
  2167. else if (vecSize == 2)
  2168. *value = spvBuilder.createVectorShuffle(
  2169. astContext.getExtVectorType(srcVecElemType, 2), *value, *value,
  2170. {0, 1}, thisSemantic.loc);
  2171. }
  2172. // Reciprocate SV_Position.w if requested
  2173. if (semanticKind == hlsl::Semantic::Kind::Position)
  2174. *value = invertWIfRequested(*value, thisSemantic.loc);
  2175. // Since boolean stage input variables are represented as unsigned
  2176. // integers, after loading them, we should cast them to boolean.
  2177. if (isBooleanStageIOVar(decl, type, semanticKind, sigPointKind)) {
  2178. *value =
  2179. theEmitter.castToType(*value, evalType, type, thisSemantic.loc);
  2180. }
  2181. } else {
  2182. if (noWriteBack)
  2183. return true;
  2184. // Negate SV_Position.y if requested
  2185. if (semanticKind == hlsl::Semantic::Kind::Position)
  2186. *value = invertYIfRequested(*value, thisSemantic.loc);
  2187. SpirvInstruction *ptr = varInstr;
  2188. // Special handling of SV_TessFactor HS patch constant output.
  2189. // TessLevelOuter is always an array of size 4 in SPIR-V, but
  2190. // SV_TessFactor could be an array of size 2, 3, or 4 in HLSL. Only the
  2191. // relevant indexes must be written to.
  2192. if (semanticKind == hlsl::Semantic::Kind::TessFactor &&
  2193. hlsl::GetArraySize(type) != 4) {
  2194. const auto tessFactorSize = hlsl::GetArraySize(type);
  2195. for (uint32_t i = 0; i < tessFactorSize; ++i) {
  2196. ptr = spvBuilder.createAccessChain(
  2197. astContext.FloatTy, varInstr,
  2198. {spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  2199. llvm::APInt(32, i))},
  2200. thisSemantic.loc);
  2201. spvBuilder.createStore(
  2202. ptr,
  2203. spvBuilder.createCompositeExtract(astContext.FloatTy, *value, {i},
  2204. thisSemantic.loc),
  2205. thisSemantic.loc);
  2206. }
  2207. }
  2208. // Special handling of SV_InsideTessFactor HS patch constant output.
  2209. // TessLevelInner is always an array of size 2 in SPIR-V, but
  2210. // SV_InsideTessFactor could be an array of size 1 (scalar) or size 2 in
  2211. // HLSL. If SV_InsideTessFactor is a scalar, only write to index 0 of
  2212. // TessLevelInner.
  2213. else if (semanticKind == hlsl::Semantic::Kind::InsideTessFactor &&
  2214. // Some developers use float[1] instead of a scalar float.
  2215. (!type->isArrayType() || hlsl::GetArraySize(type) == 1)) {
  2216. ptr = spvBuilder.createAccessChain(
  2217. astContext.FloatTy, varInstr,
  2218. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  2219. llvm::APInt(32, 0)),
  2220. thisSemantic.loc);
  2221. if (type->isArrayType()) // float[1]
  2222. *value = spvBuilder.createCompositeExtract(astContext.FloatTy, *value,
  2223. {0}, thisSemantic.loc);
  2224. spvBuilder.createStore(ptr, *value, thisSemantic.loc);
  2225. }
  2226. // Special handling of SV_Coverage, which is an unit value. We need to
  2227. // write it to the first element in the SampleMask builtin.
  2228. else if (semanticKind == hlsl::Semantic::Kind::Coverage) {
  2229. ptr = spvBuilder.createAccessChain(
  2230. type, varInstr,
  2231. spvBuilder.getConstantInt(astContext.UnsignedIntTy,
  2232. llvm::APInt(32, 0)),
  2233. thisSemantic.loc);
  2234. ptr->setStorageClass(spv::StorageClass::Output);
  2235. spvBuilder.createStore(ptr, *value, thisSemantic.loc);
  2236. }
  2237. // Special handling of HS ouput, for which we write to only one
  2238. // element in the per-vertex data array: the one indexed by
  2239. // SV_ControlPointID.
  2240. else if (invocationId.hasValue() && invocationId.getValue() != nullptr) {
  2241. // Remove the arrayness to get the element type.
  2242. assert(isa<ConstantArrayType>(evalType));
  2243. const auto elementType =
  2244. astContext.getAsArrayType(evalType)->getElementType();
  2245. auto index = invocationId.getValue();
  2246. ptr = spvBuilder.createAccessChain(elementType, varInstr, index,
  2247. thisSemantic.loc);
  2248. ptr->setStorageClass(spv::StorageClass::Output);
  2249. spvBuilder.createStore(ptr, *value, thisSemantic.loc);
  2250. }
  2251. // Since boolean output stage variables are represented as unsigned
  2252. // integers, we must cast the value to uint before storing.
  2253. else if (isBooleanStageIOVar(decl, type, semanticKind, sigPointKind)) {
  2254. *value =
  2255. theEmitter.castToType(*value, type, evalType, thisSemantic.loc);
  2256. spvBuilder.createStore(ptr, *value, thisSemantic.loc);
  2257. }
  2258. // For all normal cases
  2259. else {
  2260. spvBuilder.createStore(ptr, *value, thisSemantic.loc);
  2261. }
  2262. }
  2263. return true;
  2264. }
  2265. // If the decl itself doesn't have semantic string attached and there is no
  2266. // one to inherit, it should be a struct having all its fields with semantic
  2267. // strings.
  2268. if (!semanticToUse->isValid() && !type->isStructureType()) {
  2269. emitError("semantic string missing for shader %select{output|input}0 "
  2270. "variable '%1'",
  2271. loc)
  2272. << asInput << decl->getName();
  2273. return false;
  2274. }
  2275. const auto *structDecl = type->getAs<RecordType>()->getDecl();
  2276. if (asInput) {
  2277. // If this decl translates into multiple stage input variables, we need to
  2278. // load their values into a composite.
  2279. llvm::SmallVector<SpirvInstruction *, 4> subValues;
  2280. // If we have base classes, we need to handle them first.
  2281. if (const auto *cxxDecl = type->getAsCXXRecordDecl()) {
  2282. for (auto base : cxxDecl->bases()) {
  2283. SpirvInstruction *subValue = nullptr;
  2284. if (!createStageVars(sigPoint, base.getType()->getAsCXXRecordDecl(),
  2285. asInput, base.getType(), arraySize, namePrefix,
  2286. invocationId, &subValue, noWriteBack,
  2287. semanticToUse))
  2288. return false;
  2289. subValues.push_back(subValue);
  2290. }
  2291. }
  2292. for (const auto *field : structDecl->fields()) {
  2293. SpirvInstruction *subValue = nullptr;
  2294. if (!createStageVars(sigPoint, field, asInput, field->getType(),
  2295. arraySize, namePrefix, invocationId, &subValue,
  2296. noWriteBack, semanticToUse))
  2297. return false;
  2298. subValues.push_back(subValue);
  2299. }
  2300. if (arraySize == 0) {
  2301. *value = spvBuilder.createCompositeConstruct(evalType, subValues, loc);
  2302. return true;
  2303. }
  2304. // Handle the extra level of arrayness.
  2305. // We need to return an array of structs. But we get arrays of fields
  2306. // from visiting all fields. So now we need to extract all the elements
  2307. // at the same index of each field arrays and compose a new struct out
  2308. // of them.
  2309. const auto structType = type;
  2310. const auto arrayType = astContext.getConstantArrayType(
  2311. structType, llvm::APInt(32, arraySize), clang::ArrayType::Normal, 0);
  2312. llvm::SmallVector<SpirvInstruction *, 16> arrayElements;
  2313. for (uint32_t arrayIndex = 0; arrayIndex < arraySize; ++arrayIndex) {
  2314. llvm::SmallVector<SpirvInstruction *, 8> fields;
  2315. // If we have base classes, we need to handle them first.
  2316. if (const auto *cxxDecl = type->getAsCXXRecordDecl()) {
  2317. uint32_t baseIndex = 0;
  2318. for (auto base : cxxDecl->bases()) {
  2319. const auto baseType = base.getType();
  2320. fields.push_back(spvBuilder.createCompositeExtract(
  2321. baseType, subValues[baseIndex++], {arrayIndex}, loc));
  2322. }
  2323. }
  2324. // Extract the element at index arrayIndex from each field
  2325. for (const auto *field : structDecl->fields()) {
  2326. const auto fieldType = field->getType();
  2327. fields.push_back(spvBuilder.createCompositeExtract(
  2328. fieldType,
  2329. subValues[getNumBaseClasses(type) + field->getFieldIndex()],
  2330. {arrayIndex}, loc));
  2331. }
  2332. // Compose a new struct out of them
  2333. arrayElements.push_back(
  2334. spvBuilder.createCompositeConstruct(structType, fields, loc));
  2335. }
  2336. *value = spvBuilder.createCompositeConstruct(arrayType, arrayElements, loc);
  2337. } else {
  2338. // If we have base classes, we need to handle them first.
  2339. if (const auto *cxxDecl = type->getAsCXXRecordDecl()) {
  2340. uint32_t baseIndex = 0;
  2341. for (auto base : cxxDecl->bases()) {
  2342. SpirvInstruction *subValue = nullptr;
  2343. if (!noWriteBack)
  2344. subValue = spvBuilder.createCompositeExtract(base.getType(), *value,
  2345. {baseIndex++}, loc);
  2346. if (!createStageVars(sigPoint, base.getType()->getAsCXXRecordDecl(),
  2347. asInput, base.getType(), arraySize, namePrefix,
  2348. invocationId, &subValue, noWriteBack,
  2349. semanticToUse))
  2350. return false;
  2351. }
  2352. }
  2353. // Unlike reading, which may require us to read stand-alone builtins and
  2354. // stage input variables and compose an array of structs out of them,
  2355. // it happens that we don't need to write an array of structs in a bunch
  2356. // for all shader stages:
  2357. //
  2358. // * VS: output is a single struct, without extra arrayness
  2359. // * HS: output is an array of structs, with extra arrayness,
  2360. // but we only write to the struct at the InvocationID index
  2361. // * DS: output is a single struct, without extra arrayness
  2362. // * GS: output is controlled by OpEmitVertex, one vertex per time
  2363. // * MS: output is an array of structs, with extra arrayness
  2364. //
  2365. // The interesting shader stage is HS. We need the InvocationID to write
  2366. // out the value to the correct array element.
  2367. for (const auto *field : structDecl->fields()) {
  2368. const auto fieldType = field->getType();
  2369. SpirvInstruction *subValue = nullptr;
  2370. if (!noWriteBack)
  2371. subValue = spvBuilder.createCompositeExtract(
  2372. fieldType, *value,
  2373. {getNumBaseClasses(type) + field->getFieldIndex()}, loc);
  2374. if (!createStageVars(sigPoint, field, asInput, field->getType(),
  2375. arraySize, namePrefix, invocationId, &subValue,
  2376. noWriteBack, semanticToUse))
  2377. return false;
  2378. }
  2379. }
  2380. return true;
  2381. }
  2382. bool DeclResultIdMapper::createPayloadStageVars(
  2383. const hlsl::SigPoint *sigPoint, spv::StorageClass sc, const NamedDecl *decl,
  2384. bool asInput, QualType type, const llvm::StringRef namePrefix,
  2385. SpirvInstruction **value, uint32_t payloadMemOffset) {
  2386. assert(spvContext.isMS() || spvContext.isAS());
  2387. assert(value);
  2388. if (type->isVoidType()) {
  2389. // No stage variables will be created for void type.
  2390. return true;
  2391. }
  2392. const auto loc = decl->getLocation();
  2393. if (!type->isStructureType()) {
  2394. StageVar stageVar(sigPoint, /*semaInfo=*/{}, /*builtinAttr=*/nullptr, type,
  2395. getLocationCount(astContext, type));
  2396. const auto name = namePrefix.str() + "." + decl->getNameAsString();
  2397. SpirvVariable *varInstr =
  2398. spvBuilder.addStageIOVar(type, sc, name, /*isPrecise=*/false, loc);
  2399. if (!varInstr)
  2400. return false;
  2401. // Even though these as user defined IO stage variables, set them as SPIR-V
  2402. // builtins in order to bypass any semantic string checks and location
  2403. // assignment.
  2404. stageVar.setIsSpirvBuiltin();
  2405. stageVar.setSpirvInstr(varInstr);
  2406. stageVars.push_back(stageVar);
  2407. // Decorate with PerTaskNV for mesh/amplification shader payload variables.
  2408. spvBuilder.decoratePerTaskNV(varInstr, payloadMemOffset,
  2409. varInstr->getSourceLocation());
  2410. if (asInput) {
  2411. *value = spvBuilder.createLoad(type, varInstr, loc);
  2412. } else {
  2413. spvBuilder.createStore(varInstr, *value, loc);
  2414. }
  2415. return true;
  2416. }
  2417. // This decl translates into multiple stage input/output payload variables
  2418. // and we need to load/store these individual member variables.
  2419. const auto *structDecl = type->getAs<RecordType>()->getDecl();
  2420. llvm::SmallVector<SpirvInstruction *, 4> subValues;
  2421. AlignmentSizeCalculator alignmentCalc(astContext, spirvOptions);
  2422. uint32_t nextMemberOffset = 0;
  2423. for (const auto *field : structDecl->fields()) {
  2424. const auto fieldType = field->getType();
  2425. SpirvInstruction *subValue = nullptr;
  2426. uint32_t memberAlignment = 0, memberSize = 0, stride = 0;
  2427. // The next avaiable offset after laying out the previous members.
  2428. std::tie(memberAlignment, memberSize) = alignmentCalc.getAlignmentAndSize(
  2429. field->getType(), spirvOptions.ampPayloadLayoutRule,
  2430. /*isRowMajor*/ llvm::None, &stride);
  2431. alignmentCalc.alignUsingHLSLRelaxedLayout(
  2432. field->getType(), memberSize, memberAlignment, &nextMemberOffset);
  2433. // The vk::offset attribute takes precedence over all.
  2434. if (field->getAttr<VKOffsetAttr>()) {
  2435. nextMemberOffset = field->getAttr<VKOffsetAttr>()->getOffset();
  2436. }
  2437. // Each payload member must have an Offset Decoration.
  2438. payloadMemOffset = nextMemberOffset;
  2439. nextMemberOffset += memberSize;
  2440. if (!asInput) {
  2441. subValue = spvBuilder.createCompositeExtract(
  2442. fieldType, *value, {getNumBaseClasses(type) + field->getFieldIndex()},
  2443. loc);
  2444. }
  2445. if (!createPayloadStageVars(sigPoint, sc, field, asInput, field->getType(),
  2446. namePrefix, &subValue, payloadMemOffset))
  2447. return false;
  2448. if (asInput) {
  2449. subValues.push_back(subValue);
  2450. }
  2451. }
  2452. if (asInput) {
  2453. *value = spvBuilder.createCompositeConstruct(type, subValues, loc);
  2454. }
  2455. return true;
  2456. }
  2457. bool DeclResultIdMapper::writeBackOutputStream(const NamedDecl *decl,
  2458. QualType type,
  2459. SpirvInstruction *value) {
  2460. assert(spvContext.isGS()); // Only for GS use
  2461. if (hlsl::IsHLSLStreamOutputType(type))
  2462. type = hlsl::GetHLSLResourceResultType(type);
  2463. if (hasGSPrimitiveTypeQualifier(decl))
  2464. type = astContext.getAsConstantArrayType(type)->getElementType();
  2465. auto semanticInfo = getStageVarSemantic(decl);
  2466. const auto loc = decl->getLocation();
  2467. if (semanticInfo.isValid()) {
  2468. // Found semantic attached directly to this Decl. Write the value for this
  2469. // Decl to the corresponding stage output variable.
  2470. // Handle SV_ClipDistance, and SV_CullDistance
  2471. if (glPerVertex.tryToAccess(
  2472. hlsl::DXIL::SigPointKind::GSOut, semanticInfo.semantic->GetKind(),
  2473. semanticInfo.index, llvm::None, &value,
  2474. /*noWriteBack=*/false, /*vecComponent=*/nullptr, loc))
  2475. return true;
  2476. // Query the <result-id> for the stage output variable generated out
  2477. // of this decl.
  2478. // We have semantic string attached to this decl; therefore, it must be a
  2479. // DeclaratorDecl.
  2480. const auto found = stageVarInstructions.find(cast<DeclaratorDecl>(decl));
  2481. // We should have recorded its stage output variable previously.
  2482. assert(found != stageVarInstructions.end());
  2483. // Negate SV_Position.y if requested
  2484. if (semanticInfo.semantic->GetKind() == hlsl::Semantic::Kind::Position)
  2485. value = invertYIfRequested(value, loc);
  2486. // Boolean stage output variables are represented as unsigned integers.
  2487. if (isBooleanStageIOVar(decl, type, semanticInfo.semantic->GetKind(),
  2488. hlsl::SigPoint::Kind::GSOut)) {
  2489. QualType uintType = getUintTypeWithSourceComponents(astContext, type);
  2490. value = theEmitter.castToType(value, type, uintType, loc);
  2491. }
  2492. spvBuilder.createStore(found->second, value, loc);
  2493. return true;
  2494. }
  2495. // If the decl itself doesn't have semantic string attached, it should be
  2496. // a struct having all its fields with semantic strings.
  2497. if (!type->isStructureType()) {
  2498. emitError("semantic string missing for shader output variable '%0'", loc)
  2499. << decl->getName();
  2500. return false;
  2501. }
  2502. // If we have base classes, we need to handle them first.
  2503. if (const auto *cxxDecl = type->getAsCXXRecordDecl()) {
  2504. uint32_t baseIndex = 0;
  2505. for (auto base : cxxDecl->bases()) {
  2506. auto *subValue = spvBuilder.createCompositeExtract(base.getType(), value,
  2507. {baseIndex++}, loc);
  2508. if (!writeBackOutputStream(base.getType()->getAsCXXRecordDecl(),
  2509. base.getType(), subValue))
  2510. return false;
  2511. }
  2512. }
  2513. const auto *structDecl = type->getAs<RecordType>()->getDecl();
  2514. // Write out each field
  2515. for (const auto *field : structDecl->fields()) {
  2516. const auto fieldType = field->getType();
  2517. auto *subValue = spvBuilder.createCompositeExtract(
  2518. fieldType, value, {getNumBaseClasses(type) + field->getFieldIndex()},
  2519. loc);
  2520. if (!writeBackOutputStream(field, field->getType(), subValue))
  2521. return false;
  2522. }
  2523. return true;
  2524. }
  2525. SpirvInstruction *
  2526. DeclResultIdMapper::invertYIfRequested(SpirvInstruction *position,
  2527. SourceLocation loc) {
  2528. // Negate SV_Position.y if requested
  2529. if (spirvOptions.invertY) {
  2530. const auto oldY = spvBuilder.createCompositeExtract(astContext.FloatTy,
  2531. position, {1}, loc);
  2532. const auto newY = spvBuilder.createUnaryOp(spv::Op::OpFNegate,
  2533. astContext.FloatTy, oldY, loc);
  2534. position = spvBuilder.createCompositeInsert(
  2535. astContext.getExtVectorType(astContext.FloatTy, 4), position, {1}, newY,
  2536. loc);
  2537. }
  2538. return position;
  2539. }
  2540. SpirvInstruction *
  2541. DeclResultIdMapper::invertWIfRequested(SpirvInstruction *position,
  2542. SourceLocation loc) {
  2543. // Reciprocate SV_Position.w if requested
  2544. if (spirvOptions.invertW && spvContext.isPS()) {
  2545. const auto oldW = spvBuilder.createCompositeExtract(astContext.FloatTy,
  2546. position, {3}, loc);
  2547. const auto newW = spvBuilder.createBinaryOp(
  2548. spv::Op::OpFDiv, astContext.FloatTy,
  2549. spvBuilder.getConstantFloat(astContext.FloatTy, llvm::APFloat(1.0f)),
  2550. oldW, loc);
  2551. position = spvBuilder.createCompositeInsert(
  2552. astContext.getExtVectorType(astContext.FloatTy, 4), position, {3}, newW,
  2553. loc);
  2554. }
  2555. return position;
  2556. }
  2557. void DeclResultIdMapper::decorateInterpolationMode(const NamedDecl *decl,
  2558. QualType type,
  2559. SpirvVariable *varInstr) {
  2560. const auto loc = decl->getLocation();
  2561. if (isUintOrVecMatOfUintType(type) || isSintOrVecMatOfSintType(type) ||
  2562. isBoolOrVecMatOfBoolType(type)) {
  2563. // TODO: Probably we can call hlsl::ValidateSignatureElement() for the
  2564. // following check.
  2565. if (decl->getAttr<HLSLLinearAttr>() || decl->getAttr<HLSLCentroidAttr>() ||
  2566. decl->getAttr<HLSLNoPerspectiveAttr>() ||
  2567. decl->getAttr<HLSLSampleAttr>()) {
  2568. emitError("only nointerpolation mode allowed for integer input "
  2569. "parameters in pixel shader or integer output in vertex shader",
  2570. decl->getLocation());
  2571. } else {
  2572. spvBuilder.decorateFlat(varInstr, loc);
  2573. }
  2574. } else {
  2575. // Do nothing for HLSLLinearAttr since its the default
  2576. // Attributes can be used together. So cannot use else if.
  2577. if (decl->getAttr<HLSLCentroidAttr>())
  2578. spvBuilder.decorateCentroid(varInstr, loc);
  2579. if (decl->getAttr<HLSLNoInterpolationAttr>())
  2580. spvBuilder.decorateFlat(varInstr, loc);
  2581. if (decl->getAttr<HLSLNoPerspectiveAttr>())
  2582. spvBuilder.decorateNoPerspective(varInstr, loc);
  2583. if (decl->getAttr<HLSLSampleAttr>()) {
  2584. spvBuilder.decorateSample(varInstr, loc);
  2585. }
  2586. }
  2587. }
  2588. SpirvVariable *DeclResultIdMapper::getBuiltinVar(spv::BuiltIn builtIn,
  2589. QualType type,
  2590. SourceLocation loc) {
  2591. // Guarantee uniqueness
  2592. uint32_t spvBuiltinId = static_cast<uint32_t>(builtIn);
  2593. const auto builtInVar = builtinToVarMap.find(spvBuiltinId);
  2594. if (builtInVar != builtinToVarMap.end()) {
  2595. return builtInVar->second;
  2596. }
  2597. spv::StorageClass sc = spv::StorageClass::Max;
  2598. // Valid builtins supported
  2599. switch (builtIn) {
  2600. case spv::BuiltIn::SubgroupSize:
  2601. case spv::BuiltIn::SubgroupLocalInvocationId:
  2602. case spv::BuiltIn::HitTNV:
  2603. case spv::BuiltIn::RayTmaxNV:
  2604. case spv::BuiltIn::RayTminNV:
  2605. case spv::BuiltIn::HitKindNV:
  2606. case spv::BuiltIn::IncomingRayFlagsNV:
  2607. case spv::BuiltIn::InstanceCustomIndexNV:
  2608. case spv::BuiltIn::RayGeometryIndexKHR:
  2609. case spv::BuiltIn::PrimitiveId:
  2610. case spv::BuiltIn::InstanceId:
  2611. case spv::BuiltIn::WorldRayDirectionNV:
  2612. case spv::BuiltIn::WorldRayOriginNV:
  2613. case spv::BuiltIn::ObjectRayDirectionNV:
  2614. case spv::BuiltIn::ObjectRayOriginNV:
  2615. case spv::BuiltIn::ObjectToWorldNV:
  2616. case spv::BuiltIn::WorldToObjectNV:
  2617. case spv::BuiltIn::LaunchIdNV:
  2618. case spv::BuiltIn::LaunchSizeNV:
  2619. case spv::BuiltIn::GlobalInvocationId:
  2620. case spv::BuiltIn::WorkgroupId:
  2621. case spv::BuiltIn::LocalInvocationIndex:
  2622. sc = spv::StorageClass::Input;
  2623. break;
  2624. case spv::BuiltIn::PrimitiveCountNV:
  2625. case spv::BuiltIn::PrimitiveIndicesNV:
  2626. case spv::BuiltIn::TaskCountNV:
  2627. sc = spv::StorageClass::Output;
  2628. break;
  2629. default:
  2630. assert(false && "unsupported SPIR-V builtin");
  2631. return nullptr;
  2632. }
  2633. // Create a dummy StageVar for this builtin variable
  2634. auto var = spvBuilder.addStageBuiltinVar(type, sc, builtIn,
  2635. /*isPrecise*/ false, loc);
  2636. const hlsl::SigPoint *sigPoint =
  2637. hlsl::SigPoint::GetSigPoint(hlsl::SigPointFromInputQual(
  2638. hlsl::DxilParamInputQual::In, spvContext.getCurrentShaderModelKind(),
  2639. /*isPatchConstant=*/false));
  2640. StageVar stageVar(sigPoint, /*semaInfo=*/{}, /*builtinAttr=*/nullptr, type,
  2641. /*locCount=*/0);
  2642. stageVar.setIsSpirvBuiltin();
  2643. stageVar.setSpirvInstr(var);
  2644. stageVars.push_back(stageVar);
  2645. // Store in map for re-use
  2646. builtinToVarMap[spvBuiltinId] = var;
  2647. return var;
  2648. }
  2649. SpirvVariable *DeclResultIdMapper::createSpirvIntermediateOutputStageVar(
  2650. const NamedDecl *decl, const llvm::StringRef name, QualType type) {
  2651. const auto *semantic = hlsl::Semantic::GetByName(name);
  2652. SemanticInfo thisSemantic{name, semantic, name, 0, decl->getLocation()};
  2653. const auto *sigPoint =
  2654. deduceSigPoint(cast<DeclaratorDecl>(decl), /*asInput=*/false,
  2655. spvContext.getCurrentShaderModelKind(), /*forPCF=*/false);
  2656. StageVar stageVar(sigPoint, thisSemantic, decl->getAttr<VKBuiltInAttr>(),
  2657. type, /*locCount=*/1);
  2658. SpirvVariable *varInstr =
  2659. createSpirvStageVar(&stageVar, decl, name, thisSemantic.loc);
  2660. if (!varInstr)
  2661. return nullptr;
  2662. stageVar.setSpirvInstr(varInstr);
  2663. stageVar.setLocationAttr(decl->getAttr<VKLocationAttr>());
  2664. stageVar.setIndexAttr(decl->getAttr<VKIndexAttr>());
  2665. stageVars.push_back(stageVar);
  2666. // Emit OpDecorate* instructions to link this stage variable with the HLSL
  2667. // semantic it is created for.
  2668. spvBuilder.decorateHlslSemantic(varInstr, stageVar.getSemanticStr());
  2669. // We have semantics attached to this decl, which means it must be a
  2670. // function/parameter/variable. All are DeclaratorDecls.
  2671. stageVarInstructions[cast<DeclaratorDecl>(decl)] = varInstr;
  2672. return varInstr;
  2673. }
  2674. SpirvVariable *DeclResultIdMapper::createSpirvStageVar(
  2675. StageVar *stageVar, const NamedDecl *decl, const llvm::StringRef name,
  2676. SourceLocation srcLoc) {
  2677. using spv::BuiltIn;
  2678. const auto sigPoint = stageVar->getSigPoint();
  2679. const auto semanticKind = stageVar->getSemanticInfo().getKind();
  2680. const auto sigPointKind = sigPoint->GetKind();
  2681. const auto type = stageVar->getAstType();
  2682. const auto isPrecise = decl->hasAttr<HLSLPreciseAttr>();
  2683. spv::StorageClass sc = getStorageClassForSigPoint(sigPoint);
  2684. if (sc == spv::StorageClass::Max)
  2685. return 0;
  2686. stageVar->setStorageClass(sc);
  2687. // [[vk::builtin(...)]] takes precedence.
  2688. if (const auto *builtinAttr = stageVar->getBuiltInAttr()) {
  2689. const auto spvBuiltIn =
  2690. llvm::StringSwitch<BuiltIn>(builtinAttr->getBuiltIn())
  2691. .Case("PointSize", BuiltIn::PointSize)
  2692. .Case("HelperInvocation", BuiltIn::HelperInvocation)
  2693. .Case("BaseVertex", BuiltIn::BaseVertex)
  2694. .Case("BaseInstance", BuiltIn::BaseInstance)
  2695. .Case("DrawIndex", BuiltIn::DrawIndex)
  2696. .Case("DeviceIndex", BuiltIn::DeviceIndex)
  2697. .Case("ViewportMaskNV", BuiltIn::ViewportMaskNV)
  2698. .Default(BuiltIn::Max);
  2699. assert(spvBuiltIn != BuiltIn::Max); // The frontend should guarantee this.
  2700. return spvBuilder.addStageBuiltinVar(type, sc, spvBuiltIn, isPrecise,
  2701. srcLoc);
  2702. }
  2703. // The following translation assumes that semantic validity in the current
  2704. // shader model is already checked, so it only covers valid SigPoints for
  2705. // each semantic.
  2706. switch (semanticKind) {
  2707. // According to DXIL spec, the Position SV can be used by all SigPoints
  2708. // other than PCIn, HSIn, GSIn, PSOut, CSIn, MSIn, MSPOut, ASIn.
  2709. // According to Vulkan spec, the Position BuiltIn can only be used
  2710. // by VSOut, HS/DS/GS In/Out, MSOut.
  2711. case hlsl::Semantic::Kind::Position: {
  2712. switch (sigPointKind) {
  2713. case hlsl::SigPoint::Kind::VSIn:
  2714. case hlsl::SigPoint::Kind::PCOut:
  2715. case hlsl::SigPoint::Kind::DSIn:
  2716. return spvBuilder.addStageIOVar(type, sc, name.str(), isPrecise, srcLoc);
  2717. case hlsl::SigPoint::Kind::VSOut:
  2718. case hlsl::SigPoint::Kind::HSCPIn:
  2719. case hlsl::SigPoint::Kind::HSCPOut:
  2720. case hlsl::SigPoint::Kind::DSCPIn:
  2721. case hlsl::SigPoint::Kind::DSOut:
  2722. case hlsl::SigPoint::Kind::GSVIn:
  2723. case hlsl::SigPoint::Kind::GSOut:
  2724. case hlsl::SigPoint::Kind::MSOut:
  2725. stageVar->setIsSpirvBuiltin();
  2726. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::Position,
  2727. isPrecise, srcLoc);
  2728. case hlsl::SigPoint::Kind::PSIn:
  2729. stageVar->setIsSpirvBuiltin();
  2730. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::FragCoord,
  2731. isPrecise, srcLoc);
  2732. default:
  2733. llvm_unreachable("invalid usage of SV_Position sneaked in");
  2734. }
  2735. }
  2736. // According to DXIL spec, the VertexID SV can only be used by VSIn.
  2737. // According to Vulkan spec, the VertexIndex BuiltIn can only be used by
  2738. // VSIn.
  2739. case hlsl::Semantic::Kind::VertexID: {
  2740. stageVar->setIsSpirvBuiltin();
  2741. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::VertexIndex,
  2742. isPrecise, srcLoc);
  2743. }
  2744. // According to DXIL spec, the InstanceID SV can be used by VSIn, VSOut,
  2745. // HSCPIn, HSCPOut, DSCPIn, DSOut, GSVIn, GSOut, PSIn.
  2746. // According to Vulkan spec, the InstanceIndex BuitIn can only be used by
  2747. // VSIn.
  2748. case hlsl::Semantic::Kind::InstanceID: {
  2749. switch (sigPointKind) {
  2750. case hlsl::SigPoint::Kind::VSIn:
  2751. stageVar->setIsSpirvBuiltin();
  2752. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::InstanceIndex,
  2753. isPrecise, srcLoc);
  2754. case hlsl::SigPoint::Kind::VSOut:
  2755. case hlsl::SigPoint::Kind::HSCPIn:
  2756. case hlsl::SigPoint::Kind::HSCPOut:
  2757. case hlsl::SigPoint::Kind::DSCPIn:
  2758. case hlsl::SigPoint::Kind::DSOut:
  2759. case hlsl::SigPoint::Kind::GSVIn:
  2760. case hlsl::SigPoint::Kind::GSOut:
  2761. case hlsl::SigPoint::Kind::PSIn:
  2762. return spvBuilder.addStageIOVar(type, sc, name.str(), isPrecise, srcLoc);
  2763. default:
  2764. llvm_unreachable("invalid usage of SV_InstanceID sneaked in");
  2765. }
  2766. }
  2767. // According to DXIL spec, the Depth{|GreaterEqual|LessEqual} SV can only be
  2768. // used by PSOut.
  2769. // According to Vulkan spec, the FragDepth BuiltIn can only be used by PSOut.
  2770. case hlsl::Semantic::Kind::Depth:
  2771. case hlsl::Semantic::Kind::DepthGreaterEqual:
  2772. case hlsl::Semantic::Kind::DepthLessEqual: {
  2773. stageVar->setIsSpirvBuiltin();
  2774. // Vulkan requires the DepthReplacing execution mode to write to FragDepth.
  2775. spvBuilder.addExecutionMode(entryFunction,
  2776. spv::ExecutionMode::DepthReplacing, {}, srcLoc);
  2777. if (semanticKind == hlsl::Semantic::Kind::DepthGreaterEqual)
  2778. spvBuilder.addExecutionMode(entryFunction,
  2779. spv::ExecutionMode::DepthGreater, {}, srcLoc);
  2780. else if (semanticKind == hlsl::Semantic::Kind::DepthLessEqual)
  2781. spvBuilder.addExecutionMode(entryFunction, spv::ExecutionMode::DepthLess,
  2782. {}, srcLoc);
  2783. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::FragDepth,
  2784. isPrecise, srcLoc);
  2785. }
  2786. // According to DXIL spec, the ClipDistance/CullDistance SV can be used by all
  2787. // SigPoints other than PCIn, HSIn, GSIn, PSOut, CSIn, MSIn, MSPOut, ASIn.
  2788. // According to Vulkan spec, the ClipDistance/CullDistance
  2789. // BuiltIn can only be used by VSOut, HS/DS/GS In/Out, MSOut.
  2790. case hlsl::Semantic::Kind::ClipDistance:
  2791. case hlsl::Semantic::Kind::CullDistance: {
  2792. switch (sigPointKind) {
  2793. case hlsl::SigPoint::Kind::VSIn:
  2794. case hlsl::SigPoint::Kind::PCOut:
  2795. case hlsl::SigPoint::Kind::DSIn:
  2796. return spvBuilder.addStageIOVar(type, sc, name.str(), isPrecise, srcLoc);
  2797. case hlsl::SigPoint::Kind::VSOut:
  2798. case hlsl::SigPoint::Kind::HSCPIn:
  2799. case hlsl::SigPoint::Kind::HSCPOut:
  2800. case hlsl::SigPoint::Kind::DSCPIn:
  2801. case hlsl::SigPoint::Kind::DSOut:
  2802. case hlsl::SigPoint::Kind::GSVIn:
  2803. case hlsl::SigPoint::Kind::GSOut:
  2804. case hlsl::SigPoint::Kind::PSIn:
  2805. case hlsl::SigPoint::Kind::MSOut:
  2806. llvm_unreachable("should be handled in gl_PerVertex struct");
  2807. default:
  2808. llvm_unreachable(
  2809. "invalid usage of SV_ClipDistance/SV_CullDistance sneaked in");
  2810. }
  2811. }
  2812. // According to DXIL spec, the IsFrontFace SV can only be used by GSOut and
  2813. // PSIn.
  2814. // According to Vulkan spec, the FrontFacing BuitIn can only be used in PSIn.
  2815. case hlsl::Semantic::Kind::IsFrontFace: {
  2816. switch (sigPointKind) {
  2817. case hlsl::SigPoint::Kind::GSOut:
  2818. return spvBuilder.addStageIOVar(type, sc, name.str(), isPrecise, srcLoc);
  2819. case hlsl::SigPoint::Kind::PSIn:
  2820. stageVar->setIsSpirvBuiltin();
  2821. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::FrontFacing,
  2822. isPrecise, srcLoc);
  2823. default:
  2824. llvm_unreachable("invalid usage of SV_IsFrontFace sneaked in");
  2825. }
  2826. }
  2827. // According to DXIL spec, the Target SV can only be used by PSOut.
  2828. // There is no corresponding builtin decoration in SPIR-V. So generate normal
  2829. // Vulkan stage input/output variables.
  2830. case hlsl::Semantic::Kind::Target:
  2831. // An arbitrary semantic is defined by users. Generate normal Vulkan stage
  2832. // input/output variables.
  2833. case hlsl::Semantic::Kind::Arbitrary: {
  2834. return spvBuilder.addStageIOVar(type, sc, name.str(), isPrecise, srcLoc);
  2835. // TODO: patch constant function in hull shader
  2836. }
  2837. // According to DXIL spec, the DispatchThreadID SV can only be used by CSIn.
  2838. // According to Vulkan spec, the GlobalInvocationId can only be used in CSIn.
  2839. case hlsl::Semantic::Kind::DispatchThreadID: {
  2840. stageVar->setIsSpirvBuiltin();
  2841. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::GlobalInvocationId,
  2842. isPrecise, srcLoc);
  2843. }
  2844. // According to DXIL spec, the GroupID SV can only be used by CSIn.
  2845. // According to Vulkan spec, the WorkgroupId can only be used in CSIn.
  2846. case hlsl::Semantic::Kind::GroupID: {
  2847. stageVar->setIsSpirvBuiltin();
  2848. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::WorkgroupId,
  2849. isPrecise, srcLoc);
  2850. }
  2851. // According to DXIL spec, the GroupThreadID SV can only be used by CSIn.
  2852. // According to Vulkan spec, the LocalInvocationId can only be used in CSIn.
  2853. case hlsl::Semantic::Kind::GroupThreadID: {
  2854. stageVar->setIsSpirvBuiltin();
  2855. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::LocalInvocationId,
  2856. isPrecise, srcLoc);
  2857. }
  2858. // According to DXIL spec, the GroupIndex SV can only be used by CSIn.
  2859. // According to Vulkan spec, the LocalInvocationIndex can only be used in
  2860. // CSIn.
  2861. case hlsl::Semantic::Kind::GroupIndex: {
  2862. stageVar->setIsSpirvBuiltin();
  2863. return spvBuilder.addStageBuiltinVar(
  2864. type, sc, BuiltIn::LocalInvocationIndex, isPrecise, srcLoc);
  2865. }
  2866. // According to DXIL spec, the OutputControlID SV can only be used by HSIn.
  2867. // According to Vulkan spec, the InvocationId BuiltIn can only be used in
  2868. // HS/GS In.
  2869. case hlsl::Semantic::Kind::OutputControlPointID: {
  2870. stageVar->setIsSpirvBuiltin();
  2871. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::InvocationId,
  2872. isPrecise, srcLoc);
  2873. }
  2874. // According to DXIL spec, the PrimitiveID SV can only be used by PCIn, HSIn,
  2875. // DSIn, GSIn, GSOut, PSIn, and MSPOut.
  2876. // According to Vulkan spec, the PrimitiveId BuiltIn can only be used in
  2877. // HS/DS/PS In, GS In/Out, MSPOut.
  2878. case hlsl::Semantic::Kind::PrimitiveID: {
  2879. // Translate to PrimitiveId BuiltIn for all valid SigPoints.
  2880. stageVar->setIsSpirvBuiltin();
  2881. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::PrimitiveId,
  2882. isPrecise, srcLoc);
  2883. }
  2884. // According to DXIL spec, the TessFactor SV can only be used by PCOut and
  2885. // DSIn.
  2886. // According to Vulkan spec, the TessLevelOuter BuiltIn can only be used in
  2887. // PCOut and DSIn.
  2888. case hlsl::Semantic::Kind::TessFactor: {
  2889. stageVar->setIsSpirvBuiltin();
  2890. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::TessLevelOuter,
  2891. isPrecise, srcLoc);
  2892. }
  2893. // According to DXIL spec, the InsideTessFactor SV can only be used by PCOut
  2894. // and DSIn.
  2895. // According to Vulkan spec, the TessLevelInner BuiltIn can only be used in
  2896. // PCOut and DSIn.
  2897. case hlsl::Semantic::Kind::InsideTessFactor: {
  2898. stageVar->setIsSpirvBuiltin();
  2899. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::TessLevelInner,
  2900. isPrecise, srcLoc);
  2901. }
  2902. // According to DXIL spec, the DomainLocation SV can only be used by DSIn.
  2903. // According to Vulkan spec, the TessCoord BuiltIn can only be used in DSIn.
  2904. case hlsl::Semantic::Kind::DomainLocation: {
  2905. stageVar->setIsSpirvBuiltin();
  2906. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::TessCoord,
  2907. isPrecise, srcLoc);
  2908. }
  2909. // According to DXIL spec, the GSInstanceID SV can only be used by GSIn.
  2910. // According to Vulkan spec, the InvocationId BuiltIn can only be used in
  2911. // HS/GS In.
  2912. case hlsl::Semantic::Kind::GSInstanceID: {
  2913. stageVar->setIsSpirvBuiltin();
  2914. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::InvocationId,
  2915. isPrecise, srcLoc);
  2916. }
  2917. // According to DXIL spec, the SampleIndex SV can only be used by PSIn.
  2918. // According to Vulkan spec, the SampleId BuiltIn can only be used in PSIn.
  2919. case hlsl::Semantic::Kind::SampleIndex: {
  2920. stageVar->setIsSpirvBuiltin();
  2921. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::SampleId, isPrecise,
  2922. srcLoc);
  2923. }
  2924. // According to DXIL spec, the StencilRef SV can only be used by PSOut.
  2925. case hlsl::Semantic::Kind::StencilRef: {
  2926. stageVar->setIsSpirvBuiltin();
  2927. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::FragStencilRefEXT,
  2928. isPrecise, srcLoc);
  2929. }
  2930. // According to DXIL spec, the Barycentrics SV can only be used by PSIn.
  2931. case hlsl::Semantic::Kind::Barycentrics: {
  2932. stageVar->setIsSpirvBuiltin();
  2933. // Selecting the correct builtin according to interpolation mode
  2934. auto bi = BuiltIn::Max;
  2935. if (decl->hasAttr<HLSLNoPerspectiveAttr>()) {
  2936. if (decl->hasAttr<HLSLCentroidAttr>()) {
  2937. bi = BuiltIn::BaryCoordNoPerspCentroidAMD;
  2938. } else if (decl->hasAttr<HLSLSampleAttr>()) {
  2939. bi = BuiltIn::BaryCoordNoPerspSampleAMD;
  2940. } else {
  2941. bi = BuiltIn::BaryCoordNoPerspAMD;
  2942. }
  2943. } else {
  2944. if (decl->hasAttr<HLSLCentroidAttr>()) {
  2945. bi = BuiltIn::BaryCoordSmoothCentroidAMD;
  2946. } else if (decl->hasAttr<HLSLSampleAttr>()) {
  2947. bi = BuiltIn::BaryCoordSmoothSampleAMD;
  2948. } else {
  2949. bi = BuiltIn::BaryCoordSmoothAMD;
  2950. }
  2951. }
  2952. return spvBuilder.addStageBuiltinVar(type, sc, bi, isPrecise, srcLoc);
  2953. }
  2954. // According to DXIL spec, the RenderTargetArrayIndex SV can only be used by
  2955. // VSIn, VSOut, HSCPIn, HSCPOut, DSIn, DSOut, GSVIn, GSOut, PSIn, MSPOut.
  2956. // According to Vulkan spec, the Layer BuiltIn can only be used in GSOut
  2957. // PSIn, and MSPOut.
  2958. case hlsl::Semantic::Kind::RenderTargetArrayIndex: {
  2959. switch (sigPointKind) {
  2960. case hlsl::SigPoint::Kind::VSIn:
  2961. case hlsl::SigPoint::Kind::HSCPIn:
  2962. case hlsl::SigPoint::Kind::HSCPOut:
  2963. case hlsl::SigPoint::Kind::PCOut:
  2964. case hlsl::SigPoint::Kind::DSIn:
  2965. case hlsl::SigPoint::Kind::DSCPIn:
  2966. case hlsl::SigPoint::Kind::GSVIn:
  2967. return spvBuilder.addStageIOVar(type, sc, name.str(), isPrecise, srcLoc);
  2968. case hlsl::SigPoint::Kind::VSOut:
  2969. case hlsl::SigPoint::Kind::DSOut:
  2970. stageVar->setIsSpirvBuiltin();
  2971. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::Layer, isPrecise,
  2972. srcLoc);
  2973. case hlsl::SigPoint::Kind::GSOut:
  2974. case hlsl::SigPoint::Kind::PSIn:
  2975. case hlsl::SigPoint::Kind::MSPOut:
  2976. stageVar->setIsSpirvBuiltin();
  2977. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::Layer, isPrecise,
  2978. srcLoc);
  2979. default:
  2980. llvm_unreachable("invalid usage of SV_RenderTargetArrayIndex sneaked in");
  2981. }
  2982. }
  2983. // According to DXIL spec, the ViewportArrayIndex SV can only be used by
  2984. // VSIn, VSOut, HSCPIn, HSCPOut, DSIn, DSOut, GSVIn, GSOut, PSIn, MSPOut.
  2985. // According to Vulkan spec, the ViewportIndex BuiltIn can only be used in
  2986. // GSOut, PSIn, and MSPOut.
  2987. case hlsl::Semantic::Kind::ViewPortArrayIndex: {
  2988. switch (sigPointKind) {
  2989. case hlsl::SigPoint::Kind::VSIn:
  2990. case hlsl::SigPoint::Kind::HSCPIn:
  2991. case hlsl::SigPoint::Kind::HSCPOut:
  2992. case hlsl::SigPoint::Kind::PCOut:
  2993. case hlsl::SigPoint::Kind::DSIn:
  2994. case hlsl::SigPoint::Kind::DSCPIn:
  2995. case hlsl::SigPoint::Kind::GSVIn:
  2996. return spvBuilder.addStageIOVar(type, sc, name.str(), isPrecise, srcLoc);
  2997. case hlsl::SigPoint::Kind::VSOut:
  2998. case hlsl::SigPoint::Kind::DSOut:
  2999. stageVar->setIsSpirvBuiltin();
  3000. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::ViewportIndex,
  3001. isPrecise, srcLoc);
  3002. case hlsl::SigPoint::Kind::GSOut:
  3003. case hlsl::SigPoint::Kind::PSIn:
  3004. case hlsl::SigPoint::Kind::MSPOut:
  3005. stageVar->setIsSpirvBuiltin();
  3006. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::ViewportIndex,
  3007. isPrecise, srcLoc);
  3008. default:
  3009. llvm_unreachable("invalid usage of SV_ViewportArrayIndex sneaked in");
  3010. }
  3011. }
  3012. // According to DXIL spec, the Coverage SV can only be used by PSIn and PSOut.
  3013. // According to Vulkan spec, the SampleMask BuiltIn can only be used in
  3014. // PSIn and PSOut.
  3015. case hlsl::Semantic::Kind::Coverage: {
  3016. stageVar->setIsSpirvBuiltin();
  3017. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::SampleMask,
  3018. isPrecise, srcLoc);
  3019. }
  3020. // According to DXIL spec, the ViewID SV can only be used by VSIn, PCIn,
  3021. // HSIn, DSIn, GSIn, PSIn.
  3022. // According to Vulkan spec, the ViewIndex BuiltIn can only be used in
  3023. // VS/HS/DS/GS/PS input.
  3024. case hlsl::Semantic::Kind::ViewID: {
  3025. stageVar->setIsSpirvBuiltin();
  3026. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::ViewIndex,
  3027. isPrecise, srcLoc);
  3028. }
  3029. // According to DXIL spec, the InnerCoverage SV can only be used as PSIn.
  3030. // According to Vulkan spec, the FullyCoveredEXT BuiltIn can only be used as
  3031. // PSIn.
  3032. case hlsl::Semantic::Kind::InnerCoverage: {
  3033. stageVar->setIsSpirvBuiltin();
  3034. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::FullyCoveredEXT,
  3035. isPrecise, srcLoc);
  3036. }
  3037. // According to DXIL spec, the ShadingRate SV can only be used by GSOut,
  3038. // VSOut, or PSIn. According to Vulkan spec, the FragSizeEXT BuiltIn can only
  3039. // be used as VSOut, GSOut, MSOut or PSIn.
  3040. case hlsl::Semantic::Kind::ShadingRate: {
  3041. QualType checkType = type->getAs<ReferenceType>()
  3042. ? type->getAs<ReferenceType>()->getPointeeType()
  3043. : type;
  3044. QualType scalarTy;
  3045. if (!isScalarType(checkType, &scalarTy) || !scalarTy->isIntegerType()) {
  3046. emitError("semantic ShadingRate must be interger scalar type", srcLoc);
  3047. }
  3048. switch (sigPointKind) {
  3049. case hlsl::SigPoint::Kind::PSIn:
  3050. stageVar->setIsSpirvBuiltin();
  3051. return spvBuilder.addStageBuiltinVar(type, sc, BuiltIn::ShadingRateKHR,
  3052. isPrecise, srcLoc);
  3053. case hlsl::SigPoint::Kind::VSOut:
  3054. case hlsl::SigPoint::Kind::GSOut:
  3055. case hlsl::SigPoint::Kind::MSOut:
  3056. stageVar->setIsSpirvBuiltin();
  3057. return spvBuilder.addStageBuiltinVar(
  3058. type, sc, BuiltIn::PrimitiveShadingRateKHR, isPrecise, srcLoc);
  3059. default:
  3060. emitError("semantic ShadingRate must be used only for PSIn, VSOut, "
  3061. "GSOut, MSOut",
  3062. srcLoc);
  3063. break;
  3064. }
  3065. break;
  3066. }
  3067. default:
  3068. emitError("semantic %0 unimplemented", srcLoc)
  3069. << stageVar->getSemanticStr();
  3070. break;
  3071. }
  3072. return 0;
  3073. }
  3074. bool DeclResultIdMapper::validateVKAttributes(const NamedDecl *decl) {
  3075. bool success = true;
  3076. if (const auto *idxAttr = decl->getAttr<VKIndexAttr>()) {
  3077. if (!spvContext.isPS()) {
  3078. emitError("vk::index only allowed in pixel shader",
  3079. idxAttr->getLocation());
  3080. success = false;
  3081. }
  3082. const auto *locAttr = decl->getAttr<VKLocationAttr>();
  3083. if (!locAttr) {
  3084. emitError("vk::index should be used together with vk::location for "
  3085. "dual-source blending",
  3086. idxAttr->getLocation());
  3087. success = false;
  3088. } else {
  3089. const auto locNumber = locAttr->getNumber();
  3090. if (locNumber != 0) {
  3091. emitError("dual-source blending should use vk::location 0",
  3092. locAttr->getLocation());
  3093. success = false;
  3094. }
  3095. }
  3096. const auto idxNumber = idxAttr->getNumber();
  3097. if (idxNumber != 0 && idxNumber != 1) {
  3098. emitError("dual-source blending only accepts 0 or 1 as vk::index",
  3099. idxAttr->getLocation());
  3100. success = false;
  3101. }
  3102. }
  3103. return success;
  3104. }
  3105. bool DeclResultIdMapper::validateVKBuiltins(const NamedDecl *decl,
  3106. const hlsl::SigPoint *sigPoint) {
  3107. bool success = true;
  3108. if (const auto *builtinAttr = decl->getAttr<VKBuiltInAttr>()) {
  3109. // The front end parsing only allows vk::builtin to be attached to a
  3110. // function/parameter/variable; all of them are DeclaratorDecls.
  3111. const auto declType = getTypeOrFnRetType(cast<DeclaratorDecl>(decl));
  3112. const auto loc = builtinAttr->getLocation();
  3113. if (decl->hasAttr<VKLocationAttr>()) {
  3114. emitError("cannot use vk::builtin and vk::location together", loc);
  3115. success = false;
  3116. }
  3117. const llvm::StringRef builtin = builtinAttr->getBuiltIn();
  3118. if (builtin == "HelperInvocation") {
  3119. if (!declType->isBooleanType()) {
  3120. emitError("HelperInvocation builtin must be of boolean type", loc);
  3121. success = false;
  3122. }
  3123. if (sigPoint->GetKind() != hlsl::SigPoint::Kind::PSIn) {
  3124. emitError(
  3125. "HelperInvocation builtin can only be used as pixel shader input",
  3126. loc);
  3127. success = false;
  3128. }
  3129. } else if (builtin == "PointSize") {
  3130. if (!declType->isFloatingType()) {
  3131. emitError("PointSize builtin must be of float type", loc);
  3132. success = false;
  3133. }
  3134. switch (sigPoint->GetKind()) {
  3135. case hlsl::SigPoint::Kind::VSOut:
  3136. case hlsl::SigPoint::Kind::HSCPIn:
  3137. case hlsl::SigPoint::Kind::HSCPOut:
  3138. case hlsl::SigPoint::Kind::DSCPIn:
  3139. case hlsl::SigPoint::Kind::DSOut:
  3140. case hlsl::SigPoint::Kind::GSVIn:
  3141. case hlsl::SigPoint::Kind::GSOut:
  3142. case hlsl::SigPoint::Kind::PSIn:
  3143. case hlsl::SigPoint::Kind::MSOut:
  3144. break;
  3145. default:
  3146. emitError("PointSize builtin cannot be used as %0", loc)
  3147. << sigPoint->GetName();
  3148. success = false;
  3149. }
  3150. } else if (builtin == "BaseVertex" || builtin == "BaseInstance" ||
  3151. builtin == "DrawIndex") {
  3152. if (!declType->isSpecificBuiltinType(BuiltinType::Kind::Int) &&
  3153. !declType->isSpecificBuiltinType(BuiltinType::Kind::UInt)) {
  3154. emitError("%0 builtin must be of 32-bit scalar integer type", loc)
  3155. << builtin;
  3156. success = false;
  3157. }
  3158. switch (sigPoint->GetKind()) {
  3159. case hlsl::SigPoint::Kind::VSIn:
  3160. break;
  3161. case hlsl::SigPoint::Kind::MSIn:
  3162. case hlsl::SigPoint::Kind::ASIn:
  3163. if (builtin != "DrawIndex") {
  3164. emitError("%0 builtin cannot be used as %1", loc)
  3165. << builtin << sigPoint->GetName();
  3166. success = false;
  3167. }
  3168. break;
  3169. default:
  3170. emitError("%0 builtin cannot be used as %1", loc)
  3171. << builtin << sigPoint->GetName();
  3172. success = false;
  3173. }
  3174. } else if (builtin == "DeviceIndex") {
  3175. if (getStorageClassForSigPoint(sigPoint) != spv::StorageClass::Input) {
  3176. emitError("%0 builtin can only be used as shader input", loc)
  3177. << builtin;
  3178. success = false;
  3179. }
  3180. if (!declType->isSpecificBuiltinType(BuiltinType::Kind::Int) &&
  3181. !declType->isSpecificBuiltinType(BuiltinType::Kind::UInt)) {
  3182. emitError("%0 builtin must be of 32-bit scalar integer type", loc)
  3183. << builtin;
  3184. success = false;
  3185. }
  3186. } else if (builtin == "ViewportMaskNV") {
  3187. if (sigPoint->GetKind() != hlsl::SigPoint::Kind::MSPOut) {
  3188. emitError("%0 builtin can only be used as 'primitives' output in MS",
  3189. loc)
  3190. << builtin;
  3191. success = false;
  3192. }
  3193. if (!declType->isArrayType() ||
  3194. !declType->getArrayElementTypeNoTypeQual()->isSpecificBuiltinType(
  3195. BuiltinType::Kind::Int)) {
  3196. emitError("%0 builtin must be of type array of integers", loc)
  3197. << builtin;
  3198. success = false;
  3199. }
  3200. }
  3201. }
  3202. return success;
  3203. }
  3204. spv::StorageClass
  3205. DeclResultIdMapper::getStorageClassForSigPoint(const hlsl::SigPoint *sigPoint) {
  3206. // This translation is done based on the HLSL reference (see docs/dxil.rst).
  3207. const auto sigPointKind = sigPoint->GetKind();
  3208. const auto signatureKind = sigPoint->GetSignatureKind();
  3209. spv::StorageClass sc = spv::StorageClass::Max;
  3210. switch (signatureKind) {
  3211. case hlsl::DXIL::SignatureKind::Input:
  3212. sc = spv::StorageClass::Input;
  3213. break;
  3214. case hlsl::DXIL::SignatureKind::Output:
  3215. sc = spv::StorageClass::Output;
  3216. break;
  3217. case hlsl::DXIL::SignatureKind::Invalid: {
  3218. // There are some special cases in HLSL (See docs/dxil.rst):
  3219. // SignatureKind is "invalid" for PCIn, HSIn, GSIn, and CSIn.
  3220. switch (sigPointKind) {
  3221. case hlsl::DXIL::SigPointKind::PCIn:
  3222. case hlsl::DXIL::SigPointKind::HSIn:
  3223. case hlsl::DXIL::SigPointKind::GSIn:
  3224. case hlsl::DXIL::SigPointKind::CSIn:
  3225. case hlsl::DXIL::SigPointKind::MSIn:
  3226. case hlsl::DXIL::SigPointKind::ASIn:
  3227. sc = spv::StorageClass::Input;
  3228. break;
  3229. default:
  3230. llvm_unreachable("Found invalid SigPoint kind for semantic");
  3231. }
  3232. break;
  3233. }
  3234. case hlsl::DXIL::SignatureKind::PatchConstOrPrim: {
  3235. // There are some special cases in HLSL (See docs/dxil.rst):
  3236. // SignatureKind is "PatchConstOrPrim" for PCOut, MSPOut and DSIn.
  3237. switch (sigPointKind) {
  3238. case hlsl::DXIL::SigPointKind::PCOut:
  3239. case hlsl::DXIL::SigPointKind::MSPOut:
  3240. // Patch Constant Output (Output of Hull which is passed to Domain).
  3241. // Mesh Shader per-primitive output attributes.
  3242. sc = spv::StorageClass::Output;
  3243. break;
  3244. case hlsl::DXIL::SigPointKind::DSIn:
  3245. // Domain Shader regular input - Patch Constant data plus system values.
  3246. sc = spv::StorageClass::Input;
  3247. break;
  3248. default:
  3249. llvm_unreachable("Found invalid SigPoint kind for semantic");
  3250. }
  3251. break;
  3252. }
  3253. default:
  3254. llvm_unreachable("Found invalid SigPoint kind for semantic");
  3255. }
  3256. return sc;
  3257. }
  3258. QualType DeclResultIdMapper::getTypeAndCreateCounterForPotentialAliasVar(
  3259. const DeclaratorDecl *decl, bool *shouldBeAlias) {
  3260. if (const auto *varDecl = dyn_cast<VarDecl>(decl)) {
  3261. // This method is only intended to be used to create SPIR-V variables in the
  3262. // Function or Private storage class.
  3263. assert(!varDecl->isExternallyVisible() || varDecl->isStaticDataMember());
  3264. }
  3265. const QualType type = getTypeOrFnRetType(decl);
  3266. // Whether we should generate this decl as an alias variable.
  3267. bool genAlias = false;
  3268. // For ConstantBuffers, TextureBuffers, StructuredBuffers, ByteAddressBuffers
  3269. if (isConstantTextureBuffer(type) ||
  3270. isOrContainsAKindOfStructuredOrByteBuffer(type)) {
  3271. genAlias = true;
  3272. }
  3273. // Return via parameter whether alias was generated.
  3274. if (shouldBeAlias)
  3275. *shouldBeAlias = genAlias;
  3276. if (genAlias) {
  3277. needsLegalization = true;
  3278. createCounterVarForDecl(decl);
  3279. }
  3280. return type;
  3281. }
  3282. bool DeclResultIdMapper::getImplicitRegisterType(const ResourceVar &var,
  3283. char *registerTypeOut) const {
  3284. assert(registerTypeOut);
  3285. if (var.getSpirvInstr()) {
  3286. if (var.getSpirvInstr()->hasAstResultType()) {
  3287. QualType type = var.getSpirvInstr()->getAstResultType();
  3288. // Strip outer arrayness first
  3289. while (type->isArrayType())
  3290. type = type->getAsArrayTypeUnsafe()->getElementType();
  3291. // t - for shader resource views (SRV)
  3292. if (isTexture(type) || isNonWritableStructuredBuffer(type) ||
  3293. isByteAddressBuffer(type) || isBuffer(type)) {
  3294. *registerTypeOut = 't';
  3295. return true;
  3296. }
  3297. // s - for samplers
  3298. else if (isSampler(type)) {
  3299. *registerTypeOut = 's';
  3300. return true;
  3301. }
  3302. // u - for unordered access views (UAV)
  3303. else if (isRWByteAddressBuffer(type) || isRWAppendConsumeSBuffer(type) ||
  3304. isRWBuffer(type) || isRWTexture(type)) {
  3305. *registerTypeOut = 'u';
  3306. return true;
  3307. }
  3308. } else {
  3309. llvm::StringRef hlslUserType = var.getSpirvInstr()->getHlslUserType();
  3310. // b - for constant buffer views (CBV)
  3311. if (var.isGlobalsBuffer() || hlslUserType == "cbuffer" ||
  3312. hlslUserType == "ConstantBuffer") {
  3313. *registerTypeOut = 'b';
  3314. return true;
  3315. }
  3316. if (hlslUserType == "tbuffer") {
  3317. *registerTypeOut = 't';
  3318. return true;
  3319. }
  3320. }
  3321. }
  3322. *registerTypeOut = '\0';
  3323. return false;
  3324. }
  3325. SpirvVariable *
  3326. DeclResultIdMapper::createRayTracingNVStageVar(spv::StorageClass sc,
  3327. const VarDecl *decl) {
  3328. QualType type = decl->getType();
  3329. SpirvVariable *retVal = nullptr;
  3330. // Raytracing interface variables are special since they do not participate
  3331. // in any interface matching and hence do not create StageVar and
  3332. // track them under StageVars vector
  3333. const auto name = decl->getName();
  3334. switch (sc) {
  3335. case spv::StorageClass::IncomingRayPayloadNV:
  3336. case spv::StorageClass::IncomingCallableDataNV:
  3337. case spv::StorageClass::HitAttributeNV:
  3338. case spv::StorageClass::RayPayloadNV:
  3339. case spv::StorageClass::CallableDataNV:
  3340. retVal = spvBuilder.addModuleVar(type, sc, decl->hasAttr<HLSLPreciseAttr>(),
  3341. name.str());
  3342. break;
  3343. default:
  3344. assert(false && "Unsupported SPIR-V storage class for raytracing");
  3345. }
  3346. return retVal;
  3347. }
  3348. void DeclResultIdMapper::tryToCreateImplicitConstVar(const ValueDecl *decl) {
  3349. const VarDecl *varDecl = dyn_cast<VarDecl>(decl);
  3350. if (!varDecl || !varDecl->isImplicit())
  3351. return;
  3352. APValue *val = varDecl->evaluateValue();
  3353. if (!val)
  3354. return;
  3355. SpirvInstruction *constVal =
  3356. spvBuilder.getConstantInt(astContext.UnsignedIntTy, val->getInt());
  3357. constVal->setRValue(true);
  3358. astDecls[varDecl].instr = constVal;
  3359. }
  3360. SpirvInstruction *
  3361. DeclResultIdMapper::createHullMainOutputPatch(const ParmVarDecl *param,
  3362. const QualType retType,
  3363. uint32_t numOutputControlPoints) {
  3364. const QualType hullMainRetType = astContext.getConstantArrayType(
  3365. retType, llvm::APInt(32, numOutputControlPoints),
  3366. clang::ArrayType::Normal, 0);
  3367. SpirvInstruction *hullMainOutputPatch = createSpirvIntermediateOutputStageVar(
  3368. param, "temp.var.hullMainRetVal", hullMainRetType);
  3369. assert(astDecls[param].instr == nullptr);
  3370. astDecls[param].instr = hullMainOutputPatch;
  3371. return hullMainOutputPatch;
  3372. }
  3373. } // end namespace spirv
  3374. } // end namespace clang