================
@@ -1000,6 +1006,65 @@ void CGHLSLRuntime::addHLSLBufferLayoutType(const 
RecordType *StructType,
   LayoutTypes[StructType] = LayoutTy;
 }
 
+static std::optional<SPIRVExecutionMode>
+getSPIRVDerivativeGroupMode(CodeGenModule &CGM, const Function &F) {
+  StringRef NumThreads = 
F.getFnAttribute("hlsl.numthreads").getValueAsString();
+  SmallVector<StringRef, 3> Dimensions;
+  NumThreads.split(Dimensions, ',');
+  assert(Dimensions.size() == 3 && "expected three numthreads dimensions");
+  std::array<uint32_t, 3> Threads;
+  for (auto [Dimension, Thread] : llvm::zip(Dimensions, Threads)) {
+    [[maybe_unused]] bool Invalid = Dimension.getAsInteger(10, Thread);
+    assert(!Invalid && "expected an integer numthreads dimension");
+  }
+  bool IsLinear = Threads[1] == 1 && Threads[2] == 1;
+  if (IsLinear ? (uint64_t(Threads[0]) * Threads[1] * Threads[2]) % 4 != 0
+               : Threads[0] % 2 != 0 || Threads[1] % 2 != 0) {
+    CGM.getDiags().Report(diag::err_hlsl_spirv_derivative_group_numthreads)
+        << F.getName() << IsLinear;
+    return std::nullopt;
+  }
+  return IsLinear ? SPIRVExecutionMode::DerivativeGroupLinearKHR
+                  : SPIRVExecutionMode::DerivativeGroupQuadsKHR;
+}
+
+static void addSPIRVQuadAllExecutionModes(CodeGenModule &CGM) {
+  llvm::Module &M = CGM.getModule();
+  Function *QuadAll =
+      Intrinsic::getDeclarationIfExists(&M, Intrinsic::spv_quad_all);
+  if (!QuadAll)
+    return;
+
+  SmallVector<Function *, 8> Worklist{QuadAll};
+  SmallPtrSet<Function *, 16> Visited;
+  IRBuilder<> B(M);
+  while (!Worklist.empty()) {
+    Function *F = Worklist.pop_back_val();
+    if (!Visited.insert(F).second)
+      continue;
+
+    if (F->hasFnAttribute("hlsl.numthreads")) {
+      std::optional<SPIRVExecutionMode> Mode =
+          getSPIRVDerivativeGroupMode(CGM, *F);
+      if (!Mode) {
----------------
hekota wrote:

I think it would be best to have just the `numthreads` value parsing in a 
helper function, but the rest of the validation should probably stay here, as 
it is specific to the QuadAll call. Splitting the diagnostic over two functions 
does not seem right either.

How about this?

```suggestion
    Attr NumThAttr = F->hasFnAttribute("hlsl.numthreads");
    if (NumThAttr.isValid()) {
      std::array<unsigned, 3> Threads = 
parseNumThreads(NumThAttr->getValueAsString());
      bool IsLinear = Threads[1] == 1 && Threads[2] == 1;
      // Do validation of the Threads here, add comments explaining why, pick 
the execution mode.
      // If validation fails:
      CGM.getDiags().Report(diag::err_hlsl_spirv_derivative_group_numthreads)
        << F.getName() << IsLinear;
```

https://github.com/llvm/llvm-project/pull/240645
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to