ASTContextHLSL.cpp 53 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235
  1. //===--- ASTContextHLSL.cpp - HLSL support for AST nodes and operations ---===//
  2. ///////////////////////////////////////////////////////////////////////////////
  3. // //
  4. // ASTContextHLSL.cpp //
  5. // Copyright (C) Microsoft Corporation. All rights reserved. //
  6. // This file is distributed under the University of Illinois Open Source //
  7. // License. See LICENSE.TXT for details. //
  8. // //
  9. // This file implements the ASTContext interface for HLSL. //
  10. // //
  11. ///////////////////////////////////////////////////////////////////////////////
  12. #include "clang/AST/ASTContext.h"
  13. #include "clang/AST/Attr.h"
  14. #include "clang/AST/DeclCXX.h"
  15. #include "clang/AST/DeclTemplate.h"
  16. #include "clang/AST/Expr.h"
  17. #include "clang/AST/ExprCXX.h"
  18. #include "clang/AST/ExternalASTSource.h"
  19. #include "clang/AST/TypeLoc.h"
  20. #include "clang/Sema/SemaDiagnostic.h"
  21. #include "clang/Sema/Sema.h"
  22. #include "clang/Sema/Overload.h"
  23. #include "dxc/Support/Global.h"
  24. #include "dxc/HLSL/HLOperations.h"
  25. #include "dxc/HLSL/DxilSemantic.h"
  26. using namespace clang;
  27. using namespace hlsl;
  28. static const int FirstTemplateDepth = 0;
  29. static const int FirstParamPosition = 0;
  30. static const bool ForConstFalse = false; // a construct is targeting a const type
  31. static const bool ForConstTrue = true; // a construct is targeting a non-const type
  32. static const bool ExplicitConversionFalse = false;// a conversion operation is not the result of an explicit cast
  33. static const bool InheritedFalse = false; // template parameter default value is not inherited.
  34. static const bool ParameterPackFalse = false; // template parameter is not an ellipsis.
  35. static const bool TypenameFalse = false; // 'typename' specified rather than 'class' for a template argument.
  36. static const bool DelayTypeCreationTrue = true; // delay type creation for a declaration
  37. static const bool DelayTypeCreationFalse = false; // immediately create a type when the declaration is created
  38. static const unsigned int NoQuals = 0; // no qualifiers in effect
  39. static const SourceLocation NoLoc; // no source location attribution available
  40. static const bool HasWrittenPrototypeTrue = true; // function had the prototype written
  41. static const bool InlineFalse = false; // namespace is not an inline namespace
  42. static const bool InlineSpecifiedFalse = false; // function was not specified as inline
  43. static const bool IsConstexprFalse = false; // function is not constexpr
  44. static const bool ListInitializationFalse = false;// not performing a list initialization
  45. static const bool SuppressDiagTrue = true; // suppress diagnostics
  46. static const bool VirtualFalse = false; // whether the base class is declares 'virtual'
  47. static const bool BaseClassFalse = false; // whether the base class is declared as 'class' (vs. 'struct')
  48. /// <summary>Names of HLSLScalarType enumeration values, in matching order to HLSLScalarType.</summary>
  49. const char* HLSLScalarTypeNames[] = {
  50. "<unknown>",
  51. "bool",
  52. "int",
  53. "uint",
  54. "dword",
  55. "half",
  56. "float",
  57. "double",
  58. "min10float",
  59. "min16float",
  60. "min12int",
  61. "min16int",
  62. "min16uint",
  63. "literal float",
  64. "literal int",
  65. "int16_t",
  66. "int32_t",
  67. "int64_t",
  68. "uint16_t",
  69. "uint32_t",
  70. "uint64_t",
  71. "float16_t",
  72. "float32_t",
  73. "float64_t"
  74. };
  75. static_assert(HLSLScalarTypeCount == _countof(HLSLScalarTypeNames), "otherwise scalar constants are not aligned");
  76. static HLSLScalarType FindScalarTypeByName(const char *typeName, const size_t typeLen, const LangOptions& langOptions) {
  77. // skipped HLSLScalarType: unknown, literal int, literal float
  78. switch (typeLen) {
  79. case 3: // int
  80. if (typeName[0] == 'i') {
  81. if (strncmp(typeName, "int", 3))
  82. break;
  83. return HLSLScalarType_int;
  84. }
  85. break;
  86. case 4: // bool, uint, half
  87. if (typeName[0] == 'b') {
  88. if (strncmp(typeName, "bool", 4))
  89. break;
  90. return HLSLScalarType_bool;
  91. }
  92. else if (typeName[0] == 'u') {
  93. if (strncmp(typeName, "uint", 4))
  94. break;
  95. return HLSLScalarType_uint;
  96. }
  97. else if (typeName[0] == 'h') {
  98. if (strncmp(typeName, "half", 4))
  99. break;
  100. return HLSLScalarType_half;
  101. }
  102. break;
  103. case 5: // dword, float
  104. if (typeName[0] == 'd') {
  105. if (strncmp(typeName, "dword", 5))
  106. break;
  107. return HLSLScalarType_dword;
  108. }
  109. else if (typeName[0] == 'f') {
  110. if (strncmp(typeName, "float", 5))
  111. break;
  112. return HLSLScalarType_float;
  113. }
  114. break;
  115. case 6: // double
  116. if (typeName[0] == 'd') {
  117. if (strncmp(typeName, "double", 6))
  118. break;
  119. return HLSLScalarType_double;
  120. }
  121. break;
  122. case 7: // int64_t
  123. if (typeName[0] == 'i' && typeName[1] == 'n') {
  124. if (typeName[3] == '6') {
  125. if (strncmp(typeName, "int64_t", 7))
  126. break;
  127. return HLSLScalarType_int64;
  128. }
  129. }
  130. case 8: // min12int, min16int, uint64_t
  131. if (typeName[0] == 'm' && typeName[1] == 'i') {
  132. if (typeName[4] == '2') {
  133. if (strncmp(typeName, "min12int", 8))
  134. break;
  135. return HLSLScalarType_int_min12;
  136. }
  137. else if (typeName[4] == '6') {
  138. if (strncmp(typeName, "min16int", 8))
  139. break;
  140. return HLSLScalarType_int_min16;
  141. }
  142. }
  143. else if (typeName[0] == 'u' && typeName[1] == 'i') {
  144. if (typeName[4] == '6') {
  145. if (strncmp(typeName, "uint64_t", 8))
  146. break;
  147. return HLSLScalarType_uint64;
  148. }
  149. }
  150. break;
  151. case 9: // min16uint
  152. if (typeName[0] == 'm' && typeName[1] == 'i') {
  153. if (strncmp(typeName, "min16uint", 9))
  154. break;
  155. return HLSLScalarType_uint_min16;
  156. }
  157. break;
  158. case 10: // min10float, min16float
  159. if (typeName[0] == 'm' && typeName[1] == 'i') {
  160. if (typeName[4] == '0') {
  161. if (strncmp(typeName, "min10float", 10))
  162. break;
  163. return HLSLScalarType_float_min10;
  164. }
  165. if (typeName[4] == '6') {
  166. if (strncmp(typeName, "min16float", 10))
  167. break;
  168. return HLSLScalarType_float_min16;
  169. }
  170. }
  171. break;
  172. default:
  173. break;
  174. }
  175. // fixed width types (int16_t, uint16_t, int32_t, uint32_t, float16_t, float32_t, float64_t)
  176. // are only supported in HLSL 2018
  177. if (langOptions.HLSLVersion >= 2018) {
  178. switch (typeLen) {
  179. case 7: // int16_t, int32_t
  180. if (typeName[0] == 'i' && typeName[1] == 'n') {
  181. if (!langOptions.UseMinPrecision) {
  182. if (typeName[3] == '1') {
  183. if (strncmp(typeName, "int16_t", 7))
  184. break;
  185. return HLSLScalarType_int16;
  186. }
  187. }
  188. if (typeName[3] == '3') {
  189. if (strncmp(typeName, "int32_t", 7))
  190. break;
  191. return HLSLScalarType_int32;
  192. }
  193. }
  194. case 8: // uint16_t, uint32_t
  195. if (!langOptions.UseMinPrecision) {
  196. if (typeName[0] == 'u' && typeName[1] == 'i') {
  197. if (typeName[4] == '1') {
  198. if (strncmp(typeName, "uint16_t", 8))
  199. break;
  200. return HLSLScalarType_uint16;
  201. }
  202. }
  203. }
  204. if (typeName[4] == '3') {
  205. if (strncmp(typeName, "uint32_t", 8))
  206. break;
  207. return HLSLScalarType_uint32;
  208. }
  209. case 9: // float16_t, float32_t, float64_t
  210. if (typeName[0] == 'f' && typeName[1] == 'l') {
  211. if (!langOptions.UseMinPrecision) {
  212. if (typeName[5] == '1') {
  213. if (strncmp(typeName, "float16_t", 9))
  214. break;
  215. return HLSLScalarType_float16;
  216. }
  217. }
  218. if (typeName[5] == '3') {
  219. if (strncmp(typeName, "float32_t", 9))
  220. break;
  221. return HLSLScalarType_float32;
  222. }
  223. else if (typeName[5] == '6') {
  224. if (strncmp(typeName, "float64_t", 9))
  225. break;
  226. return HLSLScalarType_float64;
  227. }
  228. }
  229. }
  230. }
  231. return HLSLScalarType_unknown;
  232. }
  233. /// <summary>Provides the primitive type for lowering matrix types to IR.</summary>
  234. static
  235. CanQualType GetHLSLObjectHandleType(ASTContext& context)
  236. {
  237. return context.IntTy;
  238. }
  239. /// <summary>Adds a handle field to the specified record.</summary>
  240. static
  241. void AddHLSLHandleField(ASTContext& context, DeclContext* recordDecl, QualType handleQualType)
  242. {
  243. IdentifierInfo& handleId = context.Idents.get(StringRef("h"), tok::TokenKind::identifier);
  244. TypeSourceInfo* fieldTypeSource = context.getTrivialTypeSourceInfo(handleQualType, NoLoc);
  245. const bool MutableFalse = false;
  246. const InClassInitStyle initStyle = InClassInitStyle::ICIS_NoInit;
  247. FieldDecl* handleDecl = FieldDecl::Create(
  248. context, recordDecl, NoLoc, NoLoc, &handleId, handleQualType, fieldTypeSource, nullptr, MutableFalse, initStyle);
  249. handleDecl->setAccess(AccessSpecifier::AS_private);
  250. handleDecl->setImplicit(true);
  251. recordDecl->addDecl(handleDecl);
  252. }
  253. static
  254. void AddSubscriptOperator(
  255. ASTContext& context, unsigned int templateDepth, TemplateTypeParmDecl *elementTemplateParamDecl,
  256. NonTypeTemplateParmDecl* colCountTemplateParamDecl, QualType intType, CXXRecordDecl* templateRecordDecl,
  257. ClassTemplateDecl* vectorTemplateDecl,
  258. bool forConst)
  259. {
  260. QualType elementType = context.getTemplateTypeParmType(
  261. templateDepth, 0, ParameterPackFalse, elementTemplateParamDecl);
  262. Expr* sizeExpr = DeclRefExpr::Create(context, NestedNameSpecifierLoc(), NoLoc, colCountTemplateParamDecl, false,
  263. DeclarationNameInfo(colCountTemplateParamDecl->getDeclName(), NoLoc),
  264. intType, ExprValueKind::VK_RValue);
  265. CXXRecordDecl *vecTemplateRecordDecl = vectorTemplateDecl->getTemplatedDecl();
  266. const clang::Type *vecTy = vecTemplateRecordDecl->getTypeForDecl();
  267. TemplateArgument templateArgs[2] =
  268. {
  269. TemplateArgument(elementType),
  270. TemplateArgument(sizeExpr)
  271. };
  272. TemplateName canonName = context.getCanonicalTemplateName(TemplateName(vectorTemplateDecl));
  273. QualType vectorType = context.getTemplateSpecializationType(
  274. canonName, templateArgs, _countof(templateArgs), QualType(vecTy, 0));
  275. vectorType = context.getLValueReferenceType(vectorType);
  276. if (forConst)
  277. vectorType = context.getConstType(vectorType);
  278. QualType indexType = intType;
  279. CXXMethodDecl* functionDecl = CreateObjectFunctionDeclarationWithParams(
  280. context, templateRecordDecl, vectorType,
  281. ArrayRef<QualType>(indexType), ArrayRef<StringRef>(StringRef("index")),
  282. context.DeclarationNames.getCXXOperatorName(OO_Subscript), forConst);
  283. }
  284. /// <summary>Adds up-front support for HLSL matrix types (just the template declaration).</summary>
  285. void hlsl::AddHLSLMatrixTemplate(ASTContext& context, ClassTemplateDecl* vectorTemplateDecl, ClassTemplateDecl** matrixTemplateDecl)
  286. {
  287. DXASSERT_NOMSG(matrixTemplateDecl != nullptr);
  288. DXASSERT_NOMSG(vectorTemplateDecl != nullptr);
  289. DeclContext* currentDeclContext = context.getTranslationUnitDecl();
  290. // Create a matrix template declaration in translation unit scope.
  291. // template<typename element, int row_count, int col_count> matrix { ... }
  292. IdentifierInfo& elementTemplateParamId = context.Idents.get(StringRef("element"), tok::TokenKind::identifier);
  293. TemplateTypeParmDecl *elementTemplateParamDecl = TemplateTypeParmDecl::Create(
  294. context, currentDeclContext, NoLoc, NoLoc,
  295. FirstTemplateDepth, FirstParamPosition, &elementTemplateParamId, TypenameFalse, ParameterPackFalse);
  296. elementTemplateParamDecl->setDefaultArgument(context.getTrivialTypeSourceInfo(context.FloatTy));
  297. QualType intType = context.IntTy;
  298. Expr *literalIntFour = IntegerLiteral::Create(
  299. context, llvm::APInt(context.getIntWidth(intType), 4), intType, NoLoc);
  300. IdentifierInfo& rowCountParamId = context.Idents.get(StringRef("row_count"), tok::TokenKind::identifier);
  301. NonTypeTemplateParmDecl* rowCountTemplateParamDecl = NonTypeTemplateParmDecl::Create(
  302. context, currentDeclContext, NoLoc, NoLoc,
  303. FirstTemplateDepth, FirstParamPosition + 1, &rowCountParamId, intType, ParameterPackFalse, context.getTrivialTypeSourceInfo(intType));
  304. rowCountTemplateParamDecl->setDefaultArgument(literalIntFour);
  305. IdentifierInfo& colCountParamId = context.Idents.get(StringRef("col_count"), tok::TokenKind::identifier);
  306. NonTypeTemplateParmDecl* colCountTemplateParamDecl = NonTypeTemplateParmDecl::Create(
  307. context, currentDeclContext, NoLoc, NoLoc,
  308. FirstTemplateDepth, FirstParamPosition + 2, &colCountParamId, intType, ParameterPackFalse, context.getTrivialTypeSourceInfo(intType));
  309. colCountTemplateParamDecl->setDefaultArgument(literalIntFour);
  310. NamedDecl* templateParameters[] =
  311. {
  312. elementTemplateParamDecl, rowCountTemplateParamDecl, colCountTemplateParamDecl
  313. };
  314. TemplateParameterList* templateParameterList = TemplateParameterList::Create(
  315. context, NoLoc, NoLoc, templateParameters, _countof(templateParameters), NoLoc);
  316. IdentifierInfo& matrixId = context.Idents.get(StringRef("matrix"), tok::TokenKind::identifier);
  317. CXXRecordDecl* templateRecordDecl = CXXRecordDecl::Create(
  318. context, TagDecl::TagKind::TTK_Class, currentDeclContext, NoLoc, NoLoc, &matrixId,
  319. nullptr, DelayTypeCreationTrue);
  320. ClassTemplateDecl* classTemplateDecl = ClassTemplateDecl::Create(
  321. context, currentDeclContext, NoLoc, DeclarationName(&matrixId),
  322. templateParameterList, templateRecordDecl, nullptr);
  323. templateRecordDecl->setDescribedClassTemplate(classTemplateDecl);
  324. // Requesting the class name specialization will fault in required types.
  325. QualType T = classTemplateDecl->getInjectedClassNameSpecialization();
  326. T = context.getInjectedClassNameType(templateRecordDecl, T);
  327. assert(T->isDependentType() && "Class template type is not dependent?");
  328. classTemplateDecl->setLexicalDeclContext(currentDeclContext);
  329. templateRecordDecl->setLexicalDeclContext(currentDeclContext);
  330. templateRecordDecl->startDefinition();
  331. // Add an 'h' field to hold the handle.
  332. // The type is vector<element, col>[row].
  333. QualType elementType = context.getTemplateTypeParmType(
  334. /*templateDepth*/ 0, 0, ParameterPackFalse, elementTemplateParamDecl);
  335. Expr *sizeExpr = DeclRefExpr::Create(
  336. context, NestedNameSpecifierLoc(), NoLoc, rowCountTemplateParamDecl,
  337. false,
  338. DeclarationNameInfo(rowCountTemplateParamDecl->getDeclName(), NoLoc),
  339. intType, ExprValueKind::VK_RValue);
  340. Expr *rowSizeExpr = DeclRefExpr::Create(
  341. context, NestedNameSpecifierLoc(), NoLoc, colCountTemplateParamDecl,
  342. false,
  343. DeclarationNameInfo(colCountTemplateParamDecl->getDeclName(), NoLoc),
  344. intType, ExprValueKind::VK_RValue);
  345. QualType vectorType = context.getDependentSizedExtVectorType(
  346. elementType, rowSizeExpr, SourceLocation());
  347. QualType vectorArrayType = context.getDependentSizedArrayType(
  348. vectorType, sizeExpr, ArrayType::Normal, 0, SourceRange());
  349. AddHLSLHandleField(context, templateRecordDecl, vectorArrayType);
  350. // Add an operator[]. The operator ranges from zero to rowcount-1, and returns a vector of colcount elements.
  351. const unsigned int templateDepth = 0;
  352. AddSubscriptOperator(context, templateDepth, elementTemplateParamDecl,
  353. colCountTemplateParamDecl, context.UnsignedIntTy,
  354. templateRecordDecl, vectorTemplateDecl, ForConstFalse);
  355. AddSubscriptOperator(context, templateDepth, elementTemplateParamDecl,
  356. colCountTemplateParamDecl, context.UnsignedIntTy,
  357. templateRecordDecl, vectorTemplateDecl, ForConstTrue);
  358. templateRecordDecl->completeDefinition();
  359. classTemplateDecl->setImplicit(true);
  360. templateRecordDecl->setImplicit(true);
  361. // Both declarations need to be present for correct handling.
  362. currentDeclContext->addDecl(classTemplateDecl);
  363. currentDeclContext->addDecl(templateRecordDecl);
  364. #ifdef DBG
  365. // Verify that we can read the field member from the template record.
  366. DeclContext::lookup_result lookupResult = templateRecordDecl->lookup(
  367. DeclarationName(&context.Idents.get(StringRef("h"))));
  368. DXASSERT(!lookupResult.empty(), "otherwise matrix handle cannot be looked up");
  369. #endif
  370. *matrixTemplateDecl = classTemplateDecl;
  371. }
  372. static void AddHLSLVectorSubscriptAttr(Decl *D, ASTContext &context) {
  373. StringRef group = GetHLOpcodeGroupName(HLOpcodeGroup::HLSubscript);
  374. D->addAttr(HLSLIntrinsicAttr::CreateImplicit(context, group, "", static_cast<unsigned>(HLSubscriptOpcode::VectorSubscript)));
  375. }
  376. /// <summary>Adds up-front support for HLSL vector types (just the template declaration).</summary>
  377. void hlsl::AddHLSLVectorTemplate(ASTContext& context, ClassTemplateDecl** vectorTemplateDecl)
  378. {
  379. DXASSERT_NOMSG(vectorTemplateDecl != nullptr);
  380. DeclContext* currentDeclContext = context.getTranslationUnitDecl();
  381. // Create a vector template declaration in translation unit scope.
  382. // template<typename element, int element_count> vector { ... }
  383. IdentifierInfo& elementTemplateParamId = context.Idents.get(StringRef("element"), tok::TokenKind::identifier);
  384. TemplateTypeParmDecl *elementTemplateParamDecl = TemplateTypeParmDecl::Create(
  385. context, currentDeclContext, NoLoc, NoLoc,
  386. FirstTemplateDepth, FirstParamPosition, &elementTemplateParamId, TypenameFalse, ParameterPackFalse);
  387. elementTemplateParamDecl->setDefaultArgument(context.getTrivialTypeSourceInfo(context.FloatTy));
  388. QualType intType = context.IntTy;
  389. Expr *literalIntFour = IntegerLiteral::Create(
  390. context, llvm::APInt(context.getIntWidth(intType), 4), intType, NoLoc);
  391. IdentifierInfo& colCountParamId = context.Idents.get(StringRef("element_count"), tok::TokenKind::identifier);
  392. NonTypeTemplateParmDecl* colCountTemplateParamDecl = NonTypeTemplateParmDecl::Create(
  393. context, currentDeclContext, NoLoc, NoLoc,
  394. FirstTemplateDepth, FirstParamPosition + 1, &colCountParamId, intType, ParameterPackFalse, nullptr);
  395. colCountTemplateParamDecl->setDefaultArgument(literalIntFour);
  396. NamedDecl* templateParameters[] =
  397. {
  398. elementTemplateParamDecl, colCountTemplateParamDecl
  399. };
  400. TemplateParameterList* templateParameterList = TemplateParameterList::Create(
  401. context, NoLoc, NoLoc, templateParameters, _countof(templateParameters), NoLoc);
  402. IdentifierInfo& vectorId = context.Idents.get(StringRef("vector"), tok::TokenKind::identifier);
  403. CXXRecordDecl* templateRecordDecl = CXXRecordDecl::Create(
  404. context, TagDecl::TagKind::TTK_Class, currentDeclContext, NoLoc, NoLoc, &vectorId,
  405. nullptr, DelayTypeCreationTrue);
  406. ClassTemplateDecl* classTemplateDecl = ClassTemplateDecl::Create(
  407. context, currentDeclContext, NoLoc, DeclarationName(&vectorId),
  408. templateParameterList, templateRecordDecl, nullptr);
  409. templateRecordDecl->setDescribedClassTemplate(classTemplateDecl);
  410. // Requesting the class name specialization will fault in required types.
  411. QualType T = classTemplateDecl->getInjectedClassNameSpecialization();
  412. T = context.getInjectedClassNameType(templateRecordDecl, T);
  413. assert(T->isDependentType() && "Class template type is not dependent?");
  414. classTemplateDecl->setLexicalDeclContext(currentDeclContext);
  415. templateRecordDecl->setLexicalDeclContext(currentDeclContext);
  416. templateRecordDecl->startDefinition();
  417. // Add an 'h' field to hold the handle.
  418. AddHLSLHandleField(context, templateRecordDecl, QualType(GetHLSLObjectHandleType(context)));
  419. // Add an operator[]. The operator ranges from zero to colcount-1, and returns a scalar.
  420. const unsigned int templateDepth = 0;
  421. QualType resultType = context.getTemplateTypeParmType(
  422. templateDepth, 0, ParameterPackFalse, elementTemplateParamDecl);
  423. // ForConstTrue:
  424. QualType refResultType = context.getConstType(context.getLValueReferenceType(resultType));
  425. CXXMethodDecl* functionDecl = CreateObjectFunctionDeclarationWithParams(
  426. context, templateRecordDecl, refResultType,
  427. ArrayRef<QualType>(context.UnsignedIntTy), ArrayRef<StringRef>(StringRef("index")),
  428. context.DeclarationNames.getCXXOperatorName(OO_Subscript), ForConstTrue);
  429. AddHLSLVectorSubscriptAttr(functionDecl, context);
  430. // ForConstFalse:
  431. resultType = context.getLValueReferenceType(resultType);
  432. functionDecl = CreateObjectFunctionDeclarationWithParams(
  433. context, templateRecordDecl, resultType,
  434. ArrayRef<QualType>(context.UnsignedIntTy), ArrayRef<StringRef>(StringRef("index")),
  435. context.DeclarationNames.getCXXOperatorName(OO_Subscript), ForConstFalse);
  436. AddHLSLVectorSubscriptAttr(functionDecl, context);
  437. templateRecordDecl->completeDefinition();
  438. classTemplateDecl->setImplicit(true);
  439. templateRecordDecl->setImplicit(true);
  440. // Both declarations need to be present for correct handling.
  441. currentDeclContext->addDecl(classTemplateDecl);
  442. currentDeclContext->addDecl(templateRecordDecl);
  443. #ifdef DBG
  444. // Verify that we can read the field member from the template record.
  445. DeclContext::lookup_result lookupResult = templateRecordDecl->lookup(
  446. DeclarationName(&context.Idents.get(StringRef("h"))));
  447. DXASSERT(!lookupResult.empty(), "otherwise vector handle cannot be looked up");
  448. #endif
  449. *vectorTemplateDecl = classTemplateDecl;
  450. }
  451. /// <summary>
  452. /// Adds a new record type in the specified context with the given name. The record type will have a handle field.
  453. /// </summary>
  454. void hlsl::AddRecordTypeWithHandle(ASTContext& context, _Outptr_ CXXRecordDecl** typeDecl, _In_z_ const char* typeName)
  455. {
  456. DXASSERT_NOMSG(typeDecl != nullptr);
  457. DXASSERT_NOMSG(typeName != nullptr);
  458. *typeDecl = nullptr;
  459. DeclContext* currentDeclContext = context.getTranslationUnitDecl();
  460. IdentifierInfo& newTypeId = context.Idents.get(StringRef(typeName), tok::TokenKind::identifier);
  461. CXXRecordDecl* newDecl = CXXRecordDecl::Create(
  462. context, TagDecl::TagKind::TTK_Struct, currentDeclContext, NoLoc, NoLoc, &newTypeId, nullptr);
  463. newDecl->setLexicalDeclContext(currentDeclContext);
  464. newDecl->setFreeStanding();
  465. newDecl->startDefinition();
  466. AddHLSLHandleField(context, newDecl, QualType(GetHLSLObjectHandleType(context)));
  467. currentDeclContext->addDecl(newDecl);
  468. newDecl->completeDefinition();
  469. *typeDecl = newDecl;
  470. }
  471. // creates a global static constant unsigned integer with value.
  472. // equivalent to: static const uint name = val;
  473. static void AddConstInt(clang::ASTContext& context, DeclContext *DC, StringRef name, int val) {
  474. IdentifierInfo &Id = context.Idents.get(name, tok::TokenKind::identifier);
  475. QualType type = context.getConstType(context.UnsignedIntTy);
  476. VarDecl *varDecl = VarDecl::Create(context, DC, NoLoc, NoLoc, &Id, type,
  477. context.getTrivialTypeSourceInfo(type),
  478. clang::StorageClass::SC_Static);
  479. Expr *exprVal = IntegerLiteral::Create(
  480. context, llvm::APInt(context.getIntWidth(type), val), type, NoLoc);
  481. varDecl->setInit(exprVal);
  482. varDecl->setImplicit(true);
  483. DC->addDecl(varDecl);
  484. }
  485. /// <summary> Adds a const integers for ray flags </summary>
  486. void hlsl::AddRayFlags(ASTContext& context) {
  487. DeclContext *curDC = context.getTranslationUnitDecl();
  488. // typedef uint RAY_FLAG;
  489. IdentifierInfo &rayFlagId = context.Idents.get(StringRef("RAY_FLAG"), tok::TokenKind::identifier);
  490. TypeSourceInfo *uintTypeSource = context.getTrivialTypeSourceInfo(context.UnsignedIntTy, NoLoc);
  491. TypedefDecl *rayFlagDecl = TypedefDecl::Create(context, curDC, NoLoc, NoLoc, &rayFlagId, uintTypeSource);
  492. curDC->addDecl(rayFlagDecl);
  493. rayFlagDecl->setImplicit(true);
  494. // static const uint RAY_FLAG_* = *;
  495. AddConstInt(context, curDC, StringRef("RAY_FLAG_NONE"), 0x00);
  496. AddConstInt(context, curDC, StringRef("RAY_FLAG_FORCE_OPAQUE"), 0x01);
  497. AddConstInt(context, curDC, StringRef("RAY_FLAG_FORCE_NON_OPAQUE"), 0x02);
  498. AddConstInt(context, curDC, StringRef("RAY_FLAG_ACCEPT_FIRST_HIT_AND_END_SEARCH"), 0x04);
  499. AddConstInt(context, curDC, StringRef("RAY_FLAG_SKIP_CLOSEST_HIT_SHADER"), 0x08);
  500. AddConstInt(context, curDC, StringRef("RAY_FLAG_CULL_BACK_FACING_TRIANGLES"), 0x10);
  501. AddConstInt(context, curDC, StringRef("RAY_FLAG_CULL_FRONT_FACING_TRIANGLES"), 0x20);
  502. AddConstInt(context, curDC, StringRef("RAY_FLAG_CULL_OPAQUE"), 0x40);
  503. AddConstInt(context, curDC, StringRef("RAY_FLAG_CULL_NON_OPAQUE"), 0x80);
  504. }
  505. /// <summary> Adds a constant integers for hit kinds </summary>
  506. void hlsl::AddHitKinds(ASTContext& context) {
  507. DeclContext *curDC = context.getTranslationUnitDecl();
  508. // static const uint HIT_KIND_* = *;
  509. AddConstInt(context, curDC, StringRef("HIT_KIND_TRIANGLE_FRONT_FACE"), 0xfe);
  510. AddConstInt(context, curDC, StringRef("HIT_KIND_TRIANGLE_BACK_FACE"), 0xff);
  511. }
  512. static
  513. Expr* IntConstantAsBoolExpr(clang::Sema& sema, uint64_t value)
  514. {
  515. return sema.ImpCastExprToType(
  516. sema.ActOnIntegerConstant(NoLoc, value).get(), sema.getASTContext().BoolTy, CK_IntegralToBoolean).get();
  517. }
  518. static
  519. CXXRecordDecl* CreateStdStructWithStaticBool(clang::ASTContext& context, NamespaceDecl* stdNamespace, IdentifierInfo& trueTypeId, IdentifierInfo& valueId, Expr* trueExpression)
  520. {
  521. // struct true_type { static const bool value = true; }
  522. TypeSourceInfo* boolTypeSource = context.getTrivialTypeSourceInfo(context.BoolTy.withConst());
  523. CXXRecordDecl* trueTypeDecl = CXXRecordDecl::Create(context, TagTypeKind::TTK_Struct, stdNamespace, NoLoc, NoLoc, &trueTypeId, nullptr, DelayTypeCreationTrue);
  524. QualType trueTypeQT = context.getTagDeclType(trueTypeDecl); // Fault this in now.
  525. // static fields are variables in the AST
  526. VarDecl* trueValueDecl = VarDecl::Create(context, trueTypeDecl, NoLoc, NoLoc, &valueId,
  527. context.BoolTy.withConst(), boolTypeSource, SC_Static);
  528. trueValueDecl->setInit(trueExpression);
  529. trueValueDecl->setConstexpr(true);
  530. trueValueDecl->setAccess(AS_public);
  531. trueTypeDecl->setLexicalDeclContext(stdNamespace);
  532. trueTypeDecl->startDefinition();
  533. trueTypeDecl->addDecl(trueValueDecl);
  534. trueTypeDecl->completeDefinition();
  535. stdNamespace->addDecl(trueTypeDecl);
  536. return trueTypeDecl;
  537. }
  538. static
  539. void DefineRecordWithBase(CXXRecordDecl* decl, DeclContext* lexicalContext, const CXXBaseSpecifier* base)
  540. {
  541. decl->setLexicalDeclContext(lexicalContext);
  542. decl->startDefinition();
  543. decl->setBases(&base, 1);
  544. decl->completeDefinition();
  545. lexicalContext->addDecl(decl);
  546. }
  547. static
  548. void SetPartialExplicitSpecialization(ClassTemplateDecl* templateDecl, ClassTemplatePartialSpecializationDecl* specializationDecl)
  549. {
  550. specializationDecl->setSpecializationKind(TSK_ExplicitSpecialization);
  551. templateDecl->AddPartialSpecialization(specializationDecl, nullptr);
  552. }
  553. static
  554. void CreateIsEqualSpecialization(ASTContext& context, ClassTemplateDecl* templateDecl, TemplateName& templateName,
  555. DeclContext* lexicalContext, const CXXBaseSpecifier* base, TemplateParameterList* templateParamList,
  556. TemplateArgument (&templateArgs)[2])
  557. {
  558. QualType specializationCanonType = context.getTemplateSpecializationType(templateName, templateArgs, _countof(templateArgs));
  559. TemplateArgumentListInfo templateArgsListInfo = TemplateArgumentListInfo(NoLoc, NoLoc);
  560. templateArgsListInfo.addArgument(TemplateArgumentLoc(templateArgs[0], context.getTrivialTypeSourceInfo(templateArgs[0].getAsType())));
  561. templateArgsListInfo.addArgument(TemplateArgumentLoc(templateArgs[1], context.getTrivialTypeSourceInfo(templateArgs[1].getAsType())));
  562. ClassTemplatePartialSpecializationDecl* specializationDecl =
  563. ClassTemplatePartialSpecializationDecl::Create(context, TTK_Struct, lexicalContext, NoLoc, NoLoc,
  564. templateParamList, templateDecl, templateArgs, _countof(templateArgs),
  565. templateArgsListInfo, specializationCanonType, nullptr);
  566. context.getTagDeclType(specializationDecl); // Fault this in now.
  567. DefineRecordWithBase(specializationDecl, lexicalContext, base);
  568. SetPartialExplicitSpecialization(templateDecl, specializationDecl);
  569. }
  570. /// <summary>Adds the implementation for std::is_equal.</summary>
  571. void hlsl::AddStdIsEqualImplementation(clang::ASTContext& context, clang::Sema& sema)
  572. {
  573. // The goal is to support std::is_same<T, T>::value for testing purposes, in a manner that can
  574. // evolve into a compliant feature in the future.
  575. //
  576. // The definitions necessary are as follows (all in the std namespace).
  577. // template <class T, T v>
  578. // struct integral_constant {
  579. // typedef T value_type;
  580. // static const value_type value = v;
  581. // operator value_type() { return value; }
  582. // };
  583. //
  584. // typedef integral_constant<bool, true> true_type;
  585. // typedef integral_constant<bool, false> false_type;
  586. //
  587. // template<typename T, typename U> struct is_same : public false_type {};
  588. // template<typename T> struct is_same<T, T> : public true_type{};
  589. //
  590. // We instead use these simpler definitions for true_type and false_type.
  591. // struct false_type { static const bool value = false; };
  592. // struct true_type { static const bool value = true; };
  593. DeclContext* tuContext = context.getTranslationUnitDecl();
  594. IdentifierInfo& stdId = context.Idents.get(StringRef("std"), tok::TokenKind::identifier);
  595. IdentifierInfo& trueTypeId = context.Idents.get(StringRef("true_type"), tok::TokenKind::identifier);
  596. IdentifierInfo& falseTypeId = context.Idents.get(StringRef("false_type"), tok::TokenKind::identifier);
  597. IdentifierInfo& valueId = context.Idents.get(StringRef("value"), tok::TokenKind::identifier);
  598. IdentifierInfo& isSameId = context.Idents.get(StringRef("is_same"), tok::TokenKind::identifier);
  599. IdentifierInfo& tId = context.Idents.get(StringRef("T"), tok::TokenKind::identifier);
  600. IdentifierInfo& vId = context.Idents.get(StringRef("V"), tok::TokenKind::identifier);
  601. Expr* trueExpression = IntConstantAsBoolExpr(sema, 1);
  602. Expr* falseExpression = IntConstantAsBoolExpr(sema, 0);
  603. // namespace std
  604. NamespaceDecl* stdNamespace = NamespaceDecl::Create(context, tuContext, InlineFalse, NoLoc, NoLoc, &stdId, nullptr);
  605. CXXRecordDecl* trueTypeDecl = CreateStdStructWithStaticBool(context, stdNamespace, trueTypeId, valueId, trueExpression);
  606. CXXRecordDecl* falseTypeDecl = CreateStdStructWithStaticBool(context, stdNamespace, falseTypeId, valueId, falseExpression);
  607. // template<typename T, typename U> struct is_same : public false_type {};
  608. CXXRecordDecl* isSameFalseRecordDecl = CXXRecordDecl::Create(context, TagTypeKind::TTK_Struct, stdNamespace, NoLoc, NoLoc, &isSameId, nullptr, false);
  609. TemplateTypeParmDecl* tParam = TemplateTypeParmDecl::Create(context, stdNamespace, NoLoc, NoLoc, FirstTemplateDepth, FirstParamPosition, &tId, TypenameFalse, ParameterPackFalse);
  610. TemplateTypeParmDecl* uParam = TemplateTypeParmDecl::Create(context, stdNamespace, NoLoc, NoLoc, FirstTemplateDepth, FirstParamPosition + 1, &vId, TypenameFalse, ParameterPackFalse);
  611. NamedDecl* falseParams[] = { tParam, uParam };
  612. TemplateParameterList* falseParamList = TemplateParameterList::Create(context, NoLoc, NoLoc, falseParams, _countof(falseParams), NoLoc);
  613. ClassTemplateDecl* isSameFalseTemplateDecl = ClassTemplateDecl::Create(context, stdNamespace, NoLoc, DeclarationName(&isSameId), falseParamList, isSameFalseRecordDecl, nullptr);
  614. context.getTagDeclType(isSameFalseRecordDecl); // Fault this in now.
  615. CXXBaseSpecifier* falseBase = new (context)CXXBaseSpecifier(SourceRange(), VirtualFalse, BaseClassFalse, AS_public,
  616. context.getTrivialTypeSourceInfo(context.getTypeDeclType(falseTypeDecl)), NoLoc);
  617. isSameFalseRecordDecl->setDescribedClassTemplate(isSameFalseTemplateDecl);
  618. isSameFalseTemplateDecl->setLexicalDeclContext(stdNamespace);
  619. DefineRecordWithBase(isSameFalseRecordDecl, stdNamespace, falseBase);
  620. // is_same for 'true' is a specialization of is_same for 'false', taking a single T, where both T will match
  621. // template<typename T> struct is_same<T, T> : public true_type{};
  622. TemplateName tn = TemplateName(isSameFalseTemplateDecl);
  623. NamedDecl* trueParams[] = { tParam };
  624. TemplateParameterList* trueParamList = TemplateParameterList::Create(context, NoLoc, NoLoc, trueParams, _countof(trueParams), NoLoc);
  625. CXXBaseSpecifier* trueBase = new (context)CXXBaseSpecifier(SourceRange(), VirtualFalse, BaseClassFalse, AS_public,
  626. context.getTrivialTypeSourceInfo(context.getTypeDeclType(trueTypeDecl)), NoLoc);
  627. TemplateArgument ta = TemplateArgument(context.getCanonicalType(context.getTypeDeclType(tParam)));
  628. TemplateArgument isSameTrueTemplateArgs[] = { ta, ta };
  629. CreateIsEqualSpecialization(context, isSameFalseTemplateDecl, tn, stdNamespace, trueBase, trueParamList, isSameTrueTemplateArgs);
  630. stdNamespace->addDecl(isSameFalseTemplateDecl);
  631. stdNamespace->setImplicit(true);
  632. tuContext->addDecl(stdNamespace);
  633. // This could be a parameter if ever needed.
  634. const bool SupportExtensions = true;
  635. // Consider right-hand const and right-hand ref to be true for is_same:
  636. // template<typename T> struct is_same<T, const T> : public true_type{};
  637. // template<typename T> struct is_same<T, T&> : public true_type{};
  638. if (SupportExtensions)
  639. {
  640. TemplateArgument trueConstArg = TemplateArgument(context.getCanonicalType(context.getTypeDeclType(tParam)).withConst());
  641. TemplateArgument isSameTrueConstTemplateArgs[] = { ta, trueConstArg };
  642. CreateIsEqualSpecialization(context, isSameFalseTemplateDecl, tn, stdNamespace, trueBase, trueParamList, isSameTrueConstTemplateArgs);
  643. TemplateArgument trueRefArg = TemplateArgument(
  644. context.getLValueReferenceType(context.getCanonicalType(context.getTypeDeclType(tParam))));
  645. TemplateArgument isSameTrueRefTemplateArgs[] = { ta, trueRefArg };
  646. CreateIsEqualSpecialization(context, isSameFalseTemplateDecl, tn, stdNamespace, trueBase, trueParamList, isSameTrueRefTemplateArgs);
  647. }
  648. }
  649. /// <summary>
  650. /// Adds a new template type in the specified context with the given name. The record type will have a handle field.
  651. /// </summary>
  652. /// <parm name="context">AST context to which template will be added.</param>
  653. /// <parm name="typeDecl">After execution, template declaration.</param>
  654. /// <parm name="recordDecl">After execution, record declaration for template.</param>
  655. /// <parm name="typeName">Name of template to create.</param>
  656. /// <parm name="templateArgCount">Number of template arguments (one or two).</param>
  657. /// <parm name="defaultTypeArgValue">If assigned, the default argument for the element template.</param>
  658. void hlsl::AddTemplateTypeWithHandle(
  659. ASTContext& context,
  660. _Outptr_ ClassTemplateDecl** typeDecl,
  661. _Outptr_ CXXRecordDecl** recordDecl,
  662. _In_z_ const char* typeName,
  663. uint8_t templateArgCount,
  664. _In_opt_ TypeSourceInfo* defaultTypeArgValue
  665. )
  666. {
  667. DXASSERT_NOMSG(typeDecl != nullptr);
  668. DXASSERT_NOMSG(recordDecl != nullptr);
  669. DXASSERT_NOMSG(typeName != nullptr);
  670. DXASSERT(templateArgCount != 0, "otherwise caller should be creating a class or struct");
  671. DXASSERT(templateArgCount <= 2, "otherwise the function needs to be updated for a different template pattern");
  672. DeclContext* currentDeclContext = context.getTranslationUnitDecl();
  673. // Create an object template declaration in translation unit scope.
  674. // templateArgCount=1: template<typename element> typeName { ... }
  675. // templateArgCount=2: template<typename element, int count> typeName { ... }
  676. IdentifierInfo& elementTemplateParamId = context.Idents.get(StringRef("element"), tok::TokenKind::identifier);
  677. TemplateTypeParmDecl *elementTemplateParamDecl = TemplateTypeParmDecl::Create(
  678. context, currentDeclContext, NoLoc, NoLoc,
  679. FirstTemplateDepth, FirstParamPosition, &elementTemplateParamId, TypenameFalse, ParameterPackFalse);
  680. QualType intType = context.IntTy;
  681. if (defaultTypeArgValue != nullptr)
  682. {
  683. elementTemplateParamDecl->setDefaultArgument(defaultTypeArgValue);
  684. }
  685. NonTypeTemplateParmDecl* countTemplateParamDecl = nullptr;
  686. if (templateArgCount > 1) {
  687. IdentifierInfo& countParamId = context.Idents.get(StringRef("count"), tok::TokenKind::identifier);
  688. countTemplateParamDecl = NonTypeTemplateParmDecl::Create(
  689. context, currentDeclContext, NoLoc, NoLoc,
  690. FirstTemplateDepth, FirstParamPosition + 1, &countParamId, intType, ParameterPackFalse, nullptr);
  691. // Zero means default here. The count is decided by runtime.
  692. Expr *literalIntZero = IntegerLiteral::Create(
  693. context, llvm::APInt(context.getIntWidth(intType), 0), intType, NoLoc);
  694. countTemplateParamDecl->setDefaultArgument(literalIntZero);
  695. }
  696. NamedDecl* templateParameters[] =
  697. {
  698. elementTemplateParamDecl, countTemplateParamDecl
  699. };
  700. TemplateParameterList* templateParameterList = TemplateParameterList::Create(
  701. context, NoLoc, NoLoc, templateParameters, templateArgCount, NoLoc);
  702. IdentifierInfo& typeId = context.Idents.get(StringRef(typeName), tok::TokenKind::identifier);
  703. CXXRecordDecl* templateRecordDecl = CXXRecordDecl::Create(
  704. context, TagDecl::TagKind::TTK_Class, currentDeclContext, NoLoc, NoLoc, &typeId,
  705. nullptr, DelayTypeCreationTrue);
  706. ClassTemplateDecl* classTemplateDecl = ClassTemplateDecl::Create(
  707. context, currentDeclContext, NoLoc, DeclarationName(&typeId),
  708. templateParameterList, templateRecordDecl, nullptr);
  709. templateRecordDecl->setDescribedClassTemplate(classTemplateDecl);
  710. // Requesting the class name specialization will fault in required types.
  711. QualType T = classTemplateDecl->getInjectedClassNameSpecialization();
  712. T = context.getInjectedClassNameType(templateRecordDecl, T);
  713. assert(T->isDependentType() && "Class template type is not dependent?");
  714. classTemplateDecl->setLexicalDeclContext(currentDeclContext);
  715. templateRecordDecl->setLexicalDeclContext(currentDeclContext);
  716. templateRecordDecl->startDefinition();
  717. // Many more things to come here, like constructors and the like....
  718. // Add an 'h' field to hold the handle.
  719. QualType elementType = context.getTemplateTypeParmType(
  720. /*templateDepth*/ 0, 0, ParameterPackFalse, elementTemplateParamDecl);
  721. if (templateArgCount > 1 &&
  722. // Only need array type for inputpatch and outputpatch.
  723. // Avoid Texture2DMS which may use 0 count.
  724. // TODO: use hlsl types to do the check.
  725. !typeId.getName().startswith("Texture")) {
  726. Expr *countExpr = DeclRefExpr::Create(
  727. context, NestedNameSpecifierLoc(), NoLoc, countTemplateParamDecl, false,
  728. DeclarationNameInfo(countTemplateParamDecl->getDeclName(), NoLoc),
  729. intType, ExprValueKind::VK_RValue);
  730. elementType = context.getDependentSizedArrayType(
  731. elementType, countExpr, ArrayType::ArraySizeModifier::Normal, 0,
  732. SourceRange());
  733. // InputPatch and OutputPatch also have a "Length" static const member for the number of control points
  734. IdentifierInfo& lengthId = context.Idents.get(StringRef("Length"), tok::TokenKind::identifier);
  735. TypeSourceInfo* lengthTypeSource = context.getTrivialTypeSourceInfo(intType.withConst());
  736. VarDecl* lengthValueDecl = VarDecl::Create(context, templateRecordDecl, NoLoc, NoLoc, &lengthId,
  737. intType.withConst(), lengthTypeSource, SC_Static);
  738. lengthValueDecl->setInit(countExpr);
  739. lengthValueDecl->setAccess(AS_public);
  740. templateRecordDecl->addDecl(lengthValueDecl);
  741. }
  742. AddHLSLHandleField(context, templateRecordDecl, elementType);
  743. templateRecordDecl->completeDefinition();
  744. // Both declarations need to be present for correct handling.
  745. currentDeclContext->addDecl(classTemplateDecl);
  746. currentDeclContext->addDecl(templateRecordDecl);
  747. #ifdef DBG
  748. // Verify that we can read the field member from the template record.
  749. DeclContext::lookup_result lookupResult = templateRecordDecl->lookup(
  750. DeclarationName(&context.Idents.get(StringRef("h"))));
  751. DXASSERT(!lookupResult.empty(), "otherwise template object handle cannot be looked up");
  752. #endif
  753. *typeDecl = classTemplateDecl;
  754. *recordDecl = templateRecordDecl;
  755. }
  756. FunctionTemplateDecl* hlsl::CreateFunctionTemplateDecl(
  757. ASTContext& context,
  758. _In_ CXXRecordDecl* recordDecl,
  759. _In_ CXXMethodDecl* functionDecl,
  760. _In_count_(templateParamNamedDeclsCount) NamedDecl** templateParamNamedDecls,
  761. size_t templateParamNamedDeclsCount)
  762. {
  763. DXASSERT_NOMSG(recordDecl != nullptr);
  764. DXASSERT_NOMSG(templateParamNamedDecls != nullptr);
  765. DXASSERT(templateParamNamedDeclsCount > 0, "otherwise caller shouldn't invoke this function");
  766. TemplateParameterList* templateParams = TemplateParameterList::Create(
  767. context, NoLoc, NoLoc, &templateParamNamedDecls[0], templateParamNamedDeclsCount, NoLoc);
  768. FunctionTemplateDecl* functionTemplate =
  769. FunctionTemplateDecl::Create(context, recordDecl, NoLoc, functionDecl->getDeclName(), templateParams, functionDecl);
  770. functionTemplate->setAccess(AccessSpecifier::AS_public);
  771. functionTemplate->setLexicalDeclContext(recordDecl);
  772. functionDecl->setDescribedFunctionTemplate(functionTemplate);
  773. recordDecl->addDecl(functionTemplate);
  774. return functionTemplate;
  775. }
  776. static
  777. void AssociateParametersToFunctionPrototype(
  778. _In_ TypeSourceInfo* tinfo,
  779. _In_count_(numParams) ParmVarDecl** paramVarDecls,
  780. unsigned int numParams)
  781. {
  782. FunctionProtoTypeLoc protoLoc = tinfo->getTypeLoc().getAs<FunctionProtoTypeLoc>();
  783. DXASSERT(protoLoc.getNumParams() == numParams, "otherwise unexpected number of parameters available");
  784. for (unsigned i = 0; i < numParams; i++) {
  785. DXASSERT(protoLoc.getParam(i) == nullptr, "otherwise prototype parameters were already initialized");
  786. protoLoc.setParam(i, paramVarDecls[i]);
  787. }
  788. }
  789. static void CreateObjectFunctionDeclaration(
  790. ASTContext &context, _In_ CXXRecordDecl *recordDecl, QualType resultType,
  791. ArrayRef<QualType> args, DeclarationName declarationName, bool isConst,
  792. _Out_ CXXMethodDecl **functionDecl, _Out_ TypeSourceInfo **tinfo) {
  793. DXASSERT_NOMSG(recordDecl != nullptr);
  794. DXASSERT_NOMSG(functionDecl != nullptr);
  795. FunctionProtoType::ExtProtoInfo functionExtInfo;
  796. functionExtInfo.TypeQuals = isConst ? Qualifiers::Const : 0;
  797. QualType functionQT = context.getFunctionType(
  798. resultType, args, functionExtInfo, ArrayRef<ParameterModifier>());
  799. DeclarationNameInfo declNameInfo(declarationName, NoLoc);
  800. *tinfo = context.getTrivialTypeSourceInfo(functionQT, NoLoc);
  801. DXASSERT_NOMSG(*tinfo != nullptr);
  802. *functionDecl = CXXMethodDecl::Create(
  803. context, recordDecl, NoLoc, declNameInfo, functionQT, *tinfo,
  804. StorageClass::SC_None, InlineSpecifiedFalse, IsConstexprFalse, NoLoc);
  805. DXASSERT_NOMSG(*functionDecl != nullptr);
  806. (*functionDecl)->setLexicalDeclContext(recordDecl);
  807. (*functionDecl)->setAccess(AccessSpecifier::AS_public);
  808. }
  809. CXXMethodDecl* hlsl::CreateObjectFunctionDeclarationWithParams(
  810. ASTContext& context,
  811. _In_ CXXRecordDecl* recordDecl,
  812. QualType resultType,
  813. ArrayRef<QualType> paramTypes,
  814. ArrayRef<StringRef> paramNames,
  815. DeclarationName declarationName,
  816. bool isConst)
  817. {
  818. DXASSERT_NOMSG(recordDecl != nullptr);
  819. DXASSERT_NOMSG(!resultType.isNull());
  820. DXASSERT_NOMSG(paramTypes.size() == paramNames.size());
  821. TypeSourceInfo* tinfo;
  822. CXXMethodDecl* functionDecl;
  823. CreateObjectFunctionDeclaration(context, recordDecl, resultType, paramTypes,
  824. declarationName, isConst, &functionDecl,
  825. &tinfo);
  826. // Create and associate parameters to method.
  827. SmallVector<ParmVarDecl *, 2> parmVarDecls;
  828. if (!paramTypes.empty()) {
  829. for (unsigned int i = 0; i < paramTypes.size(); ++i) {
  830. IdentifierInfo *argIi = &context.Idents.get(paramNames[i]);
  831. ParmVarDecl *parmVarDecl = ParmVarDecl::Create(
  832. context, functionDecl, NoLoc, NoLoc, argIi, paramTypes[i],
  833. context.getTrivialTypeSourceInfo(paramTypes[i], NoLoc),
  834. StorageClass::SC_None, nullptr);
  835. parmVarDecl->setScopeInfo(0, i);
  836. DXASSERT(parmVarDecl->getFunctionScopeIndex() == i,
  837. "otherwise failed to set correct index");
  838. parmVarDecls.push_back(parmVarDecl);
  839. }
  840. functionDecl->setParams(ArrayRef<ParmVarDecl *>(parmVarDecls));
  841. AssociateParametersToFunctionPrototype(tinfo, &parmVarDecls.front(),
  842. parmVarDecls.size());
  843. }
  844. recordDecl->addDecl(functionDecl);
  845. return functionDecl;
  846. }
  847. bool hlsl::IsIntrinsicOp(const clang::FunctionDecl *FD) {
  848. return FD != nullptr && FD->hasAttr<HLSLIntrinsicAttr>();
  849. }
  850. bool hlsl::GetIntrinsicOp(const clang::FunctionDecl *FD, unsigned &opcode,
  851. llvm::StringRef &group) {
  852. if (FD == nullptr || !FD->hasAttr<HLSLIntrinsicAttr>()) {
  853. return false;
  854. }
  855. HLSLIntrinsicAttr *A = FD->getAttr<HLSLIntrinsicAttr>();
  856. opcode = A->getOpcode();
  857. group = A->getGroup();
  858. return true;
  859. }
  860. bool hlsl::GetIntrinsicLowering(const clang::FunctionDecl *FD, llvm::StringRef &S) {
  861. if (FD == nullptr || !FD->hasAttr<HLSLIntrinsicAttr>()) {
  862. return false;
  863. }
  864. HLSLIntrinsicAttr *A = FD->getAttr<HLSLIntrinsicAttr>();
  865. S = A->getLowering();
  866. return true;
  867. }
  868. /// <summary>Parses a column or row digit.</summary>
  869. static
  870. bool TryParseColOrRowChar(const char digit, _Out_ int* count) {
  871. if ('1' <= digit && digit <= '4') {
  872. *count = digit - '0';
  873. return true;
  874. }
  875. *count = 0;
  876. return false;
  877. }
  878. /// <summary>Parses a matrix shorthand identifier (eg, float3x2).</summary>
  879. _Use_decl_annotations_
  880. bool hlsl::TryParseMatrixShorthand(
  881. const char* typeName,
  882. size_t typeNameLen,
  883. HLSLScalarType* parsedType,
  884. int* rowCount,
  885. int* colCount,
  886. const clang::LangOptions& langOptions
  887. )
  888. {
  889. //
  890. // Matrix shorthand format is PrimitiveTypeRxC, where R is the row count and C is the column count.
  891. // R and C should be between 1 and 4 inclusive.
  892. // x is a literal 'x' character.
  893. // PrimitiveType is one of the HLSLScalarTypeNames values.
  894. //
  895. if (TryParseMatrixOrVectorDimension(typeName, typeNameLen, rowCount, colCount, langOptions) &&
  896. *rowCount != 0 && *colCount != 0) {
  897. // compare scalar component
  898. HLSLScalarType type = FindScalarTypeByName(typeName, typeNameLen-3, langOptions);
  899. if (type!= HLSLScalarType_unknown) {
  900. *parsedType = type;
  901. return true;
  902. }
  903. }
  904. // Unable to parse.
  905. return false;
  906. }
  907. /// <summary>Parses a vector shorthand identifier (eg, float3).</summary>
  908. _Use_decl_annotations_
  909. bool hlsl::TryParseVectorShorthand(
  910. const char* typeName,
  911. size_t typeNameLen,
  912. HLSLScalarType* parsedType,
  913. int* elementCount,
  914. const clang::LangOptions& langOptions
  915. )
  916. {
  917. // At least *something*N characters necessary, where something is at least 'int'
  918. if (TryParseColOrRowChar(typeName[typeNameLen - 1], elementCount)) {
  919. // compare scalar component
  920. HLSLScalarType type = FindScalarTypeByName(typeName, typeNameLen-1, langOptions);
  921. if (type!= HLSLScalarType_unknown) {
  922. *parsedType = type;
  923. return true;
  924. }
  925. }
  926. // Unable to parse.
  927. return false;
  928. }
  929. /// <summary>Parses a hlsl scalar type (e.g min16float, uint3x4) </summary>
  930. _Use_decl_annotations_
  931. bool hlsl::TryParseScalar(
  932. _In_count_(typenameLen)
  933. const char* typeName,
  934. size_t typeNameLen,
  935. _Out_ HLSLScalarType *parsedType,
  936. _In_ const clang::LangOptions& langOptions) {
  937. HLSLScalarType type = FindScalarTypeByName(typeName, typeNameLen, langOptions);
  938. if (type!= HLSLScalarType_unknown) {
  939. *parsedType = type;
  940. return true;
  941. }
  942. return false; // unable to parse
  943. }
  944. /// <summary>Parse any (scalar, vector, matrix) hlsl types (e.g float, int3x4, uint2) </summary>
  945. _Use_decl_annotations_
  946. bool hlsl::TryParseAny(
  947. _In_count_(typenameLen)
  948. const char* typeName,
  949. size_t typeNameLen,
  950. _Out_ HLSLScalarType *parsedType,
  951. int *rowCount,
  952. int *colCount,
  953. _In_ const clang::LangOptions& langOptions) {
  954. // at least 'int'
  955. const size_t MinValidLen = 3;
  956. if (typeNameLen >= MinValidLen) {
  957. TryParseMatrixOrVectorDimension(typeName, typeNameLen, rowCount, colCount, langOptions);
  958. int suffixLen = *colCount == 0 ? 0 :
  959. *rowCount == 0 ? 1 : 3;
  960. HLSLScalarType type = FindScalarTypeByName(typeName, typeNameLen-suffixLen, langOptions);
  961. if (type!= HLSLScalarType_unknown) {
  962. *parsedType = type;
  963. return true;
  964. }
  965. }
  966. return false;
  967. }
  968. /// <summary>Parse any kind of dimension for vector or matrix (e.g 4,3 in int4x3).
  969. /// If it's a matrix type, rowCount and colCount will be nonzero. If it's a vector type, colCount is 0.
  970. /// Otherwise both rowCount and colCount is 0. Returns true if either matrix or vector dimensions detected. </summary>
  971. _Use_decl_annotations_
  972. bool hlsl::TryParseMatrixOrVectorDimension(
  973. _In_count_(typeNameLen)
  974. const char *typeName,
  975. size_t typeNameLen,
  976. _Out_opt_ int *rowCount,
  977. _Out_opt_ int *colCount,
  978. _In_ const clang::LangOptions& langOptions) {
  979. *rowCount = 0;
  980. *colCount = 0;
  981. size_t MinValidLen = 3; // at least int
  982. if (typeNameLen > MinValidLen) {
  983. if (TryParseColOrRowChar(typeName[typeNameLen - 1], colCount)) {
  984. // Try parse matrix
  985. if (typeName[typeNameLen - 2] == 'x')
  986. TryParseColOrRowChar(typeName[typeNameLen - 3], rowCount);
  987. return true;
  988. }
  989. }
  990. return false;
  991. }
  992. /// <summary>Creates a typedef for a matrix shorthand (eg, float3x2).</summary>
  993. TypedefDecl* hlsl::CreateMatrixSpecializationShorthand(
  994. ASTContext& context,
  995. QualType matrixSpecialization,
  996. HLSLScalarType scalarType,
  997. size_t rowCount,
  998. size_t colCount)
  999. {
  1000. DXASSERT(rowCount <= 4, "else caller didn't validate rowCount");
  1001. DXASSERT(colCount <= 4, "else caller didn't validate colCount");
  1002. char typeName[64];
  1003. sprintf_s(typeName, _countof(typeName), "%s%ux%u",
  1004. HLSLScalarTypeNames[scalarType], (unsigned)rowCount, (unsigned)colCount);
  1005. IdentifierInfo& typedefId = context.Idents.get(StringRef(typeName), tok::TokenKind::identifier);
  1006. DeclContext* currentDeclContext = context.getTranslationUnitDecl();
  1007. TypedefDecl* decl = TypedefDecl::Create(context, currentDeclContext, NoLoc, NoLoc, &typedefId,
  1008. context.getTrivialTypeSourceInfo(matrixSpecialization, NoLoc));
  1009. decl->setImplicit(true);
  1010. currentDeclContext->addDecl(decl);
  1011. return decl;
  1012. }
  1013. /// <summary>Creates a typedef for a vector shorthand (eg, float3).</summary>
  1014. TypedefDecl* hlsl::CreateVectorSpecializationShorthand(
  1015. ASTContext& context,
  1016. QualType vectorSpecialization,
  1017. HLSLScalarType scalarType,
  1018. size_t colCount)
  1019. {
  1020. DXASSERT(colCount <= 4, "else caller didn't validate colCount");
  1021. char typeName[64];
  1022. sprintf_s(typeName, _countof(typeName), "%s%u",
  1023. HLSLScalarTypeNames[scalarType], (unsigned)colCount);
  1024. IdentifierInfo& typedefId = context.Idents.get(StringRef(typeName), tok::TokenKind::identifier);
  1025. DeclContext* currentDeclContext = context.getTranslationUnitDecl();
  1026. TypedefDecl* decl = TypedefDecl::Create(context, currentDeclContext, NoLoc, NoLoc, &typedefId,
  1027. context.getTrivialTypeSourceInfo(vectorSpecialization, NoLoc));
  1028. decl->setImplicit(true);
  1029. currentDeclContext->addDecl(decl);
  1030. return decl;
  1031. }
  1032. llvm::ArrayRef<hlsl::UnusualAnnotation*>
  1033. hlsl::UnusualAnnotation::CopyToASTContextArray(
  1034. clang::ASTContext& Context, hlsl::UnusualAnnotation** begin, size_t count) {
  1035. if (count == 0) {
  1036. return llvm::ArrayRef<hlsl::UnusualAnnotation*>();
  1037. }
  1038. UnusualAnnotation** arr = ::new (Context) UnusualAnnotation*[count];
  1039. for (size_t i = 0; i < count; ++i) {
  1040. arr[i] = begin[i]->CopyToASTContext(Context);
  1041. }
  1042. return llvm::ArrayRef<hlsl::UnusualAnnotation*>(arr, count);
  1043. }
  1044. UnusualAnnotation* hlsl::UnusualAnnotation::CopyToASTContext(ASTContext& Context) {
  1045. // All UnusualAnnotation instances can be blitted.
  1046. size_t instanceSize;
  1047. switch (Kind) {
  1048. case UA_RegisterAssignment:
  1049. instanceSize = sizeof(hlsl::RegisterAssignment);
  1050. break;
  1051. case UA_ConstantPacking:
  1052. instanceSize = sizeof(hlsl::ConstantPacking);
  1053. break;
  1054. default:
  1055. DXASSERT(Kind == UA_SemanticDecl, "Kind == UA_SemanticDecl -- otherwise switch is incomplete");
  1056. instanceSize = sizeof(hlsl::SemanticDecl);
  1057. break;
  1058. }
  1059. void* result = Context.Allocate(instanceSize);
  1060. memcpy(result, this, instanceSize);
  1061. return (UnusualAnnotation*)result;
  1062. }
  1063. static bool HasTessFactorSemantic(const ValueDecl *decl) {
  1064. for (const UnusualAnnotation *it : decl->getUnusualAnnotations()) {
  1065. switch (it->getKind()) {
  1066. case UnusualAnnotation::UA_SemanticDecl: {
  1067. const SemanticDecl *sd = cast<SemanticDecl>(it);
  1068. const Semantic *pSemantic = Semantic::GetByName(sd->SemanticName);
  1069. if (pSemantic && pSemantic->GetKind() == Semantic::Kind::TessFactor)
  1070. return true;
  1071. }
  1072. }
  1073. }
  1074. return false;
  1075. }
  1076. static bool HasTessFactorSemanticRecurse(const ValueDecl *decl, QualType Ty) {
  1077. if (Ty->isBuiltinType() || hlsl::IsHLSLVecMatType(Ty))
  1078. return false;
  1079. if (const RecordType *RT = Ty->getAsStructureType()) {
  1080. RecordDecl *RD = RT->getDecl();
  1081. for (FieldDecl *fieldDecl : RD->fields()) {
  1082. if (HasTessFactorSemanticRecurse(fieldDecl, fieldDecl->getType()))
  1083. return true;
  1084. }
  1085. return false;
  1086. }
  1087. if (const clang::ArrayType *arrayTy = Ty->getAsArrayTypeUnsafe())
  1088. return HasTessFactorSemantic(decl);
  1089. return false;
  1090. }
  1091. bool ASTContext::IsPatchConstantFunctionDecl(const FunctionDecl *FD) const {
  1092. // This checks whether the function is structurally capable of being a patch
  1093. // constant function, not whether it is in fact the patch constant function
  1094. // for the entry point of a compiled hull shader (which may not have been
  1095. // seen yet). So the answer is conservative.
  1096. if (!FD->getReturnType()->isVoidType()) {
  1097. // Try to find TessFactor in return type.
  1098. if (HasTessFactorSemanticRecurse(FD, FD->getReturnType()))
  1099. return true;
  1100. }
  1101. // Try to find TessFactor in out param.
  1102. for (const ParmVarDecl *param : FD->params()) {
  1103. if (param->hasAttr<HLSLOutAttr>()) {
  1104. if (HasTessFactorSemanticRecurse(param, param->getType()))
  1105. return true;
  1106. }
  1107. }
  1108. return false;
  1109. }