[llvm-branch-commits] [mlir] [MLIR][OpenMP] Clause-based OpenMP operation definition (PR #92523)

2024-06-28 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis approved this pull request.

I'm happy with the patch. Thanks for the good work :)

https://github.com/llvm/llvm-project/pull/92523
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] release/19.x: [clang][OpenMP] Propoagate debug location to OMPIRBuilder reduction codegen (#100358) (PR #100381)

2024-07-24 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis approved this pull request.


https://github.com/llvm/llvm-project/pull/100381
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [mlir] [OpenMP]Update use_device_clause lowering (PR #101707)

2024-08-02 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis created 
https://github.com/llvm/llvm-project/pull/101707

This patch updates the use_device_ptr and use_device_addr clauses to use the 
mapInfoOps for lowering. This allows all the types that are handle by the map 
clauses such as derived types to also be supported by the use_device_clauses.

This is patch 2/2 in a series of patches.

>From 945337b26e6c5ed3ff562b764ca4f582ee106e85 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Fri, 2 Aug 2024 17:11:21 +0100
Subject: [PATCH] [OpenMP]Update use_device_clause lowering

This patch updates the use_device_ptr and use_device_addr clauses to use the 
mapInfoOps for lowering. This allows all the types that are handle by the map 
clauses such as derived types to also be supported by the use_device_clauses.

This is patch 2/2 in a series of patches.
---
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp |   2 +-
 .../OpenMP/OpenMPToLLVMIRTranslation.cpp  | 284 ++
 mlir/test/Target/LLVMIR/omptarget-llvm.mlir   |  16 +-
 .../openmp-target-use-device-nested.mlir  |  27 ++
 4 files changed, 194 insertions(+), 135 deletions(-)
 create mode 100644 mlir/test/Target/LLVMIR/openmp-target-use-device-nested.mlir

diff --git a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp 
b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
index 77e350e7276ab..5350daa34b6bb 100644
--- a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -6351,7 +6351,7 @@ OpenMPIRBuilder::InsertPointTy 
OpenMPIRBuilder::createTargetData(
   // Disable TargetData CodeGen on Device pass.
   if (Config.IsTargetDevice.value_or(false)) {
 if (BodyGenCB)
-  Builder.restoreIP(BodyGenCB(Builder.saveIP(), BodyGenTy::NoPriv));
+  Builder.restoreIP(BodyGenCB(CodeGenIP, BodyGenTy::NoPriv));
 return Builder.saveIP();
   }
 
diff --git 
a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp 
b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index ddee117838697..dd2ecbb1f3532 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -2110,6 +2110,8 @@ getRefPtrIfDeclareTarget(mlir::Value value,
 struct MapInfoData : llvm::OpenMPIRBuilder::MapInfosTy {
   llvm::SmallVector IsDeclareTarget;
   llvm::SmallVector IsAMember;
+  // Identify if mapping was added by mapClause or use_device clauses.
+  llvm::SmallVector IsAMapping;
   llvm::SmallVector MapClause;
   llvm::SmallVector OriginalValue;
   // Stripped off array/pointer to get the underlying
@@ -2193,62 +2195,125 @@ llvm::Value *getSizeInBytes(DataLayout &dl, const 
mlir::Type &type,
   return builder.getInt64(dl.getTypeSizeInBits(type) / 8);
 }
 
-void collectMapDataFromMapVars(MapInfoData &mapData,
-   llvm::SmallVectorImpl &mapVars,
-   LLVM::ModuleTranslation &moduleTranslation,
-   DataLayout &dl, llvm::IRBuilderBase &builder) {
+void collectMapDataFromMapOperands(
+MapInfoData &mapData, llvm::SmallVectorImpl &mapVars,
+LLVM::ModuleTranslation &moduleTranslation, DataLayout &dl,
+llvm::IRBuilderBase &builder,
+const llvm::ArrayRef &useDevPtrOperands = {},
+const llvm::ArrayRef &useDevAddrOperands = {}) {
+  // Process MapOperands
   for (mlir::Value mapValue : mapVars) {
-if (auto mapOp = mlir::dyn_cast_if_present(
-mapValue.getDefiningOp())) {
-  mlir::Value offloadPtr =
-  mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
-  mapData.OriginalValue.push_back(
-  moduleTranslation.lookupValue(offloadPtr));
-  mapData.Pointers.push_back(mapData.OriginalValue.back());
-
-  if (llvm::Value *refPtr =
-  getRefPtrIfDeclareTarget(offloadPtr,
-   moduleTranslation)) { // declare target
-mapData.IsDeclareTarget.push_back(true);
-mapData.BasePointers.push_back(refPtr);
-  } else { // regular mapped variable
-mapData.IsDeclareTarget.push_back(false);
-mapData.BasePointers.push_back(mapData.OriginalValue.back());
-  }
+auto mapOp = mlir::cast(mapValue.getDefiningOp());
+mlir::Value offloadPtr =
+mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
+mapData.OriginalValue.push_back(moduleTranslation.lookupValue(offloadPtr));
+mapData.Pointers.push_back(mapData.OriginalValue.back());
+
+if (llvm::Value *refPtr =
+getRefPtrIfDeclareTarget(offloadPtr,
+ moduleTranslation)) { // declare target
+  mapData.IsDeclareTarget.push_back(true);
+  mapData.BasePointers.push_back(refPtr);
+} else { // regular mapped variable
+  mapData.IsDeclareTarget.push_back(false);
+  mapData.BasePointers.push_back(mapData.OriginalValue.back());
+}
 
-  mapData.BaseType.push_back(
-  moduleTranslation.conv

[llvm-branch-commits] [llvm] [mlir] [OpenMP]Update use_device_clause lowering (PR #101707)

2024-08-06 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/101707

>From 9db19516d50cd4f6a597fbd811419af98859315a Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Fri, 2 Aug 2024 17:11:21 +0100
Subject: [PATCH] [OpenMP]Update use_device_clause lowering

This patch updates the use_device_ptr and use_device_addr clauses to use the 
mapInfoOps for lowering. This allows all the types that are handle by the map 
clauses such as derived types to also be supported by the use_device_clauses.

This is patch 2/2 in a series of patches.
---
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp |   2 +-
 .../OpenMP/OpenMPToLLVMIRTranslation.cpp  | 284 ++
 mlir/test/Target/LLVMIR/omptarget-llvm.mlir   |  16 +-
 .../openmp-target-use-device-nested.mlir  |  27 ++
 4 files changed, 194 insertions(+), 135 deletions(-)
 create mode 100644 mlir/test/Target/LLVMIR/openmp-target-use-device-nested.mlir

diff --git a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp 
b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
index afbb9f9cc16430..4793711a986e97 100644
--- a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -6351,7 +6351,7 @@ OpenMPIRBuilder::InsertPointTy 
OpenMPIRBuilder::createTargetData(
   // Disable TargetData CodeGen on Device pass.
   if (Config.IsTargetDevice.value_or(false)) {
 if (BodyGenCB)
-  Builder.restoreIP(BodyGenCB(Builder.saveIP(), BodyGenTy::NoPriv));
+  Builder.restoreIP(BodyGenCB(CodeGenIP, BodyGenTy::NoPriv));
 return Builder.saveIP();
   }
 
diff --git 
a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp 
b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index 458d05d5059db7..78c460c50cbe5e 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -2110,6 +2110,8 @@ getRefPtrIfDeclareTarget(mlir::Value value,
 struct MapInfoData : llvm::OpenMPIRBuilder::MapInfosTy {
   llvm::SmallVector IsDeclareTarget;
   llvm::SmallVector IsAMember;
+  // Identify if mapping was added by mapClause or use_device clauses.
+  llvm::SmallVector IsAMapping;
   llvm::SmallVector MapClause;
   llvm::SmallVector OriginalValue;
   // Stripped off array/pointer to get the underlying
@@ -2193,62 +2195,125 @@ llvm::Value *getSizeInBytes(DataLayout &dl, const 
mlir::Type &type,
   return builder.getInt64(dl.getTypeSizeInBits(type) / 8);
 }
 
-void collectMapDataFromMapVars(MapInfoData &mapData,
-   llvm::SmallVectorImpl &mapVars,
-   LLVM::ModuleTranslation &moduleTranslation,
-   DataLayout &dl, llvm::IRBuilderBase &builder) {
+void collectMapDataFromMapOperands(
+MapInfoData &mapData, llvm::SmallVectorImpl &mapVars,
+LLVM::ModuleTranslation &moduleTranslation, DataLayout &dl,
+llvm::IRBuilderBase &builder,
+const llvm::ArrayRef &useDevPtrOperands = {},
+const llvm::ArrayRef &useDevAddrOperands = {}) {
+  // Process MapOperands
   for (mlir::Value mapValue : mapVars) {
-if (auto mapOp = mlir::dyn_cast_if_present(
-mapValue.getDefiningOp())) {
-  mlir::Value offloadPtr =
-  mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
-  mapData.OriginalValue.push_back(
-  moduleTranslation.lookupValue(offloadPtr));
-  mapData.Pointers.push_back(mapData.OriginalValue.back());
-
-  if (llvm::Value *refPtr =
-  getRefPtrIfDeclareTarget(offloadPtr,
-   moduleTranslation)) { // declare target
-mapData.IsDeclareTarget.push_back(true);
-mapData.BasePointers.push_back(refPtr);
-  } else { // regular mapped variable
-mapData.IsDeclareTarget.push_back(false);
-mapData.BasePointers.push_back(mapData.OriginalValue.back());
-  }
+auto mapOp = mlir::cast(mapValue.getDefiningOp());
+mlir::Value offloadPtr =
+mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
+mapData.OriginalValue.push_back(moduleTranslation.lookupValue(offloadPtr));
+mapData.Pointers.push_back(mapData.OriginalValue.back());
+
+if (llvm::Value *refPtr =
+getRefPtrIfDeclareTarget(offloadPtr,
+ moduleTranslation)) { // declare target
+  mapData.IsDeclareTarget.push_back(true);
+  mapData.BasePointers.push_back(refPtr);
+} else { // regular mapped variable
+  mapData.IsDeclareTarget.push_back(false);
+  mapData.BasePointers.push_back(mapData.OriginalValue.back());
+}
 
-  mapData.BaseType.push_back(
-  moduleTranslation.convertType(mapOp.getVarType()));
-  mapData.Sizes.push_back(
-  getSizeInBytes(dl, mapOp.getVarType(), mapOp, 
mapData.Pointers.back(),
- mapData.BaseType.back(), builder, moduleTranslation));
-  mapData.MapClause.push_back(mapOp.getOpera

[llvm-branch-commits] [flang] [mlir] [OpenMP][MLIR] Set omp.composite attr for composite loop wrappers and add verifier checks (PR #102341)

2024-08-07 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis created 
https://github.com/llvm/llvm-project/pull/102341

This patch sets the omp.composite unit attr for composite wrapper ops and also 
add appropriate checks to the verifiers of supported ops for the 
presence/absence of the attribute.

This is patch 2/2 in a series of patches.


>From 9e43d5e608935add740e078e74e1884270775862 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 5 Aug 2024 15:31:25 +0100
Subject: [PATCH 1/3] [MLIR][OpenMP] Add a new ComposableLoopWrapperInterface
 to check and set a composite unitAttr.

---
 mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td |  9 +++--
 .../Dialect/OpenMP/OpenMPOpsInterfaces.td | 34 +++
 2 files changed, 41 insertions(+), 2 deletions(-)

diff --git a/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td 
b/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
index 68f92e6952694b..44210025dfe18b 100644
--- a/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
+++ b/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
@@ -129,6 +129,7 @@ def PrivateClauseOp : OpenMP_Op<"private", 
[IsolatedFromAbove, RecipeInterface]>
 def ParallelOp : OpenMP_Op<"parallel", traits = [
 AttrSizedOperandSegments, AutomaticAllocationScope,
 DeclareOpInterfaceMethods,
+DeclareOpInterfaceMethods,
 DeclareOpInterfaceMethods,
 RecursiveMemoryEffects
   ], clauses = [
@@ -357,6 +358,7 @@ def LoopNestOp : OpenMP_Op<"loop_nest", traits = [
 
 def WsloopOp : OpenMP_Op<"wsloop", traits = [
 AttrSizedOperandSegments, DeclareOpInterfaceMethods,
+DeclareOpInterfaceMethods,
 RecursiveMemoryEffects, SingleBlock
   ], clauses = [
 OpenMP_AllocateClauseSkip,
@@ -433,6 +435,7 @@ def WsloopOp : OpenMP_Op<"wsloop", traits = [
 
 def SimdOp : OpenMP_Op<"simd", traits = [
 AttrSizedOperandSegments, DeclareOpInterfaceMethods,
+DeclareOpInterfaceMethods,
 RecursiveMemoryEffects, SingleBlock
   ], clauses = [
 OpenMP_AlignedClause, OpenMP_IfClause, OpenMP_LinearClause,
@@ -500,6 +503,7 @@ def YieldOp : OpenMP_Op<"yield",
 
//===--===//
 def DistributeOp : OpenMP_Op<"distribute", traits = [
 AttrSizedOperandSegments, DeclareOpInterfaceMethods,
+DeclareOpInterfaceMethods,
 RecursiveMemoryEffects, SingleBlock
   ], clauses = [
 OpenMP_AllocateClause, OpenMP_DistScheduleClause, OpenMP_OrderClause,
@@ -587,8 +591,9 @@ def TaskOp : OpenMP_Op<"task", traits = [
 
 def TaskloopOp : OpenMP_Op<"taskloop", traits = [
 AttrSizedOperandSegments, AutomaticAllocationScope,
-DeclareOpInterfaceMethods, RecursiveMemoryEffects,
-SingleBlock
+DeclareOpInterfaceMethods,
+DeclareOpInterfaceMethods,
+RecursiveMemoryEffects, SingleBlock
   ], clauses = [
 OpenMP_AllocateClause, OpenMP_FinalClause, OpenMP_GrainsizeClause,
 OpenMP_IfClause, OpenMP_InReductionClauseSkip,
diff --git a/mlir/include/mlir/Dialect/OpenMP/OpenMPOpsInterfaces.td 
b/mlir/include/mlir/Dialect/OpenMP/OpenMPOpsInterfaces.td
index 2d1de37239c82a..50394eaf236f94 100644
--- a/mlir/include/mlir/Dialect/OpenMP/OpenMPOpsInterfaces.td
+++ b/mlir/include/mlir/Dialect/OpenMP/OpenMPOpsInterfaces.td
@@ -142,6 +142,40 @@ def LoopWrapperInterface : 
OpInterface<"LoopWrapperInterface"> {
   ];
 }
 
+def ComposableLoopWrapperInterface : 
OpInterface<"ComposableLoopWrapperInterface"> {
+  let description = [{
+OpenMP operations that can wrap a single loop nest. When taking a wrapper
+role, these operations must only contain a single region with a single 
block
+in which there's a single operation and a terminator. That nested operation
+must be another loop wrapper or an `omp.loop_nest`.
+  }];
+
+  let cppNamespace = "::mlir::omp";
+
+  let methods = [
+InterfaceMethod<
+  /*description=*/[{
+Check whether the operation is composable.
+  }],
+  /*retTy=*/"bool",
+  /*methodName=*/"isComposite",
+  (ins ), [{}], [{
+return $_op->hasAttr("omp.composite");
+  }]
+>,
+InterfaceMethod<
+  /*description=*/[{
+Set the CompositeAttr for the op.
+  }],
+  /*retTy=*/"void",
+  /*methodName=*/"setComposite",
+  (ins), [{}], [{
+$_op->setDiscardableAttr("omp.composite", 
mlir::UnitAttr::get($_op->getContext()));
+  }]
+>
+  ];
+}
+
 def DeclareTargetInterface : OpInterface<"DeclareTargetInterface"> {
   let description = [{
 OpenMP operations that support declare target have this interface.

>From 1ce8a0500e95b0bcd5d2e64b1cbcfe3f216a048f Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Tue, 6 Aug 2024 13:25:06 +0100
Subject: [PATCH 2/3] Address reviewer comments.

---
 mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td | 19 ++
 .../Dialect/OpenMP/OpenMPOpsInterfaces.td | 20 ++-
 2 files changed, 22 insertions(+), 17 deletions(-)

diff --git a/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td 
b/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
index 4421

[llvm-branch-commits] [flang] [mlir] [OpenMP][MLIR] Set omp.composite attr for composite loop wrappers and add verifier checks (PR #102341)

2024-08-08 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/102341

>From ba8cf358a98cfcce6b1239ac88391bc25bcc7197 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Wed, 7 Aug 2024 18:31:08 +0100
Subject: [PATCH 1/2] [OpenMP][MLIR] Set omp.composite attr for composite loop
 wrappers and add verifier checks

This patch sets the omp.composite unit attr for composite wrapper ops and also 
add appropriate checks to the verifiers of supported ops for the 
presence/absence of the attribute.
---
 flang/lib/Lower/OpenMP/OpenMP.cpp|  8 +
 mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp | 32 
 2 files changed, 40 insertions(+)

diff --git a/flang/lib/Lower/OpenMP/OpenMP.cpp 
b/flang/lib/Lower/OpenMP/OpenMP.cpp
index bbde77c14f36a1..3b18e7b3ecf80e 100644
--- a/flang/lib/Lower/OpenMP/OpenMP.cpp
+++ b/flang/lib/Lower/OpenMP/OpenMP.cpp
@@ -2063,10 +2063,14 @@ static void genCompositeDistributeSimd(
   // TODO: Populate entry block arguments with private variables.
   auto distributeOp = genWrapperOp(
   converter, loc, distributeClauseOps, /*blockArgTypes=*/{});
+  llvm::cast(distributeOp.getOperation())
+  .setComposite(/*val=*/true);
 
   // TODO: Populate entry block arguments with reduction and private variables.
   auto simdOp = genWrapperOp(converter, loc, simdClauseOps,
 /*blockArgTypes=*/{});
+  llvm::cast(simdOp.getOperation())
+  .setComposite(/*val=*/true);
 
   // Construct wrapper entry block list and associated symbols. It is important
   // that the symbol order and the block argument order match, so that the
@@ -2111,10 +2115,14 @@ static void genCompositeDoSimd(lower::AbstractConverter 
&converter,
   // TODO: Add private variables to entry block arguments.
   auto wsloopOp = genWrapperOp(
   converter, loc, wsloopClauseOps, wsloopReductionTypes);
+  llvm::cast(wsloopOp.getOperation())
+  .setComposite(/*val=*/true);
 
   // TODO: Populate entry block arguments with reduction and private variables.
   auto simdOp = genWrapperOp(converter, loc, simdClauseOps,
 /*blockArgTypes=*/{});
+  llvm::cast(simdOp.getOperation())
+  .setComposite(/*val=*/true);
 
   // Construct wrapper entry block list and associated symbols. It is important
   // that the symbol and block argument order match, so that the symbol-value
diff --git a/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp 
b/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
index 11780f84697b15..641fbb5a1418f6 100644
--- a/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
+++ b/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
@@ -1546,6 +1546,9 @@ LogicalResult ParallelOp::verify() {
 if (!isWrapper())
   return emitOpError() << "must take a loop wrapper role if nested inside "
   "of 'omp.distribute'";
+if (!llvm::cast(getOperation()).isComposite())
+  return emitError()
+ << "'omp.composite' attribute missing from composite wrapper";
 
 if (LoopWrapperInterface nested = getNestedWrapper()) {
   // Check for the allowed leaf constructs that may appear in a composite
@@ -1555,6 +1558,9 @@ LogicalResult ParallelOp::verify() {
 } else {
   return emitOpError() << "must not wrap an 'omp.loop_nest' directly";
 }
+  } else if (llvm::cast(getOperation()).isComposite()) {
+return emitError()
+   << "'omp.composite' attribute present in non-composite wrapper";
   }
 
   if (getAllocateVars().size() != getAllocatorVars().size())
@@ -1749,10 +1755,18 @@ LogicalResult WsloopOp::verify() {
 return emitOpError() << "must be a loop wrapper";
 
   if (LoopWrapperInterface nested = getNestedWrapper()) {
+if (!llvm::cast(getOperation()).isComposite())
+  return emitError()
+ << "'omp.composite' attribute missing from composite wrapper";
+
 // Check for the allowed leaf constructs that may appear in a composite
 // construct directly after DO/FOR.
 if (!isa(nested))
   return emitError() << "only supported nested wrapper is 'omp.simd'";
+
+  } else if (llvm::cast(getOperation()).isComposite()) {
+return emitError()
+   << "'omp.composite' attribute present in non-composite wrapper";
   }
 
   return verifyReductionVarList(*this, getReductionSyms(), getReductionVars(),
@@ -1796,6 +1810,10 @@ LogicalResult SimdOp::verify() {
   if (getNestedWrapper())
 return emitOpError() << "must wrap an 'omp.loop_nest' directly";
 
+  if (llvm::cast(getOperation()).isComposite())
+return emitError()
+   << "'omp.composite' attribute present in non-composite wrapper";
+
   return success();
 }
 
@@ -1825,11 +1843,17 @@ LogicalResult DistributeOp::verify() {
 return emitOpError() << "must be a loop wrapper";
 
   if (LoopWrapperInterface nested = getNestedWrapper()) {
+if (!llvm::cast(getOperation()).isComposite())
+  return emitError()
+ << "'omp.composite' at

[llvm-branch-commits] [flang] [mlir] [OpenMP][MLIR] Set omp.composite attr for composite loop wrappers and add verifier checks (PR #102341)

2024-08-08 Thread Akash Banerjee via llvm-branch-commits

TIFitis wrote:

Thanks @skatrak for the review, I've updated the PR to address the comments.

https://github.com/llvm/llvm-project/pull/102341
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [mlir] [OpenMP][MLIR] Set omp.composite attr for composite loop wrappers and add verifier checks (PR #102341)

2024-08-12 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/102341

>From ba8cf358a98cfcce6b1239ac88391bc25bcc7197 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Wed, 7 Aug 2024 18:31:08 +0100
Subject: [PATCH 1/3] [OpenMP][MLIR] Set omp.composite attr for composite loop
 wrappers and add verifier checks

This patch sets the omp.composite unit attr for composite wrapper ops and also 
add appropriate checks to the verifiers of supported ops for the 
presence/absence of the attribute.
---
 flang/lib/Lower/OpenMP/OpenMP.cpp|  8 +
 mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp | 32 
 2 files changed, 40 insertions(+)

diff --git a/flang/lib/Lower/OpenMP/OpenMP.cpp 
b/flang/lib/Lower/OpenMP/OpenMP.cpp
index bbde77c14f36a1..3b18e7b3ecf80e 100644
--- a/flang/lib/Lower/OpenMP/OpenMP.cpp
+++ b/flang/lib/Lower/OpenMP/OpenMP.cpp
@@ -2063,10 +2063,14 @@ static void genCompositeDistributeSimd(
   // TODO: Populate entry block arguments with private variables.
   auto distributeOp = genWrapperOp(
   converter, loc, distributeClauseOps, /*blockArgTypes=*/{});
+  llvm::cast(distributeOp.getOperation())
+  .setComposite(/*val=*/true);
 
   // TODO: Populate entry block arguments with reduction and private variables.
   auto simdOp = genWrapperOp(converter, loc, simdClauseOps,
 /*blockArgTypes=*/{});
+  llvm::cast(simdOp.getOperation())
+  .setComposite(/*val=*/true);
 
   // Construct wrapper entry block list and associated symbols. It is important
   // that the symbol order and the block argument order match, so that the
@@ -2111,10 +2115,14 @@ static void genCompositeDoSimd(lower::AbstractConverter 
&converter,
   // TODO: Add private variables to entry block arguments.
   auto wsloopOp = genWrapperOp(
   converter, loc, wsloopClauseOps, wsloopReductionTypes);
+  llvm::cast(wsloopOp.getOperation())
+  .setComposite(/*val=*/true);
 
   // TODO: Populate entry block arguments with reduction and private variables.
   auto simdOp = genWrapperOp(converter, loc, simdClauseOps,
 /*blockArgTypes=*/{});
+  llvm::cast(simdOp.getOperation())
+  .setComposite(/*val=*/true);
 
   // Construct wrapper entry block list and associated symbols. It is important
   // that the symbol and block argument order match, so that the symbol-value
diff --git a/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp 
b/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
index 11780f84697b15..641fbb5a1418f6 100644
--- a/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
+++ b/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
@@ -1546,6 +1546,9 @@ LogicalResult ParallelOp::verify() {
 if (!isWrapper())
   return emitOpError() << "must take a loop wrapper role if nested inside "
   "of 'omp.distribute'";
+if (!llvm::cast(getOperation()).isComposite())
+  return emitError()
+ << "'omp.composite' attribute missing from composite wrapper";
 
 if (LoopWrapperInterface nested = getNestedWrapper()) {
   // Check for the allowed leaf constructs that may appear in a composite
@@ -1555,6 +1558,9 @@ LogicalResult ParallelOp::verify() {
 } else {
   return emitOpError() << "must not wrap an 'omp.loop_nest' directly";
 }
+  } else if (llvm::cast(getOperation()).isComposite()) {
+return emitError()
+   << "'omp.composite' attribute present in non-composite wrapper";
   }
 
   if (getAllocateVars().size() != getAllocatorVars().size())
@@ -1749,10 +1755,18 @@ LogicalResult WsloopOp::verify() {
 return emitOpError() << "must be a loop wrapper";
 
   if (LoopWrapperInterface nested = getNestedWrapper()) {
+if (!llvm::cast(getOperation()).isComposite())
+  return emitError()
+ << "'omp.composite' attribute missing from composite wrapper";
+
 // Check for the allowed leaf constructs that may appear in a composite
 // construct directly after DO/FOR.
 if (!isa(nested))
   return emitError() << "only supported nested wrapper is 'omp.simd'";
+
+  } else if (llvm::cast(getOperation()).isComposite()) {
+return emitError()
+   << "'omp.composite' attribute present in non-composite wrapper";
   }
 
   return verifyReductionVarList(*this, getReductionSyms(), getReductionVars(),
@@ -1796,6 +1810,10 @@ LogicalResult SimdOp::verify() {
   if (getNestedWrapper())
 return emitOpError() << "must wrap an 'omp.loop_nest' directly";
 
+  if (llvm::cast(getOperation()).isComposite())
+return emitError()
+   << "'omp.composite' attribute present in non-composite wrapper";
+
   return success();
 }
 
@@ -1825,11 +1843,17 @@ LogicalResult DistributeOp::verify() {
 return emitOpError() << "must be a loop wrapper";
 
   if (LoopWrapperInterface nested = getNestedWrapper()) {
+if (!llvm::cast(getOperation()).isComposite())
+  return emitError()
+ << "'omp.composite' at

[llvm-branch-commits] [llvm] [mlir] [OpenMP]Update use_device_clause lowering (PR #101707)

2024-08-19 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/101707

>From 3a2afe783bfd65c981424fb14d2b0f42ea0b6618 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Fri, 2 Aug 2024 17:11:21 +0100
Subject: [PATCH] [OpenMP]Update use_device_clause lowering

This patch updates the use_device_ptr and use_device_addr clauses to use the 
mapInfoOps for lowering. This allows all the types that are handle by the map 
clauses such as derived types to also be supported by the use_device_clauses.

This is patch 2/2 in a series of patches.
---
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp |   2 +-
 .../OpenMP/OpenMPToLLVMIRTranslation.cpp  | 284 ++
 mlir/test/Target/LLVMIR/omptarget-llvm.mlir   |  16 +-
 .../openmp-target-use-device-nested.mlir  |  27 ++
 4 files changed, 194 insertions(+), 135 deletions(-)
 create mode 100644 mlir/test/Target/LLVMIR/openmp-target-use-device-nested.mlir

diff --git a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp 
b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
index 83fec194d73904..f5d94069ad6f4c 100644
--- a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -6357,7 +6357,7 @@ OpenMPIRBuilder::InsertPointTy 
OpenMPIRBuilder::createTargetData(
   // Disable TargetData CodeGen on Device pass.
   if (Config.IsTargetDevice.value_or(false)) {
 if (BodyGenCB)
-  Builder.restoreIP(BodyGenCB(Builder.saveIP(), BodyGenTy::NoPriv));
+  Builder.restoreIP(BodyGenCB(CodeGenIP, BodyGenTy::NoPriv));
 return Builder.saveIP();
   }
 
diff --git 
a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp 
b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index 458d05d5059db7..78c460c50cbe5e 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -2110,6 +2110,8 @@ getRefPtrIfDeclareTarget(mlir::Value value,
 struct MapInfoData : llvm::OpenMPIRBuilder::MapInfosTy {
   llvm::SmallVector IsDeclareTarget;
   llvm::SmallVector IsAMember;
+  // Identify if mapping was added by mapClause or use_device clauses.
+  llvm::SmallVector IsAMapping;
   llvm::SmallVector MapClause;
   llvm::SmallVector OriginalValue;
   // Stripped off array/pointer to get the underlying
@@ -2193,62 +2195,125 @@ llvm::Value *getSizeInBytes(DataLayout &dl, const 
mlir::Type &type,
   return builder.getInt64(dl.getTypeSizeInBits(type) / 8);
 }
 
-void collectMapDataFromMapVars(MapInfoData &mapData,
-   llvm::SmallVectorImpl &mapVars,
-   LLVM::ModuleTranslation &moduleTranslation,
-   DataLayout &dl, llvm::IRBuilderBase &builder) {
+void collectMapDataFromMapOperands(
+MapInfoData &mapData, llvm::SmallVectorImpl &mapVars,
+LLVM::ModuleTranslation &moduleTranslation, DataLayout &dl,
+llvm::IRBuilderBase &builder,
+const llvm::ArrayRef &useDevPtrOperands = {},
+const llvm::ArrayRef &useDevAddrOperands = {}) {
+  // Process MapOperands
   for (mlir::Value mapValue : mapVars) {
-if (auto mapOp = mlir::dyn_cast_if_present(
-mapValue.getDefiningOp())) {
-  mlir::Value offloadPtr =
-  mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
-  mapData.OriginalValue.push_back(
-  moduleTranslation.lookupValue(offloadPtr));
-  mapData.Pointers.push_back(mapData.OriginalValue.back());
-
-  if (llvm::Value *refPtr =
-  getRefPtrIfDeclareTarget(offloadPtr,
-   moduleTranslation)) { // declare target
-mapData.IsDeclareTarget.push_back(true);
-mapData.BasePointers.push_back(refPtr);
-  } else { // regular mapped variable
-mapData.IsDeclareTarget.push_back(false);
-mapData.BasePointers.push_back(mapData.OriginalValue.back());
-  }
+auto mapOp = mlir::cast(mapValue.getDefiningOp());
+mlir::Value offloadPtr =
+mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
+mapData.OriginalValue.push_back(moduleTranslation.lookupValue(offloadPtr));
+mapData.Pointers.push_back(mapData.OriginalValue.back());
+
+if (llvm::Value *refPtr =
+getRefPtrIfDeclareTarget(offloadPtr,
+ moduleTranslation)) { // declare target
+  mapData.IsDeclareTarget.push_back(true);
+  mapData.BasePointers.push_back(refPtr);
+} else { // regular mapped variable
+  mapData.IsDeclareTarget.push_back(false);
+  mapData.BasePointers.push_back(mapData.OriginalValue.back());
+}
 
-  mapData.BaseType.push_back(
-  moduleTranslation.convertType(mapOp.getVarType()));
-  mapData.Sizes.push_back(
-  getSizeInBytes(dl, mapOp.getVarType(), mapOp, 
mapData.Pointers.back(),
- mapData.BaseType.back(), builder, moduleTranslation));
-  mapData.MapClause.push_back(mapOp.getOpera

[llvm-branch-commits] [llvm] [mlir] [OpenMP]Update use_device_clause lowering (PR #101707)

2024-08-20 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/101707

>From 3a2afe783bfd65c981424fb14d2b0f42ea0b6618 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Fri, 2 Aug 2024 17:11:21 +0100
Subject: [PATCH 1/2] [OpenMP]Update use_device_clause lowering

This patch updates the use_device_ptr and use_device_addr clauses to use the 
mapInfoOps for lowering. This allows all the types that are handle by the map 
clauses such as derived types to also be supported by the use_device_clauses.

This is patch 2/2 in a series of patches.
---
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp |   2 +-
 .../OpenMP/OpenMPToLLVMIRTranslation.cpp  | 284 ++
 mlir/test/Target/LLVMIR/omptarget-llvm.mlir   |  16 +-
 .../openmp-target-use-device-nested.mlir  |  27 ++
 4 files changed, 194 insertions(+), 135 deletions(-)
 create mode 100644 mlir/test/Target/LLVMIR/openmp-target-use-device-nested.mlir

diff --git a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp 
b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
index 83fec194d73904..f5d94069ad6f4c 100644
--- a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -6357,7 +6357,7 @@ OpenMPIRBuilder::InsertPointTy 
OpenMPIRBuilder::createTargetData(
   // Disable TargetData CodeGen on Device pass.
   if (Config.IsTargetDevice.value_or(false)) {
 if (BodyGenCB)
-  Builder.restoreIP(BodyGenCB(Builder.saveIP(), BodyGenTy::NoPriv));
+  Builder.restoreIP(BodyGenCB(CodeGenIP, BodyGenTy::NoPriv));
 return Builder.saveIP();
   }
 
diff --git 
a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp 
b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index 458d05d5059db7..78c460c50cbe5e 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -2110,6 +2110,8 @@ getRefPtrIfDeclareTarget(mlir::Value value,
 struct MapInfoData : llvm::OpenMPIRBuilder::MapInfosTy {
   llvm::SmallVector IsDeclareTarget;
   llvm::SmallVector IsAMember;
+  // Identify if mapping was added by mapClause or use_device clauses.
+  llvm::SmallVector IsAMapping;
   llvm::SmallVector MapClause;
   llvm::SmallVector OriginalValue;
   // Stripped off array/pointer to get the underlying
@@ -2193,62 +2195,125 @@ llvm::Value *getSizeInBytes(DataLayout &dl, const 
mlir::Type &type,
   return builder.getInt64(dl.getTypeSizeInBits(type) / 8);
 }
 
-void collectMapDataFromMapVars(MapInfoData &mapData,
-   llvm::SmallVectorImpl &mapVars,
-   LLVM::ModuleTranslation &moduleTranslation,
-   DataLayout &dl, llvm::IRBuilderBase &builder) {
+void collectMapDataFromMapOperands(
+MapInfoData &mapData, llvm::SmallVectorImpl &mapVars,
+LLVM::ModuleTranslation &moduleTranslation, DataLayout &dl,
+llvm::IRBuilderBase &builder,
+const llvm::ArrayRef &useDevPtrOperands = {},
+const llvm::ArrayRef &useDevAddrOperands = {}) {
+  // Process MapOperands
   for (mlir::Value mapValue : mapVars) {
-if (auto mapOp = mlir::dyn_cast_if_present(
-mapValue.getDefiningOp())) {
-  mlir::Value offloadPtr =
-  mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
-  mapData.OriginalValue.push_back(
-  moduleTranslation.lookupValue(offloadPtr));
-  mapData.Pointers.push_back(mapData.OriginalValue.back());
-
-  if (llvm::Value *refPtr =
-  getRefPtrIfDeclareTarget(offloadPtr,
-   moduleTranslation)) { // declare target
-mapData.IsDeclareTarget.push_back(true);
-mapData.BasePointers.push_back(refPtr);
-  } else { // regular mapped variable
-mapData.IsDeclareTarget.push_back(false);
-mapData.BasePointers.push_back(mapData.OriginalValue.back());
-  }
+auto mapOp = mlir::cast(mapValue.getDefiningOp());
+mlir::Value offloadPtr =
+mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
+mapData.OriginalValue.push_back(moduleTranslation.lookupValue(offloadPtr));
+mapData.Pointers.push_back(mapData.OriginalValue.back());
+
+if (llvm::Value *refPtr =
+getRefPtrIfDeclareTarget(offloadPtr,
+ moduleTranslation)) { // declare target
+  mapData.IsDeclareTarget.push_back(true);
+  mapData.BasePointers.push_back(refPtr);
+} else { // regular mapped variable
+  mapData.IsDeclareTarget.push_back(false);
+  mapData.BasePointers.push_back(mapData.OriginalValue.back());
+}
 
-  mapData.BaseType.push_back(
-  moduleTranslation.convertType(mapOp.getVarType()));
-  mapData.Sizes.push_back(
-  getSizeInBytes(dl, mapOp.getVarType(), mapOp, 
mapData.Pointers.back(),
- mapData.BaseType.back(), builder, moduleTranslation));
-  mapData.MapClause.push_back(mapOp.getO

[llvm-branch-commits] [llvm] [mlir] [OpenMP]Update use_device_clause lowering (PR #101707)

2024-08-20 Thread Akash Banerjee via llvm-branch-commits

TIFitis wrote:

Thanks @Dinistro for the comments, I've addressed them in the latest revision.

https://github.com/llvm/llvm-project/pull/101707
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [mlir] [OpenMP]Update use_device_clause lowering (PR #101707)

2024-08-21 Thread Akash Banerjee via llvm-branch-commits


@@ -2193,80 +2197,141 @@ llvm::Value *getSizeInBytes(DataLayout &dl, const 
mlir::Type &type,
   return builder.getInt64(dl.getTypeSizeInBits(type) / 8);
 }
 
-void collectMapDataFromMapVars(MapInfoData &mapData,
-   llvm::SmallVectorImpl &mapVars,
-   LLVM::ModuleTranslation &moduleTranslation,
-   DataLayout &dl, llvm::IRBuilderBase &builder) {
-  for (mlir::Value mapValue : mapVars) {
-if (auto mapOp = mlir::dyn_cast_if_present(
-mapValue.getDefiningOp())) {
-  mlir::Value offloadPtr =
-  mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
-  mapData.OriginalValue.push_back(
-  moduleTranslation.lookupValue(offloadPtr));
-  mapData.Pointers.push_back(mapData.OriginalValue.back());
-
-  if (llvm::Value *refPtr =
-  getRefPtrIfDeclareTarget(offloadPtr,
-   moduleTranslation)) { // declare target
-mapData.IsDeclareTarget.push_back(true);
-mapData.BasePointers.push_back(refPtr);
-  } else { // regular mapped variable
-mapData.IsDeclareTarget.push_back(false);
-mapData.BasePointers.push_back(mapData.OriginalValue.back());
-  }
+static void collectMapDataFromMapOperands(
+MapInfoData &mapData, SmallVectorImpl &mapVars,
+LLVM::ModuleTranslation &moduleTranslation, DataLayout &dl,
+llvm::IRBuilderBase &builder, const ArrayRef &useDevPtrOperands = 
{},
+const ArrayRef &useDevAddrOperands = {}) {
+  // Process MapOperands
+  for (Value mapValue : mapVars) {
+auto mapOp = cast(mapValue.getDefiningOp());
+Value offloadPtr =
+mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
+mapData.OriginalValue.push_back(moduleTranslation.lookupValue(offloadPtr));
+mapData.Pointers.push_back(mapData.OriginalValue.back());
+
+if (llvm::Value *refPtr =
+getRefPtrIfDeclareTarget(offloadPtr,
+ moduleTranslation)) { // declare target
+  mapData.IsDeclareTarget.push_back(true);
+  mapData.BasePointers.push_back(refPtr);
+} else { // regular mapped variable
+  mapData.IsDeclareTarget.push_back(false);
+  mapData.BasePointers.push_back(mapData.OriginalValue.back());
+}
 
-  mapData.BaseType.push_back(
-  moduleTranslation.convertType(mapOp.getVarType()));
-  mapData.Sizes.push_back(
-  getSizeInBytes(dl, mapOp.getVarType(), mapOp, 
mapData.Pointers.back(),
- mapData.BaseType.back(), builder, moduleTranslation));
-  mapData.MapClause.push_back(mapOp.getOperation());
-  mapData.Types.push_back(
-  llvm::omp::OpenMPOffloadMappingFlags(mapOp.getMapType().value()));
-  mapData.Names.push_back(LLVM::createMappingInformation(
-  mapOp.getLoc(), *moduleTranslation.getOpenMPBuilder()));
-  mapData.DevicePointers.push_back(
-  llvm::OpenMPIRBuilder::DeviceInfoTy::None);
-
-  // Check if this is a member mapping and correctly assign that it is, if
-  // it is a member of a larger object.
-  // TODO: Need better handling of members, and distinguishing of members
-  // that are implicitly allocated on device vs explicitly passed in as
-  // arguments.
-  // TODO: May require some further additions to support nested record
-  // types, i.e. member maps that can have member maps.
-  mapData.IsAMember.push_back(false);
-  for (mlir::Value mapValue : mapVars) {
-if (auto map = mlir::dyn_cast_if_present(
-mapValue.getDefiningOp())) {
-  for (auto member : map.getMembers()) {
-if (member == mapOp) {
-  mapData.IsAMember.back() = true;
-}
+mapData.BaseType.push_back(
+moduleTranslation.convertType(mapOp.getVarType()));
+mapData.Sizes.push_back(
+getSizeInBytes(dl, mapOp.getVarType(), mapOp, mapData.Pointers.back(),
+   mapData.BaseType.back(), builder, moduleTranslation));
+mapData.MapClause.push_back(mapOp.getOperation());
+mapData.Types.push_back(
+llvm::omp::OpenMPOffloadMappingFlags(mapOp.getMapType().value()));
+mapData.Names.push_back(LLVM::createMappingInformation(
+mapOp.getLoc(), *moduleTranslation.getOpenMPBuilder()));
+
mapData.DevicePointers.push_back(llvm::OpenMPIRBuilder::DeviceInfoTy::None);
+mapData.IsAMapping.push_back(true);
+
+// Check if this is a member mapping and correctly assign that it is, if
+// it is a member of a larger object.
+// TODO: Need better handling of members, and distinguishing of members
+// that are implicitly allocated on device vs explicitly passed in as
+// arguments.
+// TODO: May require some further additions to support nested record
+// types, i.e. member maps that can have member maps.
+mapData.IsAMember.push_back(false);
+for (Valu

[llvm-branch-commits] [llvm] [mlir] [OpenMP]Update use_device_clause lowering (PR #101707)

2024-08-21 Thread Akash Banerjee via llvm-branch-commits


@@ -2193,80 +2197,141 @@ llvm::Value *getSizeInBytes(DataLayout &dl, const 
mlir::Type &type,
   return builder.getInt64(dl.getTypeSizeInBits(type) / 8);
 }
 
-void collectMapDataFromMapVars(MapInfoData &mapData,
-   llvm::SmallVectorImpl &mapVars,
-   LLVM::ModuleTranslation &moduleTranslation,
-   DataLayout &dl, llvm::IRBuilderBase &builder) {
-  for (mlir::Value mapValue : mapVars) {
-if (auto mapOp = mlir::dyn_cast_if_present(
-mapValue.getDefiningOp())) {
-  mlir::Value offloadPtr =
-  mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
-  mapData.OriginalValue.push_back(
-  moduleTranslation.lookupValue(offloadPtr));
-  mapData.Pointers.push_back(mapData.OriginalValue.back());
-
-  if (llvm::Value *refPtr =
-  getRefPtrIfDeclareTarget(offloadPtr,
-   moduleTranslation)) { // declare target
-mapData.IsDeclareTarget.push_back(true);
-mapData.BasePointers.push_back(refPtr);
-  } else { // regular mapped variable
-mapData.IsDeclareTarget.push_back(false);
-mapData.BasePointers.push_back(mapData.OriginalValue.back());
-  }
+static void collectMapDataFromMapOperands(
+MapInfoData &mapData, SmallVectorImpl &mapVars,
+LLVM::ModuleTranslation &moduleTranslation, DataLayout &dl,
+llvm::IRBuilderBase &builder, const ArrayRef &useDevPtrOperands = 
{},
+const ArrayRef &useDevAddrOperands = {}) {
+  // Process MapOperands
+  for (Value mapValue : mapVars) {
+auto mapOp = cast(mapValue.getDefiningOp());

TIFitis wrote:

Yes, I've replaced the others with cast as well.

https://github.com/llvm/llvm-project/pull/101707
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [mlir] [OpenMP]Update use_device_clause lowering (PR #101707)

2024-08-21 Thread Akash Banerjee via llvm-branch-commits


@@ -6357,7 +6357,7 @@ OpenMPIRBuilder::InsertPointTy 
OpenMPIRBuilder::createTargetData(
   // Disable TargetData CodeGen on Device pass.
   if (Config.IsTargetDevice.value_or(false)) {
 if (BodyGenCB)
-  Builder.restoreIP(BodyGenCB(Builder.saveIP(), BodyGenTy::NoPriv));
+  Builder.restoreIP(BodyGenCB(CodeGenIP, BodyGenTy::NoPriv));

TIFitis wrote:

It's because `CodeGenIP` hasn't been restored by the `Builder` at this point. 
Instead of passing `CodeGenIP`, I've moved the `restoreIp` call upward.

https://github.com/llvm/llvm-project/pull/101707
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [mlir] [OpenMP]Update use_device_clause lowering (PR #101707)

2024-08-21 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/101707

>From 547b339b175fa996eef8d45c5df8a73967ee94c2 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Fri, 2 Aug 2024 17:11:21 +0100
Subject: [PATCH 1/3] [OpenMP]Update use_device_clause lowering

This patch updates the use_device_ptr and use_device_addr clauses to use the 
mapInfoOps for lowering. This allows all the types that are handle by the map 
clauses such as derived types to also be supported by the use_device_clauses.

This is patch 2/2 in a series of patches.
---
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp |   2 +-
 .../OpenMP/OpenMPToLLVMIRTranslation.cpp  | 284 ++
 mlir/test/Target/LLVMIR/omptarget-llvm.mlir   |  16 +-
 .../openmp-target-use-device-nested.mlir  |  27 ++
 4 files changed, 194 insertions(+), 135 deletions(-)
 create mode 100644 mlir/test/Target/LLVMIR/openmp-target-use-device-nested.mlir

diff --git a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp 
b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
index 83fec194d73904..f5d94069ad6f4c 100644
--- a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -6357,7 +6357,7 @@ OpenMPIRBuilder::InsertPointTy 
OpenMPIRBuilder::createTargetData(
   // Disable TargetData CodeGen on Device pass.
   if (Config.IsTargetDevice.value_or(false)) {
 if (BodyGenCB)
-  Builder.restoreIP(BodyGenCB(Builder.saveIP(), BodyGenTy::NoPriv));
+  Builder.restoreIP(BodyGenCB(CodeGenIP, BodyGenTy::NoPriv));
 return Builder.saveIP();
   }
 
diff --git 
a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp 
b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index 458d05d5059db7..78c460c50cbe5e 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -2110,6 +2110,8 @@ getRefPtrIfDeclareTarget(mlir::Value value,
 struct MapInfoData : llvm::OpenMPIRBuilder::MapInfosTy {
   llvm::SmallVector IsDeclareTarget;
   llvm::SmallVector IsAMember;
+  // Identify if mapping was added by mapClause or use_device clauses.
+  llvm::SmallVector IsAMapping;
   llvm::SmallVector MapClause;
   llvm::SmallVector OriginalValue;
   // Stripped off array/pointer to get the underlying
@@ -2193,62 +2195,125 @@ llvm::Value *getSizeInBytes(DataLayout &dl, const 
mlir::Type &type,
   return builder.getInt64(dl.getTypeSizeInBits(type) / 8);
 }
 
-void collectMapDataFromMapVars(MapInfoData &mapData,
-   llvm::SmallVectorImpl &mapVars,
-   LLVM::ModuleTranslation &moduleTranslation,
-   DataLayout &dl, llvm::IRBuilderBase &builder) {
+void collectMapDataFromMapOperands(
+MapInfoData &mapData, llvm::SmallVectorImpl &mapVars,
+LLVM::ModuleTranslation &moduleTranslation, DataLayout &dl,
+llvm::IRBuilderBase &builder,
+const llvm::ArrayRef &useDevPtrOperands = {},
+const llvm::ArrayRef &useDevAddrOperands = {}) {
+  // Process MapOperands
   for (mlir::Value mapValue : mapVars) {
-if (auto mapOp = mlir::dyn_cast_if_present(
-mapValue.getDefiningOp())) {
-  mlir::Value offloadPtr =
-  mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
-  mapData.OriginalValue.push_back(
-  moduleTranslation.lookupValue(offloadPtr));
-  mapData.Pointers.push_back(mapData.OriginalValue.back());
-
-  if (llvm::Value *refPtr =
-  getRefPtrIfDeclareTarget(offloadPtr,
-   moduleTranslation)) { // declare target
-mapData.IsDeclareTarget.push_back(true);
-mapData.BasePointers.push_back(refPtr);
-  } else { // regular mapped variable
-mapData.IsDeclareTarget.push_back(false);
-mapData.BasePointers.push_back(mapData.OriginalValue.back());
-  }
+auto mapOp = mlir::cast(mapValue.getDefiningOp());
+mlir::Value offloadPtr =
+mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
+mapData.OriginalValue.push_back(moduleTranslation.lookupValue(offloadPtr));
+mapData.Pointers.push_back(mapData.OriginalValue.back());
+
+if (llvm::Value *refPtr =
+getRefPtrIfDeclareTarget(offloadPtr,
+ moduleTranslation)) { // declare target
+  mapData.IsDeclareTarget.push_back(true);
+  mapData.BasePointers.push_back(refPtr);
+} else { // regular mapped variable
+  mapData.IsDeclareTarget.push_back(false);
+  mapData.BasePointers.push_back(mapData.OriginalValue.back());
+}
 
-  mapData.BaseType.push_back(
-  moduleTranslation.convertType(mapOp.getVarType()));
-  mapData.Sizes.push_back(
-  getSizeInBytes(dl, mapOp.getVarType(), mapOp, 
mapData.Pointers.back(),
- mapData.BaseType.back(), builder, moduleTranslation));
-  mapData.MapClause.push_back(mapOp.getO

[llvm-branch-commits] [llvm] [mlir] [OpenMP]Update use_device_clause lowering (PR #101707)

2024-08-21 Thread Akash Banerjee via llvm-branch-commits

TIFitis wrote:

@skatrak Thanks for the review, I've addressed the comments in the latest 
revision.


https://github.com/llvm/llvm-project/pull/101707
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [mlir] [OpenMP]Update use_device_clause lowering (PR #101707)

2024-08-21 Thread Akash Banerjee via llvm-branch-commits


@@ -2439,7 +2504,7 @@ static llvm::omp::OpenMPOffloadMappingFlags 
mapParentWithMembers(
   // data by the descriptor (which itself, is a structure containing
   // runtime information on the dynamically allocated data).
   auto parentClause =
-  llvm::cast(mapData.MapClause[mapDataIndex]);
+  llvm::cast(mapData.MapClause[mapDataIndex]);

TIFitis wrote:

Agreed, I'll create an NFC PR to address this.

https://github.com/llvm/llvm-project/pull/101707
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [mlir] [OpenMP]Update use_device_clause lowering (PR #101707)

2024-08-29 Thread Akash Banerjee via llvm-branch-commits

TIFitis wrote:

Ping for review.

https://github.com/llvm/llvm-project/pull/101707
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [llvm] [mlir] [OpenMP]Update use_device_clause lowering (PR #101707)

2024-09-03 Thread Akash Banerjee via llvm-branch-commits


@@ -2193,80 +2197,137 @@ llvm::Value *getSizeInBytes(DataLayout &dl, const 
mlir::Type &type,
   return builder.getInt64(dl.getTypeSizeInBits(type) / 8);
 }
 
-void collectMapDataFromMapVars(MapInfoData &mapData,
-   llvm::SmallVectorImpl &mapVars,
-   LLVM::ModuleTranslation &moduleTranslation,
-   DataLayout &dl, llvm::IRBuilderBase &builder) {
-  for (mlir::Value mapValue : mapVars) {
-if (auto mapOp = mlir::dyn_cast_if_present(
-mapValue.getDefiningOp())) {
-  mlir::Value offloadPtr =
+static void collectMapDataFromMapOperands(
+MapInfoData &mapData, SmallVectorImpl &mapVars,
+LLVM::ModuleTranslation &moduleTranslation, DataLayout &dl,
+llvm::IRBuilderBase &builder, const ArrayRef &useDevPtrOperands = 
{},
+const ArrayRef &useDevAddrOperands = {}) {
+  // Process MapOperands
+  for (Value mapValue : mapVars) {
+auto mapOp = cast(mapValue.getDefiningOp());
+Value offloadPtr =
+mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
+mapData.OriginalValue.push_back(moduleTranslation.lookupValue(offloadPtr));
+mapData.Pointers.push_back(mapData.OriginalValue.back());
+
+if (llvm::Value *refPtr =
+getRefPtrIfDeclareTarget(offloadPtr,
+ moduleTranslation)) { // declare target
+  mapData.IsDeclareTarget.push_back(true);
+  mapData.BasePointers.push_back(refPtr);
+} else { // regular mapped variable
+  mapData.IsDeclareTarget.push_back(false);
+  mapData.BasePointers.push_back(mapData.OriginalValue.back());
+}
+
+mapData.BaseType.push_back(
+moduleTranslation.convertType(mapOp.getVarType()));
+mapData.Sizes.push_back(
+getSizeInBytes(dl, mapOp.getVarType(), mapOp, mapData.Pointers.back(),
+   mapData.BaseType.back(), builder, moduleTranslation));
+mapData.MapClause.push_back(mapOp.getOperation());
+mapData.Types.push_back(
+llvm::omp::OpenMPOffloadMappingFlags(mapOp.getMapType().value()));
+mapData.Names.push_back(LLVM::createMappingInformation(
+mapOp.getLoc(), *moduleTranslation.getOpenMPBuilder()));
+
mapData.DevicePointers.push_back(llvm::OpenMPIRBuilder::DeviceInfoTy::None);
+mapData.IsAMapping.push_back(true);
+
+// Check if this is a member mapping and correctly assign that it is, if
+// it is a member of a larger object.
+// TODO: Need better handling of members, and distinguishing of members
+// that are implicitly allocated on device vs explicitly passed in as
+// arguments.
+// TODO: May require some further additions to support nested record
+// types, i.e. member maps that can have member maps.
+mapData.IsAMember.push_back(false);
+for (Value mapValue : mapVars) {
+  auto map = cast(mapValue.getDefiningOp());

TIFitis wrote:

I've moved the logic to a lambda, hopefully that helps readability along with 
code divergence.

I don't think we need to check for member mapOp being same as parent as that 
would be a peculiar scenario we aren't expecting.

https://github.com/llvm/llvm-project/pull/101707
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [llvm] [mlir] [OpenMP]Update use_device_clause lowering (PR #101707)

2024-09-03 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/101707

>From 10f575c3457719e2b21f9633c890c34ae671548e Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Fri, 2 Aug 2024 17:11:21 +0100
Subject: [PATCH] [OpenMP]Update use_device_clause lowering

This patch updates the use_device_ptr and use_device_addr clauses to use the 
mapInfoOps for lowering. This allows all the types that are handle by the map 
clauses such as derived types to also be supported by the use_device_clauses.

This is patch 2/2 in a series of patches.
---
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp |   2 +-
 .../OpenMP/OpenMPToLLVMIRTranslation.cpp  | 354 +-
 mlir/test/Target/LLVMIR/omptarget-llvm.mlir   |  16 +-
 .../openmp-target-use-device-nested.mlir  |  39 ++
 4 files changed, 228 insertions(+), 183 deletions(-)
 create mode 100644 mlir/test/Target/LLVMIR/openmp-target-use-device-nested.mlir

diff --git a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp 
b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
index 532313a31fc132..497fecbf6ea199 100644
--- a/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
+++ b/llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp
@@ -6369,6 +6369,7 @@ OpenMPIRBuilder::InsertPointTy 
OpenMPIRBuilder::createTargetData(
   if (!updateToLocation(Loc))
 return InsertPointTy();
 
+  Builder.restoreIP(CodeGenIP);
   // Disable TargetData CodeGen on Device pass.
   if (Config.IsTargetDevice.value_or(false)) {
 if (BodyGenCB)
@@ -6376,7 +6377,6 @@ OpenMPIRBuilder::InsertPointTy 
OpenMPIRBuilder::createTargetData(
 return Builder.saveIP();
   }
 
-  Builder.restoreIP(CodeGenIP);
   bool IsStandAlone = !BodyGenCB;
   MapInfosTy *MapInfo;
   // Generate the code for the opening of the data environment. Capture all the
diff --git 
a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp 
b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
index 6a32aeb4441406..d597bbfee2fe19 100644
--- a/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
+++ b/mlir/lib/Target/LLVMIR/Dialect/OpenMP/OpenMPToLLVMIRTranslation.cpp
@@ -2260,6 +2260,7 @@ getRefPtrIfDeclareTarget(mlir::Value value,
   return nullptr;
 }
 
+namespace {
 // A small helper structure to contain data gathered
 // for map lowering and coalese it into one area and
 // avoiding extra computations such as searches in the
@@ -2269,6 +2270,8 @@ getRefPtrIfDeclareTarget(mlir::Value value,
 struct MapInfoData : llvm::OpenMPIRBuilder::MapInfosTy {
   llvm::SmallVector IsDeclareTarget;
   llvm::SmallVector IsAMember;
+  // Identify if mapping was added by mapClause or use_device clauses.
+  llvm::SmallVector IsAMapping;
   llvm::SmallVector MapClause;
   llvm::SmallVector OriginalValue;
   // Stripped off array/pointer to get the underlying
@@ -2286,6 +2289,7 @@ struct MapInfoData : llvm::OpenMPIRBuilder::MapInfosTy {
 llvm::OpenMPIRBuilder::MapInfosTy::append(CurInfo);
   }
 };
+} // namespace
 
 uint64_t getArrayElementSizeInBits(LLVM::LLVMArrayType arrTy, DataLayout &dl) {
   if (auto nestedArrTy = llvm::dyn_cast_if_present(
@@ -2352,80 +2356,126 @@ llvm::Value *getSizeInBytes(DataLayout &dl, const 
mlir::Type &type,
   return builder.getInt64(dl.getTypeSizeInBits(type) / 8);
 }
 
-void collectMapDataFromMapVars(MapInfoData &mapData,
-   llvm::SmallVectorImpl &mapVars,
-   LLVM::ModuleTranslation &moduleTranslation,
-   DataLayout &dl, llvm::IRBuilderBase &builder) {
-  for (mlir::Value mapValue : mapVars) {
-if (auto mapOp = mlir::dyn_cast_if_present(
-mapValue.getDefiningOp())) {
-  mlir::Value offloadPtr =
+static void collectMapDataFromMapOperands(
+MapInfoData &mapData, SmallVectorImpl &mapVars,
+LLVM::ModuleTranslation &moduleTranslation, DataLayout &dl,
+llvm::IRBuilderBase &builder, const ArrayRef &useDevPtrOperands = 
{},
+const ArrayRef &useDevAddrOperands = {}) {
+  auto checkIsAMember = [](const auto &mapVars, auto mapOp) {
+// Check if this is a member mapping and correctly assign that it is, if
+// it is a member of a larger object.
+// TODO: Need better handling of members, and distinguishing of members
+// that are implicitly allocated on device vs explicitly passed in as
+// arguments.
+// TODO: May require some further additions to support nested record
+// types, i.e. member maps that can have member maps.
+for (Value mapValue : mapVars) {
+  auto map = cast(mapValue.getDefiningOp());
+  for (auto member : map.getMembers())
+if (member == mapOp)
+  return true;
+}
+return false;
+  };
+
+  // Process MapOperands
+  for (Value mapValue : mapVars) {
+auto mapOp = cast(mapValue.getDefiningOp());
+Value offloadPtr =
+mapOp.getVarPtrPtr() ? mapOp.getVarPtrPtr() : mapOp.getVarPtr();
+mapData.OriginalValue.push_back(moduleTranslation.lookupValue(offloadPtr));
+mapD

[llvm-branch-commits] [OpenMP][MLIR] Descriptor explicit member map lowering changes (PR #111191)

2024-10-08 Thread Akash Banerjee via llvm-branch-commits


@@ -2468,51 +2468,45 @@ static int getMapDataMemberIdx(MapInfoData &mapData, 
omp::MapInfoOp memberOp) {
   return std::distance(mapData.MapClause.begin(), res);
 }
 
-static omp::MapInfoOp getFirstOrLastMappedMemberPtr(omp::MapInfoOp mapInfo,
-bool first) {
-  DenseIntElementsAttr indexAttr = mapInfo.getMembersIndexAttr();
-
+static mlir::omp::MapInfoOp
+getFirstOrLastMappedMemberPtr(mlir::omp::MapInfoOp mapInfo, bool first) {
+  mlir::ArrayAttr indexAttr = mapInfo.getMembersIndexAttr();
   // Only 1 member has been mapped, we can return it.
   if (indexAttr.size() == 1)
-if (auto mapOp =
-dyn_cast(mapInfo.getMembers()[0].getDefiningOp()))
+if (auto mapOp = mlir::dyn_cast(

TIFitis wrote:

Is there a scenario where the definingOp can be anything other than a 
MapInfoOp? If not, you can take get rid of the if statement and replace the 
`dyn_cast` with a `cast`.

https://github.com/llvm/llvm-project/pull/91
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [OpenMP][MLIR] Descriptor explicit member map lowering changes (PR #111191)

2024-10-08 Thread Akash Banerjee via llvm-branch-commits


@@ -2663,6 +2657,8 @@ static llvm::omp::OpenMPOffloadMappingFlags 
mapParentWithMembers(
 auto mapOp = dyn_cast(mapData.MapClause[mapDataIndex]);
 int firstMemberIdx = getMapDataMemberIdx(
 mapData, getFirstOrLastMappedMemberPtr(mapOp, true));
+// NOTE/TODO: Should perhaps use OriginalValue here instead of Pointers to

TIFitis wrote:

Is it possible to determine this definitively in this patch itself? 

https://github.com/llvm/llvm-project/pull/91
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [OpenMP][MLIR] Descriptor explicit member map lowering changes (PR #111191)

2024-10-08 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis approved this pull request.

Added couple of nit comments. Otherwise happy with the patch. Thank you for the 
amazing work :)

https://github.com/llvm/llvm-project/pull/91
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [OpenMP][MLIR] Descriptor explicit member map lowering changes (PR #111191)

2024-10-08 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis edited 
https://github.com/llvm/llvm-project/pull/91
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [Flang][OpenMP] Derived type explicit allocatable member mapping (PR #111192)

2024-10-08 Thread Akash Banerjee via llvm-branch-commits


@@ -13,19 +13,22 @@
 #include "Utils.h"
 
 #include "Clauses.h"
+#include 
+
+#include 
 #include 
+#include 

TIFitis wrote:

Are all of the header file changes necessary? Just making sure we only have the 
minimal set here.

https://github.com/llvm/llvm-project/pull/92
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [Flang][OpenMP] Derived type explicit allocatable member mapping (PR #111192)

2024-10-18 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis approved this pull request.

LGTM :)

https://github.com/llvm/llvm-project/pull/92
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Use map format to represent use_device_{addr, ptr} (PR #109810)

2024-10-01 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis approved this pull request.

Im happy with the changes. Thanks :)

https://github.com/llvm/llvm-project/pull/109810
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2024-11-28 Thread Akash Banerjee via llvm-branch-commits


@@ -2701,7 +2701,42 @@ static void
 genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
const parser::OpenMPDeclareMapperConstruct &declareMapperConstruct) {
-  TODO(converter.getCurrentLocation(), "OpenMPDeclareMapperConstruct");
+  fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  lower::StatementContext stmtCtx;
+  const auto &spec =
+  std::get(declareMapperConstruct.t);
+  const auto &mapperName{std::get>(spec.t)};
+  const auto &varType{std::get(spec.t)};
+  const auto &varName{std::get(spec.t)};
+  assert(varType.declTypeSpec->category() ==
+ semantics::DeclTypeSpec::Category::TypeDerived &&
+ "Expected derived type");
+
+  std::string mapperNameStr;
+  if (mapperName.has_value())
+mapperNameStr = mapperName->ToString();
+  else
+mapperNameStr =
+"default_" + varType.declTypeSpec->derivedTypeSpec().name().ToString();
+
+  mlir::OpBuilder::InsertPoint insPt = firOpBuilder.saveInsertionPoint();
+  firOpBuilder.setInsertionPointToStart(converter.getModuleOp().getBody());
+  auto mlirType = converter.genType(varType.declTypeSpec->derivedTypeSpec());
+  auto varVal = firOpBuilder.createTemporaryAlloc(
+  converter.getCurrentLocation(), mlirType, varName.ToString());

TIFitis wrote:

I have made the required changes to both PRs to update the representation for 
the DeclMapperOp.

Some changes I've incorporated are:

Inside DeclMapperOp's region I've introduce a new `DeclMapperInfoOp` to which 
I've attached the `MapClause`. Not having any `MapClause` explicitly associated 
seemed weird to me, also walking through the region collecting all the 
`MapInfoOps` for processing in various places in the code base seemed like a 
bad design to me.

Also, instead of using the block arg, I've created a `temporary alloca` inside 
the region. This is to save the hassle of binding the block_arg to the symbol, 
binding the `alloca` is much more straightforward.

We can drop the entire `DeclMapperOp` including the region once it reaches 
`OpenMPTOLLVMIRTranslation`.

Let me what are your thoughts on this approach :)

https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2024-11-28 Thread Akash Banerjee via llvm-branch-commits

TIFitis wrote:

As @agozillon requested, here's a sample of how Clang lowers declare mapper.

**C Code:**
```
typedef struct {
  int *ptr;
  int buf_size;
} T;
#pragma omp declare mapper(deep_copy : T abc) map(abc, abc.ptr[ : abc.buf_size])
int main() {
  T xyz;
#pragma omp target data map(mapper(deep_copy), tofrom : xyz)
  {
  }
  return 0;
}
```

**LLVM IR:**
```
@.offload_sizes = private unnamed_addr constant [1 x i64] [i64 16]
@.offload_maptypes = private unnamed_addr constant [1 x i64] [i64 3]

; Function Attrs: noinline nounwind optnone uwtable
define dso_local i32 @main() #0 {
entry:
  %retval = alloca i32, align 4
  %xyz = alloca %struct.T, align 8
  %.offload_baseptrs = alloca [1 x ptr], align 8
  %.offload_ptrs = alloca [1 x ptr], align 8
  %.offload_mappers = alloca [1 x ptr], align 8
  store i32 0, ptr %retval, align 4
  %0 = getelementptr inbounds [1 x ptr], ptr %.offload_baseptrs, i32 0, i32 0
  store ptr %xyz, ptr %0, align 8
  %1 = getelementptr inbounds [1 x ptr], ptr %.offload_ptrs, i32 0, i32 0
  store ptr %xyz, ptr %1, align 8
  %2 = getelementptr inbounds [1 x ptr], ptr %.offload_mappers, i64 0, i64 0
  store ptr @.omp_mapper._ZTS1T.deep_copy, ptr %2, align 8
  %3 = getelementptr inbounds [1 x ptr], ptr %.offload_baseptrs, i32 0, i32 0
  %4 = getelementptr inbounds [1 x ptr], ptr %.offload_ptrs, i32 0, i32 0
  call void @__tgt_target_data_begin_mapper(ptr @1, i64 -1, i32 1, ptr %3, ptr 
%4, ptr @.offload_sizes, ptr @.offload_maptypes, ptr null, ptr 
%.offload_mappers)
  %5 = getelementptr inbounds [1 x ptr], ptr %.offload_baseptrs, i32 0, i32 0
  %6 = getelementptr inbounds [1 x ptr], ptr %.offload_ptrs, i32 0, i32 0
  call void @__tgt_target_data_end_mapper(ptr @1, i64 -1, i32 1, ptr %5, ptr 
%6, ptr @.offload_sizes, ptr @.offload_maptypes, ptr null, ptr 
%.offload_mappers)
  ret i32 0
}

; Function Attrs: noinline nounwind uwtable
define internal void @.omp_mapper._ZTS1T.deep_copy(ptr noundef %0, ptr noundef 
%1, ptr noundef %2, i64 noundef %3, i64 noundef %4, ptr noundef %5) #1 {
entry:
  %.addr = alloca ptr, align 8
  %.addr1 = alloca ptr, align 8
  %.addr2 = alloca ptr, align 8
  %.addr3 = alloca i64, align 8
  %.addr4 = alloca i64, align 8
  %.addr5 = alloca ptr, align 8
  store ptr %0, ptr %.addr, align 8
  store ptr %1, ptr %.addr1, align 8
  store ptr %2, ptr %.addr2, align 8
  store i64 %3, ptr %.addr3, align 8
  store i64 %4, ptr %.addr4, align 8
  store ptr %5, ptr %.addr5, align 8
  %6 = load i64, ptr %.addr3, align 8
  %7 = load ptr, ptr %.addr, align 8
  %8 = load ptr, ptr %.addr1, align 8
  %9 = load ptr, ptr %.addr2, align 8
  %10 = udiv exact i64 %6, 16
  %11 = getelementptr %struct.T, ptr %9, i64 %10
  %12 = load i64, ptr %.addr4, align 8
  %13 = load ptr, ptr %.addr5, align 8
  %omp.arrayinit.isarray = icmp sgt i64 %10, 1
  %14 = and i64 %12, 8
  %15 = icmp ne ptr %8, %9
  %16 = and i64 %12, 16
  %17 = icmp ne i64 %16, 0
  %18 = and i1 %15, %17
  %19 = or i1 %omp.arrayinit.isarray, %18
  %.omp.array..init..delete = icmp eq i64 %14, 0
  %20 = and i1 %19, %.omp.array..init..delete
  br i1 %20, label %.omp.array..init, label %omp.arraymap.head

.omp.array..init: ; preds = %entry
  %21 = mul nuw i64 %10, 16
  %22 = and i64 %12, -4
  %23 = or i64 %22, 512
  call void @__tgt_push_mapper_component(ptr %7, ptr %8, ptr %9, i64 %21, i64 
%23, ptr %13)
  br label %omp.arraymap.head

omp.arraymap.head:; preds = %.omp.array..init, 
%entry
  %omp.arraymap.isempty = icmp eq ptr %9, %11
  br i1 %omp.arraymap.isempty, label %omp.done, label %omp.arraymap.body

omp.arraymap.body:; preds = %omp.type.end19, 
%omp.arraymap.head
  %omp.arraymap.ptrcurrent = phi ptr [ %9, %omp.arraymap.head ], [ 
%omp.arraymap.next, %omp.type.end19 ]
  %ptr = getelementptr inbounds nuw %struct.T, ptr %omp.arraymap.ptrcurrent, 
i32 0, i32 0
  %ptr6 = getelementptr inbounds nuw %struct.T, ptr %omp.arraymap.ptrcurrent, 
i32 0, i32 0
  %24 = load ptr, ptr %ptr6, align 8
  %arrayidx = getelementptr inbounds nuw i32, ptr %24, i64 0
  %buf_size = getelementptr inbounds nuw %struct.T, ptr 
%omp.arraymap.ptrcurrent, i32 0, i32 1
  %25 = load i32, ptr %buf_size, align 8
  %conv = sext i32 %25 to i64
  %26 = mul nuw i64 %conv, 4
  %27 = getelementptr %struct.T, ptr %omp.arraymap.ptrcurrent, i32 1
  %28 = ptrtoint ptr %27 to i64
  %29 = ptrtoint ptr %omp.arraymap.ptrcurrent to i64
  %30 = sub i64 %28, %29
  %31 = sdiv exact i64 %30, ptrtoint (ptr getelementptr (i8, ptr null, i32 1) 
to i64)
  %32 = call i64 @__tgt_mapper_num_components(ptr %7)
  %33 = shl i64 %32, 48
  %34 = add nuw i64 0, %33
  %35 = and i64 %12, 3
  %36 = icmp eq i64 %35, 0
  br i1 %36, label %omp.type.alloc, label %omp.type.alloc.else

omp.type.alloc:   ; preds = %omp.arraymap.body
  %37 = and i64 %34, -4
  br label %omp.type.end

omp.type.alloc.else:  ; preds = %omp.arraymap.body
  %38 = icmp

[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2024-11-26 Thread Akash Banerjee via llvm-branch-commits


@@ -2701,7 +2701,42 @@ static void
 genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
const parser::OpenMPDeclareMapperConstruct &declareMapperConstruct) {
-  TODO(converter.getCurrentLocation(), "OpenMPDeclareMapperConstruct");
+  fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  lower::StatementContext stmtCtx;
+  const auto &spec =
+  std::get(declareMapperConstruct.t);
+  const auto &mapperName{std::get>(spec.t)};
+  const auto &varType{std::get(spec.t)};
+  const auto &varName{std::get(spec.t)};
+  assert(varType.declTypeSpec->category() ==
+ semantics::DeclTypeSpec::Category::TypeDerived &&
+ "Expected derived type");
+
+  std::string mapperNameStr;
+  if (mapperName.has_value())
+mapperNameStr = mapperName->ToString();
+  else
+mapperNameStr =
+"default_" + varType.declTypeSpec->derivedTypeSpec().name().ToString();
+
+  mlir::OpBuilder::InsertPoint insPt = firOpBuilder.saveInsertionPoint();
+  firOpBuilder.setInsertionPointToStart(converter.getModuleOp().getBody());
+  auto mlirType = converter.genType(varType.declTypeSpec->derivedTypeSpec());
+  auto varVal = firOpBuilder.createTemporaryAlloc(
+  converter.getCurrentLocation(), mlirType, varName.ToString());

TIFitis wrote:

@agozillon Do you have any insight or suggestion to handling the declMapperOp 
map clause one way or the other?

https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2024-11-26 Thread Akash Banerjee via llvm-branch-commits


@@ -2701,7 +2701,42 @@ static void
 genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
const parser::OpenMPDeclareMapperConstruct &declareMapperConstruct) {
-  TODO(converter.getCurrentLocation(), "OpenMPDeclareMapperConstruct");
+  fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  lower::StatementContext stmtCtx;
+  const auto &spec =
+  std::get(declareMapperConstruct.t);
+  const auto &mapperName{std::get>(spec.t)};
+  const auto &varType{std::get(spec.t)};
+  const auto &varName{std::get(spec.t)};
+  assert(varType.declTypeSpec->category() ==
+ semantics::DeclTypeSpec::Category::TypeDerived &&
+ "Expected derived type");
+
+  std::string mapperNameStr;
+  if (mapperName.has_value())
+mapperNameStr = mapperName->ToString();
+  else
+mapperNameStr =
+"default_" + varType.declTypeSpec->derivedTypeSpec().name().ToString();
+
+  mlir::OpBuilder::InsertPoint insPt = firOpBuilder.saveInsertionPoint();
+  firOpBuilder.setInsertionPointToStart(converter.getModuleOp().getBody());
+  auto mlirType = converter.genType(varType.declTypeSpec->derivedTypeSpec());
+  auto varVal = firOpBuilder.createTemporaryAlloc(
+  converter.getCurrentLocation(), mlirType, varName.ToString());

TIFitis wrote:

>From what I understand, declare mapper directive doesn't simply apply those 
>mapping rules as is to `%x` in your example, or at least not in the plain 
>manner suggested.

A new mapper function is emitted, and a pointer to this function is passed on 
to the runtime kernel call for target. The OMPRTL takes offload_mappers as the 
last argument, which is an array of pointers to the user defined mapper funcs.

If we go with the approach you are suggesting above, we would have to decouple 
the `map clause` from the declare mapper directive and have floating 
`mapInfoOps` in its nested region. This seems like an off approach to me. Also, 
we would need to handle this as a special case everywhere we handle regular map 
clauses, including the several lowering stages and passes like 
`mapInfoFinalization`.

If we really want to enforce the scoping rule for the declare mapper `var`, 
perhaps we can do so in the verifier to check that `%var` has a single use, 
i.e, the `declMapperOp`. Let me know if that sounds reasonable and we can leave 
the `%var` declaration just above the `declMapperOp`.

As for the placement of the `declMapperOp` at the Module level or Func level, I 
am undecided. The `declMapperOp` is in some sense akin to a function 
declaration and will be lowered into one eventually in the llvm IR. We're just 
delaying that process until we lower to llvm IR, as it saves us unnecessary 
work, and also we can share the lowering between Clang and MLIR through the 
OMPIRBUilder.

With that being said, as we are not planning on expanding it into a function at 
the MLIR level, I am not opposed to leaving it inside the func it's defined in 
to retain scoping rules. We can do so by changing the `declMapperOp` to no 
longer declare a symbol for itself, to prevent MLIR from complaining about 
`ModuleOp` not being it's parent.
This would mean that later when lowering map clauses, instead of doing a 
sym_table lookup for the mapper, we would have to scan the code for 
`declMapperOps` instead and match. This may be slightly inefficient, but I 
don't think should be too much of an issue.

Let me know what are your thoughts on this and how you'd like me to proceed :)

https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2024-11-26 Thread Akash Banerjee via llvm-branch-commits


@@ -2701,7 +2701,42 @@ static void
 genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
const parser::OpenMPDeclareMapperConstruct &declareMapperConstruct) {
-  TODO(converter.getCurrentLocation(), "OpenMPDeclareMapperConstruct");
+  fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  lower::StatementContext stmtCtx;
+  const auto &spec =
+  std::get(declareMapperConstruct.t);
+  const auto &mapperName{std::get>(spec.t)};
+  const auto &varType{std::get(spec.t)};
+  const auto &varName{std::get(spec.t)};
+  assert(varType.declTypeSpec->category() ==
+ semantics::DeclTypeSpec::Category::TypeDerived &&
+ "Expected derived type");
+
+  std::string mapperNameStr;
+  if (mapperName.has_value())
+mapperNameStr = mapperName->ToString();
+  else
+mapperNameStr =
+"default_" + varType.declTypeSpec->derivedTypeSpec().name().ToString();
+
+  mlir::OpBuilder::InsertPoint insPt = firOpBuilder.saveInsertionPoint();
+  firOpBuilder.setInsertionPointToStart(converter.getModuleOp().getBody());
+  auto mlirType = converter.genType(varType.declTypeSpec->derivedTypeSpec());
+  auto varVal = firOpBuilder.createTemporaryAlloc(
+  converter.getCurrentLocation(), mlirType, varName.ToString());

TIFitis wrote:

Nesting the mapInfo inside the region can be made to work.

I am just wary that it leads to unnecessary changes in a lot of other code base 
and introducing a corner case for the mapClause(mapEntries) itself.

Also, I'm not sure what we stand to gain from this approach. Every other 
instance of where a directive has a mapClause associated with it, does so by 
creating the map related Ops just above it. Why are we nesting them in case of 
declMapperOp?

https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2024-11-25 Thread Akash Banerjee via llvm-branch-commits


@@ -2701,7 +2701,42 @@ static void
 genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
const parser::OpenMPDeclareMapperConstruct &declareMapperConstruct) {
-  TODO(converter.getCurrentLocation(), "OpenMPDeclareMapperConstruct");
+  fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  lower::StatementContext stmtCtx;
+  const auto &spec =
+  std::get(declareMapperConstruct.t);
+  const auto &mapperName{std::get>(spec.t)};
+  const auto &varType{std::get(spec.t)};
+  const auto &varName{std::get(spec.t)};
+  assert(varType.declTypeSpec->category() ==
+ semantics::DeclTypeSpec::Category::TypeDerived &&
+ "Expected derived type");
+
+  std::string mapperNameStr;
+  if (mapperName.has_value())
+mapperNameStr = mapperName->ToString();
+  else
+mapperNameStr =
+"default_" + varType.declTypeSpec->derivedTypeSpec().name().ToString();
+
+  mlir::OpBuilder::InsertPoint insPt = firOpBuilder.saveInsertionPoint();
+  firOpBuilder.setInsertionPointToStart(converter.getModuleOp().getBody());
+  auto mlirType = converter.genType(varType.declTypeSpec->derivedTypeSpec());
+  auto varVal = firOpBuilder.createTemporaryAlloc(
+  converter.getCurrentLocation(), mlirType, varName.ToString());

TIFitis wrote:

>From what I understood when trying to implement this lowering: 
The `declMapperOp's` `parentOp` must have a symbol table as it declares a new 
symbol, this is why I hoisted it to the `ModuleOp` from the `funcOp`.

The `declMapperOp` also relies on a var definition which is immediately used in 
it's map clause. I can't put this var inside a region, as then it can't be used 
in the map clause. As such, this new `alloc` is also moved to just before the 
`declMapperOp`.

Do you have any suggestion to do this in a different way?

https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2024-11-25 Thread Akash Banerjee via llvm-branch-commits


@@ -2701,7 +2701,42 @@ static void
 genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
const parser::OpenMPDeclareMapperConstruct &declareMapperConstruct) {
-  TODO(converter.getCurrentLocation(), "OpenMPDeclareMapperConstruct");
+  fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  lower::StatementContext stmtCtx;
+  const auto &spec =
+  std::get(declareMapperConstruct.t);
+  const auto &mapperName{std::get>(spec.t)};
+  const auto &varType{std::get(spec.t)};
+  const auto &varName{std::get(spec.t)};
+  assert(varType.declTypeSpec->category() ==
+ semantics::DeclTypeSpec::Category::TypeDerived &&
+ "Expected derived type");
+
+  std::string mapperNameStr;
+  if (mapperName.has_value())
+mapperNameStr = mapperName->ToString();
+  else
+mapperNameStr =
+"default_" + varType.declTypeSpec->derivedTypeSpec().name().ToString();
+
+  mlir::OpBuilder::InsertPoint insPt = firOpBuilder.saveInsertionPoint();
+  firOpBuilder.setInsertionPointToStart(converter.getModuleOp().getBody());
+  auto mlirType = converter.genType(varType.declTypeSpec->derivedTypeSpec());
+  auto varVal = firOpBuilder.createTemporaryAlloc(
+  converter.getCurrentLocation(), mlirType, varName.ToString());

TIFitis wrote:

> Therefore I don't think it is right to be pushing this to the module scope in 
> case there are conflicting mappers declared in different scopes in the same 
> module.

It isn't my intention to move the `declMapperOp` to the module scope, but 
rather MLIR is forcing me to. If there's an alternative I'm missing where I can 
keep the declMapperOp within the func/block where it was declared, I'd much 
rather do that. In case there is no way to do that in MLIR, I can prepend the 
name of the function to the module scope declaration to prevent conflicts.

> So it should be treated as though this parse node is a variable declaration 
> so `createTemporaryAlloc` would be appropriate if this is inside of a 
> function, but if it is not, this should probably be a `fir.global` (like if 
> you declared a module- or file-level variable).

If we go forward with keeping the `declMapperOp` in the module scope, then I'll 
alter the `var` declaration to be a `fir.global`.



https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2024-12-03 Thread Akash Banerjee via llvm-branch-commits


@@ -2701,7 +2701,42 @@ static void
 genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
const parser::OpenMPDeclareMapperConstruct &declareMapperConstruct) {
-  TODO(converter.getCurrentLocation(), "OpenMPDeclareMapperConstruct");
+  fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  lower::StatementContext stmtCtx;
+  const auto &spec =
+  std::get(declareMapperConstruct.t);
+  const auto &mapperName{std::get>(spec.t)};
+  const auto &varType{std::get(spec.t)};
+  const auto &varName{std::get(spec.t)};
+  assert(varType.declTypeSpec->category() ==
+ semantics::DeclTypeSpec::Category::TypeDerived &&
+ "Expected derived type");
+
+  std::string mapperNameStr;
+  if (mapperName.has_value())
+mapperNameStr = mapperName->ToString();
+  else
+mapperNameStr =
+"default_" + varType.declTypeSpec->derivedTypeSpec().name().ToString();
+
+  mlir::OpBuilder::InsertPoint insPt = firOpBuilder.saveInsertionPoint();
+  firOpBuilder.setInsertionPointToStart(converter.getModuleOp().getBody());
+  auto mlirType = converter.genType(varType.declTypeSpec->derivedTypeSpec());
+  auto varVal = firOpBuilder.createTemporaryAlloc(
+  converter.getCurrentLocation(), mlirType, varName.ToString());

TIFitis wrote:

@kiranchandramohan @tblah @skatrak @agozillon Any thoughts on this approach?

https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2024-12-03 Thread Akash Banerjee via llvm-branch-commits


@@ -2701,7 +2701,42 @@ static void
 genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
const parser::OpenMPDeclareMapperConstruct &declareMapperConstruct) {
-  TODO(converter.getCurrentLocation(), "OpenMPDeclareMapperConstruct");
+  fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  lower::StatementContext stmtCtx;
+  const auto &spec =
+  std::get(declareMapperConstruct.t);
+  const auto &mapperName{std::get>(spec.t)};
+  const auto &varType{std::get(spec.t)};
+  const auto &varName{std::get(spec.t)};
+  assert(varType.declTypeSpec->category() ==
+ semantics::DeclTypeSpec::Category::TypeDerived &&
+ "Expected derived type");
+
+  std::string mapperNameStr;
+  if (mapperName.has_value())
+mapperNameStr = mapperName->ToString();
+  else
+mapperNameStr =
+"default_" + varType.declTypeSpec->derivedTypeSpec().name().ToString();
+
+  mlir::OpBuilder::InsertPoint insPt = firOpBuilder.saveInsertionPoint();
+  firOpBuilder.setInsertionPointToStart(converter.getModuleOp().getBody());
+  auto mlirType = converter.genType(varType.declTypeSpec->derivedTypeSpec());
+  auto varVal = firOpBuilder.createTemporaryAlloc(
+  converter.getCurrentLocation(), mlirType, varName.ToString());

TIFitis wrote:

> You should feel free to proceed with the approval of @agozillon and @skatrak.
Thanks for the go ahead, I'll consult with them before proceeding, and post any 
relevant findings here.

> > Inside DeclMapperOp's region I've introduce a new DeclMapperInfoOp to which 
> > I've attached the MapClause. Not having any MapClause explicitly associated 
> > seemed weird to me, also walking through the region collecting all the 
> > MapInfoOps for processing in various places in the code base seemed like a 
> > bad design to me.
> 
> The idea would generally be to inline the whole declare mapper operation 
> region, replacing the block_arg with the real variable that is going to be 
> mapped. Would an alloca always be created for all kinds of mappings? If not 
> committing to an alloca might mean you have to delete it in some 
> circumstances.

In case of DeclareMapper the mapping is handled in a ad-hoc basis. There is no 
real variable to be replaced later. The variable simply exists as a dummy to 
represent the mapping information for other real variables where the mapping 
would be used. However, this mapping isn't applied directly to those variables 
either, rather the runtime is notified that a mapper function exists for these 
variables.

> > We can drop the entire DeclMapperOp including the region once it reaches 
> > OpenMPTOLLVMIRTranslation.
> 
> As in just drop it without using it? Or using it create the 
> `@.omp_mapper._ZTS1T.deep_copy` function for the declare mapper (`#pragma omp 
> declare mapper(deep_copy : T abc) map(abc, abc.ptr[ : abc.buf_size])`) in the 
> C example you gave below.
Yes, I mean't each declareMapperOp would be resolved to a function like 
`@.omp_mapper._ZTS1T.deep_copy`. By dropping it, I mean't it's region won't be 
separately lowered.

> You have not talked about the following two points.
> 
> ```
> -> where we create the map_entries for the relevant operations (like target) 
> for which the declare mapper implicitly applies. Currently, this is done 
> during lowering. But in this patch you have solely focused on creating the 
> declare mapper.
> -> where the composition of map-types (map-type decay) from the map clause of 
> declare mapper and the map clause of the relevant operation (like target) 
> happens
> ```

I'll address the implicit mapping either in the DeclMapper lowering support for 
the mapClause or a separate PR soon after that.

The composition of mapClause AFAIK is likely handled in the OMPIRBuilder. If 
that's not the case, I'll address it in a future patch. 

> Couple of other things that came to my mind : -> Since declare mappers are in 
> the specification section, it can also occur in modules. We have not added 
> code to propagate it to the module file. If this is not urgent for you, I can 
> fix it sometime. 

Please feel free to do this if you're already familiar with what needs to be 
done, as I'm not. Otherwise, I can add it to my TODO list :)

-> You should test the case where the declare mapper is in the host subroutine
> 
> ```
> subroutine A
> type t
> end type
> declare mapper(t)
> contains
> subroutine B
> !$omp target 
> ! use a var of type t
> !$omp end target
> end subroutine
> ```

Thanks, I'll test this in the mapClause mapper support PR once I have it ready.

Many thanks for the review.



https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP custom mappers in map clause (PR #121001)

2024-12-28 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis edited 
https://github.com/llvm/llvm-project/pull/121001
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2025-02-03 Thread Akash Banerjee via llvm-branch-commits

TIFitis wrote:

Polite request for review 🙂

https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2025-02-03 Thread Akash Banerjee via llvm-branch-commits


@@ -2612,7 +2612,54 @@ static void
 genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
const parser::OpenMPDeclareMapperConstruct &declareMapperConstruct) {
-  TODO(converter.getCurrentLocation(), "OpenMPDeclareMapperConstruct");
+  mlir::Location loc = converter.genLocation(declareMapperConstruct.source);
+  fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  lower::StatementContext stmtCtx;
+  const auto &spec =
+  std::get(declareMapperConstruct.t);
+  const auto &mapperName{std::get>(spec.t)};
+  const auto &varType{std::get(spec.t)};
+  const auto &varName{std::get(spec.t)};
+  assert(varType.declTypeSpec->category() ==
+ semantics::DeclTypeSpec::Category::TypeDerived &&
+ "Expected derived type");
+
+  std::string mapperNameStr;
+  if (mapperName.has_value()) {
+mapperNameStr = mapperName->ToString();
+mapperNameStr =
+converter.mangleName(mapperNameStr, mapperName->symbol->owner());
+  } else {
+mapperNameStr =
+varType.declTypeSpec->derivedTypeSpec().name().ToString() + ".default";
+mapperNameStr = converter.mangleName(
+mapperNameStr, *varType.declTypeSpec->derivedTypeSpec().GetScope());
+  }
+
+  // Save insert point just after the DeclMapperOp.
+  mlir::OpBuilder::InsertPoint insPt = firOpBuilder.saveInsertionPoint();

TIFitis wrote:

Done :)

https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-01-31 Thread Akash Banerjee via llvm-branch-commits


@@ -2709,13 +2709,23 @@ getRefPtrIfDeclareTarget(mlir::Value value,
 }
 
 namespace {
+// Append customMappers information to existing MapInfosTy
+struct MapInfosTy : llvm::OpenMPIRBuilder::MapInfosTy {
+  SmallVector Mappers;

TIFitis wrote:

Yes, we can do that, but I don't think we should. Semantically they are used in 
different stages for different purposes. We don't stand to gain much from 
merging these two types, and using the same type might only lead to confusion 
in the future.

If anything, using the two different types should have a slightly less memory 
footprint, as we don't need any of the `mapInfoData` specific members during 
CodeGen in `OMPIRBuilder`.

https://github.com/llvm/llvm-project/pull/124746
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [flang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-01-31 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/124746

>From 5ca5a1f7c1e33949f8e0d32a4c94645842432559 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Tue, 28 Jan 2025 15:45:55 +
Subject: [PATCH 1/8] Add description for mapper_id. Add verifier check for
 valid mapper_id.

---
 mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td |  2 ++
 mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp  |  6 ++
 mlir/test/Dialect/OpenMP/invalid.mlir | 10 ++
 3 files changed, 18 insertions(+)

diff --git a/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td 
b/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
index 7cc2c8fa8ce1e1..326b5d0122f3ba 100644
--- a/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
+++ b/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
@@ -1054,6 +1054,8 @@ def MapInfoOp : OpenMP_Op<"map.info", 
[AttrSizedOperandSegments]> {
 - 'map_type': OpenMP map type for this map capture, for example: from, to 
and
always. It's a bitfield composed of the OpenMP runtime flags stored in
OpenMPOffloadMappingFlags.
+- 'mapper_id': OpenMP mapper map type modifier for this map capture. It's 
used to
+   specify a user defined mapper to be used for mapping.
 - 'map_capture_type': Capture type for the variable e.g. this, byref, 
byvalue, byvla
this can affect how the variable is lowered.
 - `name`: Holds the name of variable as specified in user clause 
(including bounds).
diff --git a/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp 
b/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
index 92233654ba1ddc..6fc1495938fe55 100644
--- a/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
+++ b/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
@@ -1592,6 +1592,12 @@ static LogicalResult verifyMapClause(Operation *op, 
OperandRange mapVars) {
 
 to ? updateToVars.insert(updateVar) : updateFromVars.insert(updateVar);
   }
+
+  if (mapInfoOp.getMapperId() &&
+  !SymbolTable::lookupNearestSymbolFrom(
+  mapInfoOp, mapInfoOp.getMapperIdAttr())) {
+return emitError(op->getLoc(), "invalid mapper id");
+  }
 } else if (!isa(op)) {
   emitError(op->getLoc(), "map argument is not a map entry operation");
 }
diff --git a/mlir/test/Dialect/OpenMP/invalid.mlir 
b/mlir/test/Dialect/OpenMP/invalid.mlir
index 1fbb4c93e855b9..93db9eb08aac98 100644
--- a/mlir/test/Dialect/OpenMP/invalid.mlir
+++ b/mlir/test/Dialect/OpenMP/invalid.mlir
@@ -2661,3 +2661,13 @@ func.func @missing_workshare(%idx : index) {
   }
   return
 }
+
+// -
+llvm.func @invalid_mapper(%0 : !llvm.ptr) {
+  %1 = omp.map.info var_ptr(%0 : !llvm.ptr, !llvm.struct<"my_type", (i32)>) 
mapper(@my_mapper) map_clauses(to) capture(ByRef) -> !llvm.ptr {name = ""}
+  // expected-error @below {{invalid mapper id}}
+  omp.target_data map_entries(%1 : !llvm.ptr) {
+omp.terminator
+  }
+  llvm.return
+}

>From a00e7f9acc36dd019abe6a4f86f995c0724cfc74 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 19:05:30 +
Subject: [PATCH 2/8] Add mapper field to mapInfoOp.

---
 flang/test/Lower/OpenMP/map-mapper.f90 | 15 +++
 1 file changed, 15 insertions(+)
 create mode 100644 flang/test/Lower/OpenMP/map-mapper.f90

diff --git a/flang/test/Lower/OpenMP/map-mapper.f90 
b/flang/test/Lower/OpenMP/map-mapper.f90
new file mode 100644
index 00..e7fded3034406e
--- /dev/null
+++ b/flang/test/Lower/OpenMP/map-mapper.f90
@@ -0,0 +1,15 @@
+! RUN: %flang_fc1 -emit-hlfir -fopenmp -fopenmp-version=50 %s -o - | FileCheck 
%s
+program p
+   integer, parameter :: n = 256
+   real(8) :: a(256)
+   type t1
+  integer :: x
+   end type t1
+   !$omp declare mapper(xx : t1 :: nn) map(nn, nn%x)
+   !$omp target map(mapper(xx), from:a)
+!CHECK: not yet implemented: Support for mapper modifiers is not implemented 
yet
+   do i = 1, n
+  a(i) = 4.2
+   end do
+   !$omp end target
+end program p

>From 4da7c864b77596a8697d1056cf23ba95e226d3ba Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 21:13:42 +
Subject: [PATCH 3/8] Add flang lowering changes for mapper field in map
 clause.

---
 flang/lib/Lower/OpenMP/ClauseProcessor.cpp  | 32 +
 flang/lib/Lower/OpenMP/ClauseProcessor.h|  3 +-
 flang/test/Lower/OpenMP/Todo/map-mapper.f90 | 16 ---
 flang/test/Lower/OpenMP/map-mapper.f90  | 20 +
 4 files changed, 43 insertions(+), 28 deletions(-)
 delete mode 100644 flang/test/Lower/OpenMP/Todo/map-mapper.f90

diff --git a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp 
b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
index 3c9831120351ee..0bc9f4919330e4 100644
--- a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
+++ b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
@@ -936,8 +936,10 @@ void ClauseProcessor::processMapObjects(
 llvm::omp::OpenMPOffloadMappingFlags mapTypeBits,
 std::map &parentMemberIndices,
 llvm::SmallVectorImpl &mapVars,
-llvm::SmallVectorImpl &mapSyms) const {
+

[llvm-branch-commits] [clang] [flang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-01-31 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/124746

>From 5ca5a1f7c1e33949f8e0d32a4c94645842432559 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Tue, 28 Jan 2025 15:45:55 +
Subject: [PATCH 1/8] Add description for mapper_id. Add verifier check for
 valid mapper_id.

---
 mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td |  2 ++
 mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp  |  6 ++
 mlir/test/Dialect/OpenMP/invalid.mlir | 10 ++
 3 files changed, 18 insertions(+)

diff --git a/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td 
b/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
index 7cc2c8fa8ce1e1..326b5d0122f3ba 100644
--- a/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
+++ b/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
@@ -1054,6 +1054,8 @@ def MapInfoOp : OpenMP_Op<"map.info", 
[AttrSizedOperandSegments]> {
 - 'map_type': OpenMP map type for this map capture, for example: from, to 
and
always. It's a bitfield composed of the OpenMP runtime flags stored in
OpenMPOffloadMappingFlags.
+- 'mapper_id': OpenMP mapper map type modifier for this map capture. It's 
used to
+   specify a user defined mapper to be used for mapping.
 - 'map_capture_type': Capture type for the variable e.g. this, byref, 
byvalue, byvla
this can affect how the variable is lowered.
 - `name`: Holds the name of variable as specified in user clause 
(including bounds).
diff --git a/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp 
b/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
index 92233654ba1ddc..6fc1495938fe55 100644
--- a/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
+++ b/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
@@ -1592,6 +1592,12 @@ static LogicalResult verifyMapClause(Operation *op, 
OperandRange mapVars) {
 
 to ? updateToVars.insert(updateVar) : updateFromVars.insert(updateVar);
   }
+
+  if (mapInfoOp.getMapperId() &&
+  !SymbolTable::lookupNearestSymbolFrom(
+  mapInfoOp, mapInfoOp.getMapperIdAttr())) {
+return emitError(op->getLoc(), "invalid mapper id");
+  }
 } else if (!isa(op)) {
   emitError(op->getLoc(), "map argument is not a map entry operation");
 }
diff --git a/mlir/test/Dialect/OpenMP/invalid.mlir 
b/mlir/test/Dialect/OpenMP/invalid.mlir
index 1fbb4c93e855b9..93db9eb08aac98 100644
--- a/mlir/test/Dialect/OpenMP/invalid.mlir
+++ b/mlir/test/Dialect/OpenMP/invalid.mlir
@@ -2661,3 +2661,13 @@ func.func @missing_workshare(%idx : index) {
   }
   return
 }
+
+// -
+llvm.func @invalid_mapper(%0 : !llvm.ptr) {
+  %1 = omp.map.info var_ptr(%0 : !llvm.ptr, !llvm.struct<"my_type", (i32)>) 
mapper(@my_mapper) map_clauses(to) capture(ByRef) -> !llvm.ptr {name = ""}
+  // expected-error @below {{invalid mapper id}}
+  omp.target_data map_entries(%1 : !llvm.ptr) {
+omp.terminator
+  }
+  llvm.return
+}

>From 45f5e9769f49b5550cea647a775584e019f5dbbc Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 19:05:30 +
Subject: [PATCH 2/8] Add mapper field to mapInfoOp.

---
 flang/test/Lower/OpenMP/map-mapper.f90 | 15 +++
 1 file changed, 15 insertions(+)
 create mode 100644 flang/test/Lower/OpenMP/map-mapper.f90

diff --git a/flang/test/Lower/OpenMP/map-mapper.f90 
b/flang/test/Lower/OpenMP/map-mapper.f90
new file mode 100644
index 00..e7fded3034406e
--- /dev/null
+++ b/flang/test/Lower/OpenMP/map-mapper.f90
@@ -0,0 +1,15 @@
+! RUN: %flang_fc1 -emit-hlfir -fopenmp -fopenmp-version=50 %s -o - | FileCheck 
%s
+program p
+   integer, parameter :: n = 256
+   real(8) :: a(256)
+   type t1
+  integer :: x
+   end type t1
+   !$omp declare mapper(xx : t1 :: nn) map(nn, nn%x)
+   !$omp target map(mapper(xx), from:a)
+!CHECK: not yet implemented: Support for mapper modifiers is not implemented 
yet
+   do i = 1, n
+  a(i) = 4.2
+   end do
+   !$omp end target
+end program p

>From 2869c270d45bbb33612843e9e3d2ed84730a18fa Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 21:13:42 +
Subject: [PATCH 3/8] Add flang lowering changes for mapper field in map
 clause.

---
 flang/lib/Lower/OpenMP/ClauseProcessor.cpp  | 32 +
 flang/lib/Lower/OpenMP/ClauseProcessor.h|  3 +-
 flang/test/Lower/OpenMP/Todo/map-mapper.f90 | 16 ---
 flang/test/Lower/OpenMP/map-mapper.f90  | 20 +
 4 files changed, 43 insertions(+), 28 deletions(-)
 delete mode 100644 flang/test/Lower/OpenMP/Todo/map-mapper.f90

diff --git a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp 
b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
index 3c9831120351ee..0bc9f4919330e4 100644
--- a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
+++ b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
@@ -936,8 +936,10 @@ void ClauseProcessor::processMapObjects(
 llvm::omp::OpenMPOffloadMappingFlags mapTypeBits,
 std::map &parentMemberIndices,
 llvm::SmallVectorImpl &mapVars,
-llvm::SmallVectorImpl &mapSyms) const {
+

[llvm-branch-commits] [clang] [flang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-01-31 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/124746

>From 431c404dc125aa6b27f32b6019baebf603111f51 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Tue, 28 Jan 2025 15:45:55 +
Subject: [PATCH 1/5] Add description for mapper_id. Add verifier check for
 valid mapper_id.

---
 mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td |  2 ++
 mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp  |  6 ++
 mlir/test/Dialect/OpenMP/invalid.mlir | 10 ++
 3 files changed, 18 insertions(+)

diff --git a/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td 
b/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
index 7cc2c8fa8ce1e1..326b5d0122f3ba 100644
--- a/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
+++ b/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
@@ -1054,6 +1054,8 @@ def MapInfoOp : OpenMP_Op<"map.info", 
[AttrSizedOperandSegments]> {
 - 'map_type': OpenMP map type for this map capture, for example: from, to 
and
always. It's a bitfield composed of the OpenMP runtime flags stored in
OpenMPOffloadMappingFlags.
+- 'mapper_id': OpenMP mapper map type modifier for this map capture. It's 
used to
+   specify a user defined mapper to be used for mapping.
 - 'map_capture_type': Capture type for the variable e.g. this, byref, 
byvalue, byvla
this can affect how the variable is lowered.
 - `name`: Holds the name of variable as specified in user clause 
(including bounds).
diff --git a/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp 
b/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
index 92233654ba1ddc..6fc1495938fe55 100644
--- a/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
+++ b/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
@@ -1592,6 +1592,12 @@ static LogicalResult verifyMapClause(Operation *op, 
OperandRange mapVars) {
 
 to ? updateToVars.insert(updateVar) : updateFromVars.insert(updateVar);
   }
+
+  if (mapInfoOp.getMapperId() &&
+  !SymbolTable::lookupNearestSymbolFrom(
+  mapInfoOp, mapInfoOp.getMapperIdAttr())) {
+return emitError(op->getLoc(), "invalid mapper id");
+  }
 } else if (!isa(op)) {
   emitError(op->getLoc(), "map argument is not a map entry operation");
 }
diff --git a/mlir/test/Dialect/OpenMP/invalid.mlir 
b/mlir/test/Dialect/OpenMP/invalid.mlir
index 1fbb4c93e855b9..93db9eb08aac98 100644
--- a/mlir/test/Dialect/OpenMP/invalid.mlir
+++ b/mlir/test/Dialect/OpenMP/invalid.mlir
@@ -2661,3 +2661,13 @@ func.func @missing_workshare(%idx : index) {
   }
   return
 }
+
+// -
+llvm.func @invalid_mapper(%0 : !llvm.ptr) {
+  %1 = omp.map.info var_ptr(%0 : !llvm.ptr, !llvm.struct<"my_type", (i32)>) 
mapper(@my_mapper) map_clauses(to) capture(ByRef) -> !llvm.ptr {name = ""}
+  // expected-error @below {{invalid mapper id}}
+  omp.target_data map_entries(%1 : !llvm.ptr) {
+omp.terminator
+  }
+  llvm.return
+}

>From 728a8321b572553ac3fa853f785ab3e58d93e1f8 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Tue, 28 Jan 2025 15:28:29 +
Subject: [PATCH 2/5] Split test into two separate directives.

---
 flang/test/Lower/OpenMP/map-mapper.f90 | 13 ++---
 1 file changed, 10 insertions(+), 3 deletions(-)

diff --git a/flang/test/Lower/OpenMP/map-mapper.f90 
b/flang/test/Lower/OpenMP/map-mapper.f90
index 856fff834643e4..0d8fe7344bfab5 100644
--- a/flang/test/Lower/OpenMP/map-mapper.f90
+++ b/flang/test/Lower/OpenMP/map-mapper.f90
@@ -13,11 +13,18 @@ program p
 
type(t1) :: a, b
!CHECK: %[[MAP_A:.*]] = omp.map.info var_ptr(%{{.*}} : {{.*}}, {{.*}}) 
mapper(@_QQFxx) map_clauses(tofrom) capture(ByRef) -> {{.*}} {name = "a"}
+   !CHECK: omp.target map_entries(%[[MAP_A]] -> %{{.*}}, %{{.*}} -> %{{.*}} : 
{{.*}}, {{.*}}) {
+   !$omp target map(mapper(xx) : a)
+   do i = 1, n
+  a%x(i) = i
+   end do
+   !$omp end target
+
!CHECK: %[[MAP_B:.*]] = omp.map.info var_ptr(%{{.*}} : {{.*}}, {{.*}}) 
mapper(@_QQFt1.default) map_clauses(tofrom) capture(ByRef) -> {{.*}} {name = 
"b"}
-   !CHECK: omp.target map_entries(%[[MAP_A]] -> %{{.*}}, %[[MAP_B]] -> 
%{{.*}}, %{{.*}} -> %{{.*}}, %{{.*}} -> %{{.*}} : {{.*}}, {{.*}}, {{.*}}, 
{{.*}}) {
-   !$omp target map(mapper(xx) : a) map(mapper(default) : b)
+   !CHECK: omp.target map_entries(%[[MAP_B]] -> %{{.*}}, %{{.*}} -> %{{.*}} : 
{{.*}}, {{.*}}) {
+   !$omp target map(mapper(default) : b)
do i = 1, n
-  b%x(i) = a%x(i)
+  b%x(i) = i
end do
!$omp end target
 end program p

>From e020b174360a645f64e2a6562eece48ce8a97482 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Tue, 28 Jan 2025 13:38:13 +
Subject: [PATCH 3/5] [MLIR][OpenMP] Add LLVM translation support for OpenMP
 UserDefinedMappers

This patch adds OpenMPToLLVMIRTranslation support for the OpenMP Declare Mapper 
directive.

Since both MLIR and Clang now support custom mappers, I've made the relative 
params required instead of optional as well.

Depends on #121005
---
 clang/lib/CodeGen/CGOpenMPRuntime.cpp |  20 +-
 .../llvm

[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP custom mappers in map clause (PR #121001)

2025-01-31 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/121001

>From 44eafafd74ecbce7ed7c4a408fff6c82b4cc07e1 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 21:13:42 +
Subject: [PATCH 1/2] Add flang lowering changes for mapper field in map
 clause.

---
 flang/lib/Lower/OpenMP/ClauseProcessor.cpp  | 32 +
 flang/lib/Lower/OpenMP/ClauseProcessor.h|  3 +-
 flang/test/Lower/OpenMP/Todo/map-mapper.f90 | 16 ---
 flang/test/Lower/OpenMP/map-mapper.f90  | 23 +++
 4 files changed, 52 insertions(+), 22 deletions(-)
 delete mode 100644 flang/test/Lower/OpenMP/Todo/map-mapper.f90
 create mode 100644 flang/test/Lower/OpenMP/map-mapper.f90

diff --git a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp 
b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
index 3c9831120351ee..0bc9f4919330e4 100644
--- a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
+++ b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
@@ -936,8 +936,10 @@ void ClauseProcessor::processMapObjects(
 llvm::omp::OpenMPOffloadMappingFlags mapTypeBits,
 std::map &parentMemberIndices,
 llvm::SmallVectorImpl &mapVars,
-llvm::SmallVectorImpl &mapSyms) const {
+llvm::SmallVectorImpl &mapSyms,
+std::string mapperIdName) const {
   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  mlir::FlatSymbolRefAttr mapperId;
 
   for (const omp::Object &object : objects) {
 llvm::SmallVector bounds;
@@ -970,6 +972,20 @@ void ClauseProcessor::processMapObjects(
   }
 }
 
+if (!mapperIdName.empty()) {
+  if (mapperIdName == "default") {
+auto &typeSpec = object.sym()->owner().IsDerivedType()
+ ? *object.sym()->owner().derivedTypeSpec()
+ : object.sym()->GetType()->derivedTypeSpec();
+mapperIdName = typeSpec.name().ToString() + ".default";
+mapperIdName = converter.mangleName(mapperIdName, 
*typeSpec.GetScope());
+  }
+  assert(converter.getMLIRSymbolTable()->lookup(mapperIdName) &&
+ "mapper not found");
+  mapperId = mlir::FlatSymbolRefAttr::get(&converter.getMLIRContext(),
+  mapperIdName);
+  mapperIdName.clear();
+}
 // Explicit map captures are captured ByRef by default,
 // optimisation passes may alter this to ByCopy or other capture
 // types to optimise
@@ -983,7 +999,8 @@ void ClauseProcessor::processMapObjects(
 static_cast<
 std::underlying_type_t>(
 mapTypeBits),
-mlir::omp::VariableCaptureKind::ByRef, baseOp.getType());
+mlir::omp::VariableCaptureKind::ByRef, baseOp.getType(), false,
+mapperId);
 
 if (parentObj.has_value()) {
   parentMemberIndices[parentObj.value()].addChildIndexAndMapToParent(
@@ -1014,6 +1031,7 @@ bool ClauseProcessor::processMap(
 const auto &[mapType, typeMods, mappers, iterator, objects] = clause.t;
 llvm::omp::OpenMPOffloadMappingFlags mapTypeBits =
 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE;
+std::string mapperIdName;
 // If the map type is specified, then process it else Tofrom is the
 // default.
 Map::MapType type = mapType.value_or(Map::MapType::Tofrom);
@@ -1057,13 +1075,17 @@ bool ClauseProcessor::processMap(
"Support for iterator modifiers is not implemented yet");
 }
 if (mappers) {
-  TODO(currentLocation,
-   "Support for mapper modifiers is not implemented yet");
+  assert(mappers->size() == 1 && "more than one mapper");
+  mapperIdName = mappers->front().v.id().symbol->name().ToString();
+  if (mapperIdName != "default")
+mapperIdName = converter.mangleName(
+mapperIdName, mappers->front().v.id().symbol->owner());
 }
 
 processMapObjects(stmtCtx, clauseLocation,
   std::get(clause.t), mapTypeBits,
-  parentMemberIndices, result.mapVars, *ptrMapSyms);
+  parentMemberIndices, result.mapVars, *ptrMapSyms,
+  mapperIdName);
   };
 
   bool clauseFound = findRepeatableClause(process);
diff --git a/flang/lib/Lower/OpenMP/ClauseProcessor.h 
b/flang/lib/Lower/OpenMP/ClauseProcessor.h
index 7b047d4a7567ad..34eebf16ca17b0 100644
--- a/flang/lib/Lower/OpenMP/ClauseProcessor.h
+++ b/flang/lib/Lower/OpenMP/ClauseProcessor.h
@@ -171,7 +171,8 @@ class ClauseProcessor {
   llvm::omp::OpenMPOffloadMappingFlags mapTypeBits,
   std::map &parentMemberIndices,
   llvm::SmallVectorImpl &mapVars,
-  llvm::SmallVectorImpl &mapSyms) const;
+  llvm::SmallVectorImpl &mapSyms,
+  std::string mapperIdName = "") const;
 
   lower::AbstractConverter &converter;
   semantics::SemanticsContext &semaCtx;
diff --git a/flang/test/Lower/OpenMP/Todo/map-mapper.f90 
b/flang/test/Lower/OpenMP/Todo/map-mapper.f90
deleted file mode 100644
index 9554ffd5fda7bd..00
--- a/flang/test/Lo

[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add conversion support from FIR to LLVM Dialect for OMP DeclareMapper (PR #121005)

2025-01-31 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/121005

>From 5fe7a97dd2f1844ad4d538c0ee5bf47f44aefa95 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 21:50:03 +
Subject: [PATCH] Add OpenMP to LLVM dialect conversion support for
 DeclareMapperOp.

---
 .../Fir/convert-to-llvm-openmp-and-fir.fir| 27 --
 .../Conversion/OpenMPToLLVM/OpenMPToLLVM.cpp  | 50 +++
 .../OpenMPToLLVM/convert-to-llvmir.mlir   | 13 +
 3 files changed, 75 insertions(+), 15 deletions(-)

diff --git a/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir 
b/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
index 8e4e1fe824d9f5b..82f2aea3ad983c9 100644
--- a/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
+++ b/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
@@ -936,9 +936,9 @@ func.func @omp_map_info_descriptor_type_conversion(%arg0 : 
!fir.ref>, i32) 
map_clauses(tofrom) capture(ByRef) -> !fir.llvm_ptr> {name = ""}
   // CHECK: %[[DESC_MAP:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<(ptr, i64, i32, i8, i8, i8, i8)>) map_clauses(always, delete) 
capture(ByRef) members(%[[MEMBER_MAP]] : [0] : !llvm.ptr) -> !llvm.ptr {name = 
""}
   %2 = omp.map.info var_ptr(%arg0 : !fir.ref>>, 
!fir.box>) map_clauses(always, delete) capture(ByRef) members(%1 
: [0] : !fir.llvm_ptr>) -> !fir.ref>> 
{name = ""}
-  // CHECK: omp.target_exit_data map_entries(%[[DESC_MAP]] : !llvm.ptr) 
+  // CHECK: omp.target_exit_data map_entries(%[[DESC_MAP]] : !llvm.ptr)
   omp.target_exit_data   map_entries(%2 : !fir.ref>>)
-  return 
+  return
 }
 
 // -
@@ -956,8 +956,8 @@ func.func 
@omp_map_info_derived_type_explicit_member_conversion(%arg0 : !fir.ref
   %3 = fir.field_index real, 
!fir.type<_QFderived_type{real:f32,array:!fir.array<10xi32>,int:i32}>
   %4 = fir.coordinate_of %arg0, %3 : 
(!fir.ref,int:i32}>>,
 !fir.field) -> !fir.ref
   // CHECK: %[[MAP_MEMBER_2:.*]] = omp.map.info var_ptr(%[[GEP_2]] : 
!llvm.ptr, f32) map_clauses(tofrom) capture(ByRef) -> !llvm.ptr {name = 
"dtype%real"}
-  %5 = omp.map.info var_ptr(%4 : !fir.ref, f32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "dtype%real"}
-  // CHECK: %[[MAP_PARENT:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<"_QFderived_type", (f32, array<10 x i32>, i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[MAP_MEMBER_1]], %[[MAP_MEMBER_2]] 
: [2], [0] : !llvm.ptr, !llvm.ptr) -> !llvm.ptr {name = "dtype", partial_map = 
true} 
+  %5 = omp.map.info var_ptr(%4 : !fir.ref, f32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "dtype%real"}
+  // CHECK: %[[MAP_PARENT:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<"_QFderived_type", (f32, array<10 x i32>, i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[MAP_MEMBER_1]], %[[MAP_MEMBER_2]] 
: [2], [0] : !llvm.ptr, !llvm.ptr) -> !llvm.ptr {name = "dtype", partial_map = 
true}
   %6 = omp.map.info var_ptr(%arg0 : 
!fir.ref,int:i32}>>,
 !fir.type<_QFderived_type{real:f32,array:!fir.array<10xi32>,int:i32}>) 
map_clauses(tofrom) capture(ByRef) members(%2, %5 : [2], [0] : !fir.ref, 
!fir.ref) -> 
!fir.ref,int:i32}>> 
{name = "dtype", partial_map = true}
   // CHECK: omp.target map_entries(%[[MAP_MEMBER_1]] -> %[[ARG_1:.*]], 
%[[MAP_MEMBER_2]] -> %[[ARG_2:.*]], %[[MAP_PARENT]] -> %[[ARG_3:.*]] : 
!llvm.ptr, !llvm.ptr, !llvm.ptr) {
   omp.target map_entries(%2 -> %arg1, %5 -> %arg2, %6 -> %arg3 : 
!fir.ref, !fir.ref, 
!fir.ref,int:i32}>>)
 {
@@ -1275,3 +1275,22 @@ func.func @map_nested_dtype_alloca_mem2(%arg0 : 
!fir.ref {
+omp.declare_mapper @my_mapper : !fir.type<_QFdeclare_mapperTmy_type{data:i32}> 
{
+// CHECK: ^bb0(%[[VAL_0:.*]]: !llvm.ptr):
+^bb0(%0: !fir.ref>):
+// CHECK:   %[[VAL_1:.*]] = llvm.mlir.constant(0 : i32) : i32
+  %1 = fir.field_index data, !fir.type<_QFdeclare_mapperTmy_type{data:i32}>
+// CHECK:   %[[VAL_2:.*]] = llvm.getelementptr %[[VAL_0]][0, 0] : 
(!llvm.ptr) -> !llvm.ptr, !llvm.struct<"_QFdeclare_mapperTmy_type", (i32)>
+  %2 = fir.coordinate_of %0, %1 : 
(!fir.ref>, !fir.field) -> 
!fir.ref
+// CHECK:   %[[VAL_3:.*]] = omp.map.info var_ptr(%[[VAL_2]] : 
!llvm.ptr, i32) map_clauses(tofrom) capture(ByRef) -> !llvm.ptr {name = 
"var%[[VAL_4:.*]]"}
+  %3 = omp.map.info var_ptr(%2 : !fir.ref, i32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "var%data"}
+// CHECK:   %[[VAL_5:.*]] = omp.map.info var_ptr(%[[VAL_0]] : 
!llvm.ptr, !llvm.struct<"_QFdeclare_mapperTmy_type", (i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[VAL_3]] : [0] : !llvm.ptr) -> 
!llvm.ptr {name = "var", partial_map = true}
+  %4 = omp.map.info var_ptr(%0 : 
!fir.ref>, 
!fir.type<_QFdeclare_mapperTmy_type{data:i32}>) map_clauses(tofrom) 
capture(ByRef) members(%3 : [0] : !fir.ref) -> 
!fir.ref> {name = "var", 
partial_map = true}
+// CHECK:   omp.declare_mapper_info map_entries(%[[VAL_5]], %[[VAL_3]] 
: !llvm.ptr, !llvm.ptr)
+  omp.declare_mapper

[llvm-branch-commits] [clang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-01-31 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/124746

>From a8671fc83f026a692802d4eee25c91657228928b Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Tue, 28 Jan 2025 13:38:13 +
Subject: [PATCH 1/3] [MLIR][OpenMP] Add LLVM translation support for OpenMP
 UserDefinedMappers

This patch adds OpenMPToLLVMIRTranslation support for the OpenMP Declare Mapper 
directive.

Since both MLIR and Clang now support custom mappers, I've made the relative 
params required instead of optional as well.

Depends on #121005
---
 clang/lib/CodeGen/CGOpenMPRuntime.cpp |  20 +-
 .../llvm/Frontend/OpenMP/OMPIRBuilder.h   |  49 +++--
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp |  78 +++
 .../Frontend/OpenMPIRBuilderTest.cpp  |  56 +++--
 .../OpenMP/OpenMPToLLVMIRTranslation.cpp  | 198 ++
 mlir/test/Target/LLVMIR/omptarget-llvm.mlir   | 117 +++
 .../fortran/target-custom-mapper.f90  |  46 
 7 files changed, 443 insertions(+), 121 deletions(-)
 create mode 100644 offload/test/offloading/fortran/target-custom-mapper.f90

diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 30c3834de139c3..0a13581dcb1700 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -32,10 +32,12 @@
 #include "llvm/Bitcode/BitcodeReader.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/DerivedTypes.h"
+#include "llvm/IR/Function.h"
 #include "llvm/IR/GlobalValue.h"
 #include "llvm/IR/InstrTypes.h"
 #include "llvm/IR/Value.h"
 #include "llvm/Support/AtomicOrdering.h"
+#include "llvm/Support/Error.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -,8 +8890,8 @@ static void emitOffloadingArraysAndArgs(
 return MFunc;
   };
   OMPBuilder.emitOffloadingArraysAndArgs(
-  AllocaIP, CodeGenIP, Info, Info.RTArgs, CombinedInfo, IsNonContiguous,
-  ForEndCall, DeviceAddrCB, CustomMapperCB);
+  AllocaIP, CodeGenIP, Info, Info.RTArgs, CombinedInfo, CustomMapperCB,
+  IsNonContiguous, ForEndCall, DeviceAddrCB);
 }
 
 /// Check for inner distribute directive.
@@ -9098,9 +9100,10 @@ void CGOpenMPRuntime::emitUserDefinedMapper(const 
OMPDeclareMapperDecl *D,
   CGM.getCXXABI().getMangleContext().mangleCanonicalTypeName(Ty, Out);
   std::string Name = getName({"omp_mapper", TyStr, D->getName()});
 
-  auto *NewFn = OMPBuilder.emitUserDefinedMapper(PrivatizeAndGenMapInfoCB,
- ElemTy, Name, CustomMapperCB);
-  UDMMap.try_emplace(D, NewFn);
+  llvm::Expected NewFn = OMPBuilder.emitUserDefinedMapper(
+  PrivatizeAndGenMapInfoCB, ElemTy, Name, CustomMapperCB);
+  assert(NewFn && "Unexpected error in emitUserDefinedMapper");
+  UDMMap.try_emplace(D, *NewFn);
   if (CGF)
 FunctionUDMMap[CGF->CurFn].push_back(D);
 }
@@ -10092,9 +10095,10 @@ void CGOpenMPRuntime::emitTargetDataCalls(
   CGF.Builder.GetInsertPoint());
   llvm::OpenMPIRBuilder::LocationDescription OmpLoc(CodeGenIP);
   llvm::OpenMPIRBuilder::InsertPointOrErrorTy AfterIP =
-  OMPBuilder.createTargetData(
-  OmpLoc, AllocaIP, CodeGenIP, DeviceID, IfCondVal, Info, GenMapInfoCB,
-  /*MapperFunc=*/nullptr, BodyCB, DeviceAddrCB, CustomMapperCB, RTLoc);
+  OMPBuilder.createTargetData(OmpLoc, AllocaIP, CodeGenIP, DeviceID,
+  IfCondVal, Info, GenMapInfoCB, 
CustomMapperCB,
+  /*MapperFunc=*/nullptr, BodyCB, DeviceAddrCB,
+  RTLoc);
   assert(AfterIP && "unexpected error creating target data");
   CGF.Builder.restoreIP(*AfterIP);
 }
diff --git a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h 
b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
index 4ce47b1c05d9b0..4e80bff6db4553 100644
--- a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
+++ b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
@@ -22,6 +22,7 @@
 #include "llvm/IR/IRBuilder.h"
 #include "llvm/IR/Module.h"
 #include "llvm/Support/Allocator.h"
+#include "llvm/Support/Error.h"
 #include "llvm/TargetParser/Triple.h"
 #include 
 #include 
@@ -2355,6 +2356,7 @@ class OpenMPIRBuilder {
CurInfo.NonContigInfo.Strides.end());
 }
   };
+  using MapInfosOrErrorTy = Expected;
 
   /// Callback function type for functions emitting the host fallback code that
   /// is executed when the kernel launch fails. It takes an insertion point as
@@ -2431,9 +2433,9 @@ class OpenMPIRBuilder {
   /// including base pointers, pointers, sizes, map types, user-defined 
mappers.
   void emitOffloadingArrays(
   InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy 
&CombinedInfo,
-  TargetDataInfo &Info, bool IsNonContiguous = false,
-  function_ref DeviceAddrCB = nullptr,
-  function_ref CustomMapperCB = nullptr);
+  TargetDataInfo &Info, function_ref CustomMapperCB,
+  bool IsNonContiguo

[llvm-branch-commits] [clang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-01-31 Thread Akash Banerjee via llvm-branch-commits


@@ -3421,6 +3441,85 @@ static void genMapInfos(llvm::IRBuilderBase &builder,
   }
 }
 
+static llvm::Expected
+emitUserDefinedMapper(Operation *declMapperOp, llvm::IRBuilderBase &builder,
+  LLVM::ModuleTranslation &moduleTranslation);
+
+static llvm::Expected
+getOrCreateUserDefinedMapperFunc(Operation *declMapperOp,
+ llvm::IRBuilderBase &builder,
+ LLVM::ModuleTranslation &moduleTranslation) {
+  llvm::DenseMap userDefMapperMap;
+  auto iter = userDefMapperMap.find(declMapperOp);

TIFitis wrote:

Sorry, I intended to make `userDefMapperMap` a static variable. Fixed now.

https://github.com/llvm/llvm-project/pull/124746
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-01-31 Thread Akash Banerjee via llvm-branch-commits


@@ -3421,6 +3441,85 @@ static void genMapInfos(llvm::IRBuilderBase &builder,
   }
 }
 
+static llvm::Expected
+emitUserDefinedMapper(Operation *declMapperOp, llvm::IRBuilderBase &builder,
+  LLVM::ModuleTranslation &moduleTranslation);
+
+static llvm::Expected
+getOrCreateUserDefinedMapperFunc(Operation *declMapperOp,
+ llvm::IRBuilderBase &builder,
+ LLVM::ModuleTranslation &moduleTranslation) {
+  llvm::DenseMap userDefMapperMap;
+  auto iter = userDefMapperMap.find(declMapperOp);
+  if (iter != userDefMapperMap.end())
+return iter->second;
+  llvm::Expected mapperFunc =
+  emitUserDefinedMapper(declMapperOp, builder, moduleTranslation);
+  if (!mapperFunc)
+return mapperFunc.takeError();
+  userDefMapperMap.try_emplace(declMapperOp, *mapperFunc);
+  return userDefMapperMap.lookup(declMapperOp);
+}
+
+static llvm::Expected
+emitUserDefinedMapper(Operation *op, llvm::IRBuilderBase &builder,
+  LLVM::ModuleTranslation &moduleTranslation) {
+  auto declMapperOp = cast(op);
+  auto declMapperInfoOp =
+  *declMapperOp.getOps().begin();
+  DataLayout dl = DataLayout(declMapperOp->getParentOfType());
+  llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
+  llvm::Type *varType =
+  moduleTranslation.convertType(declMapperOp.getVarType());
+  std::string mapperName = ompBuilder->createPlatformSpecificName(
+  {"omp_mapper", declMapperOp.getSymName()});
+  SmallVector mapVars = declMapperInfoOp.getMapVars();
+
+  using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
+
+  // Fill up the arrays with all the mapped variables.
+  MapInfosTy combinedInfo;
+  auto genMapInfoCB =
+  [&](InsertPointTy codeGenIP, llvm::Value *ptrPHI,
+  llvm::Value *unused2) -> llvm::OpenMPIRBuilder::MapInfosOrErrorTy {
+builder.restoreIP(codeGenIP);
+moduleTranslation.mapValue(declMapperOp.getRegion().getArgument(0), 
ptrPHI);
+moduleTranslation.mapBlock(&declMapperOp.getRegion().front(),
+   builder.GetInsertBlock());
+if (failed(moduleTranslation.convertBlock(declMapperOp.getRegion().front(),
+  /*ignoreArguments=*/true,
+  builder)))
+  return llvm::make_error();
+MapInfoData mapData;
+collectMapDataFromMapOperands(mapData, mapVars, moduleTranslation, dl,
+  builder);
+genMapInfos(builder, moduleTranslation, dl, combinedInfo, mapData);
+
+// Drop the mapping that is no longer necessary so that the same region can
+// be processed multiple times.
+moduleTranslation.forgetMapping(declMapperOp.getRegion());
+return combinedInfo;
+  };
+
+  auto customMapperCB = [&](unsigned i, llvm::Function **mapperFunc) {
+if (combinedInfo.Mappers[i]) {
+  // Call the corresponding mapper function.
+  llvm::Expected newFn = 
getOrCreateUserDefinedMapperFunc(

TIFitis wrote:

I've updated the offloading test to trigger this recursion.

Worklist for something like this might be an overkill. Clang implements declare 
mapper in a similar recursive manner. Also, cyclic recursions are not possible 
in legal code.

Here's what the generated llvm IR looks like for the new test:

```
define void @_QQmain() {
  %.offload_baseptrs = alloca [2 x ptr], align 8
  %.offload_ptrs = alloca [2 x ptr], align 8
  %.offload_mappers = alloca [2 x ptr], align 8
  %1 = alloca { ptr, i64, i32, i8, i8, i8, i8, [1 x [3 x i64]] }, align 8
  %2 = alloca i32, i64 1, align 4
  %3 = alloca i32, i64 1, align 4
  %4 = alloca i32, i64 1, align 4
  br label %5

5:; preds = %9, %0
  %6 = phi i32 [ %18, %9 ], [ 1, %0 ]
  %7 = phi i64 [ %19, %9 ], [ 1024, %0 ]
  %8 = icmp sgt i64 %7, 0
  br i1 %8, label %9, label %20

9:; preds = %5
  store i32 %6, ptr %4, align 4
  %10 = load i32, ptr %4, align 4
  %11 = sext i32 %10 to i64
  %12 = sub nsw i64 %11, 1
  %13 = mul nsw i64 %12, 1
  %14 = mul nsw i64 %13, 1
  %15 = add nsw i64 %14, 0
  %16 = getelementptr i32, ptr @_QFEobj, i64 %15
  store i32 1, ptr %16, align 4
  %17 = load i32, ptr %4, align 4
  %18 = add nsw i32 %17, 1
  %19 = sub i64 %7, 1
  br label %5

20:   ; preds = %5
  store i32 %6, ptr %4, align 4
  store { ptr, i64, i32, i8, i8, i8, i8, [1 x [3 x i64]] } { ptr @_QFEobj, i64 
ptrtoint (ptr getelementptr (i32, ptr null, i32 1) to i64), i32 20240719, i8 1, 
i8 9, i8 0, i8 0, [1 x [3 x i64]] [[3 x i64] [i64 1, i64 1024, i64 ptrtoint 
(ptr getelementptr (i32, ptr null, i32 1) to i64)]] }, ptr %1, align 8
  %21 = call i32 @_FortranASumInteger4(ptr %1, ptr 
@_QQclXf46b0d060c890540d012b521bc3468aa, i32 21, i32 0, ptr null)
  store i32 %21, ptr %2, align 4
  store i32 0, ptr %3, align 4
  %22 = getel

[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add OMP Mapper field to MapInfoOp (PR #120994)

2025-02-07 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/120994

>From f7c3a6505a3affa159b178852c67cff5739f2c26 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 20:53:47 +
Subject: [PATCH 1/2] Add mapper field to mapInfoOp.

---
 flang/lib/Lower/OpenMP/Utils.cpp| 3 ++-
 flang/lib/Lower/OpenMP/Utils.h  | 3 ++-
 flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp  | 5 -
 flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp | 1 +
 mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td   | 2 ++
 mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp| 2 +-
 mlir/test/Dialect/OpenMP/ops.mlir   | 4 ++--
 7 files changed, 14 insertions(+), 6 deletions(-)

diff --git a/flang/lib/Lower/OpenMP/Utils.cpp b/flang/lib/Lower/OpenMP/Utils.cpp
index 35722fa7d1b1206..fa1975dac789b12 100644
--- a/flang/lib/Lower/OpenMP/Utils.cpp
+++ b/flang/lib/Lower/OpenMP/Utils.cpp
@@ -125,7 +125,7 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
 llvm::ArrayRef members,
 mlir::ArrayAttr membersIndex, uint64_t mapType,
 mlir::omp::VariableCaptureKind mapCaptureType, mlir::Type 
retTy,
-bool partialMap) {
+bool partialMap, mlir::FlatSymbolRefAttr mapperId) {
   if (auto boxTy = llvm::dyn_cast(baseAddr.getType())) {
 baseAddr = builder.create(loc, baseAddr);
 retTy = baseAddr.getType();
@@ -144,6 +144,7 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
   mlir::omp::MapInfoOp op = builder.create(
   loc, retTy, baseAddr, varType, varPtrPtr, members, membersIndex, bounds,
   builder.getIntegerAttr(builder.getIntegerType(64, false), mapType),
+  mapperId,
   builder.getAttr(mapCaptureType),
   builder.getStringAttr(name), builder.getBoolAttr(partialMap));
   return op;
diff --git a/flang/lib/Lower/OpenMP/Utils.h b/flang/lib/Lower/OpenMP/Utils.h
index f2e378443e5f295..3943eb633b04e36 100644
--- a/flang/lib/Lower/OpenMP/Utils.h
+++ b/flang/lib/Lower/OpenMP/Utils.h
@@ -116,7 +116,8 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
 llvm::ArrayRef members,
 mlir::ArrayAttr membersIndex, uint64_t mapType,
 mlir::omp::VariableCaptureKind mapCaptureType, mlir::Type 
retTy,
-bool partialMap = false);
+bool partialMap = false,
+mlir::FlatSymbolRefAttr mapperId = mlir::FlatSymbolRefAttr());
 
 void insertChildMapInfoIntoParent(
 Fortran::lower::AbstractConverter &converter,
diff --git a/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp 
b/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
index e7c1d1d9d560f87..beea7543e54b324 100644
--- a/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
+++ b/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
@@ -184,6 +184,7 @@ class MapInfoFinalizationPass
 /*members=*/mlir::SmallVector{},
 /*membersIndex=*/mlir::ArrayAttr{}, bounds,
 builder.getIntegerAttr(builder.getIntegerType(64, false), mapType),
+/*mapperId*/ mlir::FlatSymbolRefAttr(),
 builder.getAttr(
 mlir::omp::VariableCaptureKind::ByRef),
 /*name=*/builder.getStringAttr(""),
@@ -329,7 +330,8 @@ class MapInfoFinalizationPass
 builder.getIntegerAttr(
 builder.getIntegerType(64, false),
 getDescriptorMapType(op.getMapType().value_or(0), target)),
-op.getMapCaptureTypeAttr(), op.getNameAttr(),
+/*mapperId*/ mlir::FlatSymbolRefAttr(), op.getMapCaptureTypeAttr(),
+op.getNameAttr(),
 /*partial_map=*/builder.getBoolAttr(false));
 op.replaceAllUsesWith(newDescParentMapOp.getResult());
 op->erase();
@@ -623,6 +625,7 @@ class MapInfoFinalizationPass
   /*members=*/mlir::ValueRange{},
   /*members_index=*/mlir::ArrayAttr{},
   /*bounds=*/bounds, op.getMapTypeAttr(),
+  /*mapperId*/ mlir::FlatSymbolRefAttr(),
   builder.getAttr(
   mlir::omp::VariableCaptureKind::ByRef),
   builder.getStringAttr(op.getNameAttr().strref() + "." +
diff --git a/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp 
b/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
index 963ae863c1fc5cb..97ea463a3c495df 100644
--- a/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
+++ b/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
@@ -91,6 +91,7 @@ class MapsForPrivatizedSymbolsPass
 /*bounds=*/ValueRange{},
 builder.getIntegerAttr(builder.getIntegerType(64, /*isSigned=*/false),
mapTypeTo),
+/*mapperId*/ mlir::FlatSymbolRefAttr(),
 builder.getAttr(
 omp::VariableCaptureKind::ByRef),
 StringAttr(), builder.getBoolAttr(false));
diff --git a/ml

[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP custom mappers in map clause (PR #121001)

2025-02-07 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/121001

>From 64e17c3992cc89aa02148b2b0e9319552a9ca63f Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 21:13:42 +
Subject: [PATCH 1/3] Add flang lowering changes for mapper field in map
 clause.

---
 flang/lib/Lower/OpenMP/ClauseProcessor.cpp  | 32 +
 flang/lib/Lower/OpenMP/ClauseProcessor.h|  3 +-
 flang/test/Lower/OpenMP/Todo/map-mapper.f90 | 16 ---
 flang/test/Lower/OpenMP/map-mapper.f90  | 23 +++
 4 files changed, 52 insertions(+), 22 deletions(-)
 delete mode 100644 flang/test/Lower/OpenMP/Todo/map-mapper.f90
 create mode 100644 flang/test/Lower/OpenMP/map-mapper.f90

diff --git a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp 
b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
index febc6adcf9d6ff4..467a0dcebf2b8a9 100644
--- a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
+++ b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
@@ -969,8 +969,10 @@ void ClauseProcessor::processMapObjects(
 llvm::omp::OpenMPOffloadMappingFlags mapTypeBits,
 std::map &parentMemberIndices,
 llvm::SmallVectorImpl &mapVars,
-llvm::SmallVectorImpl &mapSyms) const {
+llvm::SmallVectorImpl &mapSyms,
+std::string mapperIdName) const {
   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  mlir::FlatSymbolRefAttr mapperId;
 
   for (const omp::Object &object : objects) {
 llvm::SmallVector bounds;
@@ -1003,6 +1005,20 @@ void ClauseProcessor::processMapObjects(
   }
 }
 
+if (!mapperIdName.empty()) {
+  if (mapperIdName == "default") {
+auto &typeSpec = object.sym()->owner().IsDerivedType()
+ ? *object.sym()->owner().derivedTypeSpec()
+ : object.sym()->GetType()->derivedTypeSpec();
+mapperIdName = typeSpec.name().ToString() + ".default";
+mapperIdName = converter.mangleName(mapperIdName, 
*typeSpec.GetScope());
+  }
+  assert(converter.getMLIRSymbolTable()->lookup(mapperIdName) &&
+ "mapper not found");
+  mapperId = mlir::FlatSymbolRefAttr::get(&converter.getMLIRContext(),
+  mapperIdName);
+  mapperIdName.clear();
+}
 // Explicit map captures are captured ByRef by default,
 // optimisation passes may alter this to ByCopy or other capture
 // types to optimise
@@ -1016,7 +1032,8 @@ void ClauseProcessor::processMapObjects(
 static_cast<
 std::underlying_type_t>(
 mapTypeBits),
-mlir::omp::VariableCaptureKind::ByRef, baseOp.getType());
+mlir::omp::VariableCaptureKind::ByRef, baseOp.getType(), false,
+mapperId);
 
 if (parentObj.has_value()) {
   parentMemberIndices[parentObj.value()].addChildIndexAndMapToParent(
@@ -1047,6 +1064,7 @@ bool ClauseProcessor::processMap(
 const auto &[mapType, typeMods, mappers, iterator, objects] = clause.t;
 llvm::omp::OpenMPOffloadMappingFlags mapTypeBits =
 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE;
+std::string mapperIdName;
 // If the map type is specified, then process it else Tofrom is the
 // default.
 Map::MapType type = mapType.value_or(Map::MapType::Tofrom);
@@ -1090,13 +1108,17 @@ bool ClauseProcessor::processMap(
"Support for iterator modifiers is not implemented yet");
 }
 if (mappers) {
-  TODO(currentLocation,
-   "Support for mapper modifiers is not implemented yet");
+  assert(mappers->size() == 1 && "more than one mapper");
+  mapperIdName = mappers->front().v.id().symbol->name().ToString();
+  if (mapperIdName != "default")
+mapperIdName = converter.mangleName(
+mapperIdName, mappers->front().v.id().symbol->owner());
 }
 
 processMapObjects(stmtCtx, clauseLocation,
   std::get(clause.t), mapTypeBits,
-  parentMemberIndices, result.mapVars, *ptrMapSyms);
+  parentMemberIndices, result.mapVars, *ptrMapSyms,
+  mapperIdName);
   };
 
   bool clauseFound = findRepeatableClause(process);
diff --git a/flang/lib/Lower/OpenMP/ClauseProcessor.h 
b/flang/lib/Lower/OpenMP/ClauseProcessor.h
index e05f66c7666844f..2b319e890a5adbe 100644
--- a/flang/lib/Lower/OpenMP/ClauseProcessor.h
+++ b/flang/lib/Lower/OpenMP/ClauseProcessor.h
@@ -175,7 +175,8 @@ class ClauseProcessor {
   llvm::omp::OpenMPOffloadMappingFlags mapTypeBits,
   std::map &parentMemberIndices,
   llvm::SmallVectorImpl &mapVars,
-  llvm::SmallVectorImpl &mapSyms) const;
+  llvm::SmallVectorImpl &mapSyms,
+  std::string mapperIdName = "") const;
 
   lower::AbstractConverter &converter;
   semantics::SemanticsContext &semaCtx;
diff --git a/flang/test/Lower/OpenMP/Todo/map-mapper.f90 
b/flang/test/Lower/OpenMP/Todo/map-mapper.f90
deleted file mode 100644
index 9554ffd5fda7bdd..000
--- a/fla

[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add conversion support from FIR to LLVM Dialect for OMP DeclareMapper (PR #121005)

2025-02-07 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/121005

>From c993ac570b1788867be44690f87cf8ccafb97534 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 21:50:03 +
Subject: [PATCH 1/2] Add OpenMP to LLVM dialect conversion support for
 DeclareMapperOp.

---
 .../Fir/convert-to-llvm-openmp-and-fir.fir| 27 +--
 .../Conversion/OpenMPToLLVM/OpenMPToLLVM.cpp  | 48 +++
 .../OpenMPToLLVM/convert-to-llvmir.mlir   | 13 +
 3 files changed, 74 insertions(+), 14 deletions(-)

diff --git a/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir 
b/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
index 8e4e1fe824d9f5b..82f2aea3ad983c9 100644
--- a/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
+++ b/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
@@ -936,9 +936,9 @@ func.func @omp_map_info_descriptor_type_conversion(%arg0 : 
!fir.ref>, i32) 
map_clauses(tofrom) capture(ByRef) -> !fir.llvm_ptr> {name = ""}
   // CHECK: %[[DESC_MAP:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<(ptr, i64, i32, i8, i8, i8, i8)>) map_clauses(always, delete) 
capture(ByRef) members(%[[MEMBER_MAP]] : [0] : !llvm.ptr) -> !llvm.ptr {name = 
""}
   %2 = omp.map.info var_ptr(%arg0 : !fir.ref>>, 
!fir.box>) map_clauses(always, delete) capture(ByRef) members(%1 
: [0] : !fir.llvm_ptr>) -> !fir.ref>> 
{name = ""}
-  // CHECK: omp.target_exit_data map_entries(%[[DESC_MAP]] : !llvm.ptr) 
+  // CHECK: omp.target_exit_data map_entries(%[[DESC_MAP]] : !llvm.ptr)
   omp.target_exit_data   map_entries(%2 : !fir.ref>>)
-  return 
+  return
 }
 
 // -
@@ -956,8 +956,8 @@ func.func 
@omp_map_info_derived_type_explicit_member_conversion(%arg0 : !fir.ref
   %3 = fir.field_index real, 
!fir.type<_QFderived_type{real:f32,array:!fir.array<10xi32>,int:i32}>
   %4 = fir.coordinate_of %arg0, %3 : 
(!fir.ref,int:i32}>>,
 !fir.field) -> !fir.ref
   // CHECK: %[[MAP_MEMBER_2:.*]] = omp.map.info var_ptr(%[[GEP_2]] : 
!llvm.ptr, f32) map_clauses(tofrom) capture(ByRef) -> !llvm.ptr {name = 
"dtype%real"}
-  %5 = omp.map.info var_ptr(%4 : !fir.ref, f32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "dtype%real"}
-  // CHECK: %[[MAP_PARENT:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<"_QFderived_type", (f32, array<10 x i32>, i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[MAP_MEMBER_1]], %[[MAP_MEMBER_2]] 
: [2], [0] : !llvm.ptr, !llvm.ptr) -> !llvm.ptr {name = "dtype", partial_map = 
true} 
+  %5 = omp.map.info var_ptr(%4 : !fir.ref, f32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "dtype%real"}
+  // CHECK: %[[MAP_PARENT:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<"_QFderived_type", (f32, array<10 x i32>, i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[MAP_MEMBER_1]], %[[MAP_MEMBER_2]] 
: [2], [0] : !llvm.ptr, !llvm.ptr) -> !llvm.ptr {name = "dtype", partial_map = 
true}
   %6 = omp.map.info var_ptr(%arg0 : 
!fir.ref,int:i32}>>,
 !fir.type<_QFderived_type{real:f32,array:!fir.array<10xi32>,int:i32}>) 
map_clauses(tofrom) capture(ByRef) members(%2, %5 : [2], [0] : !fir.ref, 
!fir.ref) -> 
!fir.ref,int:i32}>> 
{name = "dtype", partial_map = true}
   // CHECK: omp.target map_entries(%[[MAP_MEMBER_1]] -> %[[ARG_1:.*]], 
%[[MAP_MEMBER_2]] -> %[[ARG_2:.*]], %[[MAP_PARENT]] -> %[[ARG_3:.*]] : 
!llvm.ptr, !llvm.ptr, !llvm.ptr) {
   omp.target map_entries(%2 -> %arg1, %5 -> %arg2, %6 -> %arg3 : 
!fir.ref, !fir.ref, 
!fir.ref,int:i32}>>)
 {
@@ -1275,3 +1275,22 @@ func.func @map_nested_dtype_alloca_mem2(%arg0 : 
!fir.ref {
+omp.declare_mapper @my_mapper : !fir.type<_QFdeclare_mapperTmy_type{data:i32}> 
{
+// CHECK: ^bb0(%[[VAL_0:.*]]: !llvm.ptr):
+^bb0(%0: !fir.ref>):
+// CHECK:   %[[VAL_1:.*]] = llvm.mlir.constant(0 : i32) : i32
+  %1 = fir.field_index data, !fir.type<_QFdeclare_mapperTmy_type{data:i32}>
+// CHECK:   %[[VAL_2:.*]] = llvm.getelementptr %[[VAL_0]][0, 0] : 
(!llvm.ptr) -> !llvm.ptr, !llvm.struct<"_QFdeclare_mapperTmy_type", (i32)>
+  %2 = fir.coordinate_of %0, %1 : 
(!fir.ref>, !fir.field) -> 
!fir.ref
+// CHECK:   %[[VAL_3:.*]] = omp.map.info var_ptr(%[[VAL_2]] : 
!llvm.ptr, i32) map_clauses(tofrom) capture(ByRef) -> !llvm.ptr {name = 
"var%[[VAL_4:.*]]"}
+  %3 = omp.map.info var_ptr(%2 : !fir.ref, i32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "var%data"}
+// CHECK:   %[[VAL_5:.*]] = omp.map.info var_ptr(%[[VAL_0]] : 
!llvm.ptr, !llvm.struct<"_QFdeclare_mapperTmy_type", (i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[VAL_3]] : [0] : !llvm.ptr) -> 
!llvm.ptr {name = "var", partial_map = true}
+  %4 = omp.map.info var_ptr(%0 : 
!fir.ref>, 
!fir.type<_QFdeclare_mapperTmy_type{data:i32}>) map_clauses(tofrom) 
capture(ByRef) members(%3 : [0] : !fir.ref) -> 
!fir.ref> {name = "var", 
partial_map = true}
+// CHECK:   omp.declare_mapper_info map_entries(%[[VAL_5]], %[[VAL_3]] 
: !llvm.ptr, !llvm.ptr)
+  omp.declare_m

[llvm-branch-commits] [clang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-02-07 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/124746

>From d80da54e1edee017f97aebf5f2e17895ddbf6413 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Tue, 28 Jan 2025 13:38:13 +
Subject: [PATCH 1/4] [MLIR][OpenMP] Add LLVM translation support for OpenMP
 UserDefinedMappers

This patch adds OpenMPToLLVMIRTranslation support for the OpenMP Declare Mapper 
directive.

Since both MLIR and Clang now support custom mappers, I've made the relative 
params required instead of optional as well.

Depends on #121005
---
 clang/lib/CodeGen/CGOpenMPRuntime.cpp |  11 +-
 .../llvm/Frontend/OpenMP/OMPIRBuilder.h   |  31 +--
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp |  70 +++---
 .../Frontend/OpenMPIRBuilderTest.cpp  |  46 ++--
 .../OpenMP/OpenMPToLLVMIRTranslation.cpp  | 215 +++---
 mlir/test/Target/LLVMIR/omptarget-llvm.mlir   | 117 ++
 .../fortran/target-custom-mapper.f90  |  46 
 7 files changed, 437 insertions(+), 99 deletions(-)
 create mode 100644 offload/test/offloading/fortran/target-custom-mapper.f90

diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index cafaaa364cb7630..b919c1f6ac62760 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -8889,8 +8889,8 @@ static void emitOffloadingArraysAndArgs(
 return MFunc;
   };
   OMPBuilder.emitOffloadingArraysAndArgs(
-  AllocaIP, CodeGenIP, Info, Info.RTArgs, CombinedInfo, IsNonContiguous,
-  ForEndCall, DeviceAddrCB, CustomMapperCB);
+  AllocaIP, CodeGenIP, Info, Info.RTArgs, CombinedInfo, CustomMapperCB,
+  IsNonContiguous, ForEndCall, DeviceAddrCB);
 }
 
 /// Check for inner distribute directive.
@@ -9099,9 +9099,10 @@ void CGOpenMPRuntime::emitUserDefinedMapper(const 
OMPDeclareMapperDecl *D,
   CGM.getCXXABI().getMangleContext().mangleCanonicalTypeName(Ty, Out);
   std::string Name = getName({"omp_mapper", TyStr, D->getName()});
 
-  auto *NewFn = OMPBuilder.emitUserDefinedMapper(PrivatizeAndGenMapInfoCB,
- ElemTy, Name, CustomMapperCB);
-  UDMMap.try_emplace(D, NewFn);
+  llvm::Expected NewFn = OMPBuilder.emitUserDefinedMapper(
+  PrivatizeAndGenMapInfoCB, ElemTy, Name, CustomMapperCB);
+  assert(NewFn && "Unexpected error in emitUserDefinedMapper");
+  UDMMap.try_emplace(D, *NewFn);
   if (CGF)
 FunctionUDMMap[CGF->CurFn].push_back(D);
 }
diff --git a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h 
b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
index d25077cae63e42b..151bd36aadaf0a4 100644
--- a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
+++ b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
@@ -2399,6 +2399,7 @@ class OpenMPIRBuilder {
CurInfo.NonContigInfo.Strides.end());
 }
   };
+  using MapInfosOrErrorTy = Expected;
 
   /// Callback function type for functions emitting the host fallback code that
   /// is executed when the kernel launch fails. It takes an insertion point as
@@ -2475,9 +2476,9 @@ class OpenMPIRBuilder {
   /// including base pointers, pointers, sizes, map types, user-defined 
mappers.
   void emitOffloadingArrays(
   InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy 
&CombinedInfo,
-  TargetDataInfo &Info, bool IsNonContiguous = false,
-  function_ref DeviceAddrCB = nullptr,
-  function_ref CustomMapperCB = nullptr);
+  TargetDataInfo &Info, function_ref CustomMapperCB,
+  bool IsNonContiguous = false,
+  function_ref DeviceAddrCB = nullptr);
 
   /// Allocates memory for and populates the arrays required for offloading
   /// (offload_{baseptrs|ptrs|mappers|sizes|maptypes|mapnames}). Then, it
@@ -2488,9 +2489,9 @@ class OpenMPIRBuilder {
   void emitOffloadingArraysAndArgs(
   InsertPointTy AllocaIP, InsertPointTy CodeGenIP, TargetDataInfo &Info,
   TargetDataRTArgs &RTArgs, MapInfosTy &CombinedInfo,
+  function_ref CustomMapperCB,
   bool IsNonContiguous = false, bool ForEndCall = false,
-  function_ref DeviceAddrCB = nullptr,
-  function_ref CustomMapperCB = nullptr);
+  function_ref DeviceAddrCB = nullptr);
 
   /// Creates offloading entry for the provided entry ID \a ID, address \a
   /// Addr, size \a Size, and flags \a Flags.
@@ -2950,12 +2951,12 @@ class OpenMPIRBuilder {
   /// \param FuncName Optional param to specify mapper function name.
   /// \param CustomMapperCB Optional callback to generate code related to
   /// custom mappers.
-  Function *emitUserDefinedMapper(
-  function_ref
+  Expected emitUserDefinedMapper(
+  function_ref
   PrivAndGenMapInfoCB,
   llvm::Type *ElemTy, StringRef FuncName,
-  function_ref CustomMapperCB = nullptr);
+  function_ref CustomMapperCB);
 
   /// Generator for '#omp target data'
   ///
@@ -2969,21 +2970,21 @@ class OpenMPIRBuilder {
   /// \param IfCond Value which corresponds to the i

[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2025-02-10 Thread Akash Banerjee via llvm-branch-commits


@@ -2612,7 +2612,52 @@ static void
 genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
const parser::OpenMPDeclareMapperConstruct &declareMapperConstruct) {
-  TODO(converter.getCurrentLocation(), "OpenMPDeclareMapperConstruct");
+  mlir::Location loc = converter.genLocation(declareMapperConstruct.source);
+  fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  lower::StatementContext stmtCtx;
+  const auto &spec =
+  std::get(declareMapperConstruct.t);
+  const auto &mapperName{std::get>(spec.t)};
+  const auto &varType{std::get(spec.t)};
+  const auto &varName{std::get(spec.t)};
+  assert(varType.declTypeSpec->category() ==
+ semantics::DeclTypeSpec::Category::TypeDerived &&
+ "Expected derived type");
+
+  std::string mapperNameStr;
+  if (mapperName.has_value()) {
+mapperNameStr = mapperName->ToString();
+mapperNameStr =
+converter.mangleName(mapperNameStr, mapperName->symbol->owner());
+  } else {
+mapperNameStr =
+varType.declTypeSpec->derivedTypeSpec().name().ToString() + ".default";
+mapperNameStr = converter.mangleName(
+mapperNameStr, *varType.declTypeSpec->derivedTypeSpec().GetScope());
+  }
+
+  // Save current insertion point before moving to the module scope to create
+  // the DeclareMapperOp
+  mlir::OpBuilder::InsertionGuard guard(firOpBuilder);
+
+  firOpBuilder.setInsertionPointToStart(converter.getModuleOp().getBody());

TIFitis wrote:

`offload/test/offloading/fortran/target-custom-mapper.f90` uses a mapper within 
a mapper. Let me know if that's the scenario you were referring to here.

https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP custom mappers in map clause (PR #121001)

2025-02-10 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/121001

>From c93eefb9cc4db635a694f16aee6b42525cd05e79 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 21:13:42 +
Subject: [PATCH 1/4] Add flang lowering changes for mapper field in map
 clause.

---
 flang/lib/Lower/OpenMP/ClauseProcessor.cpp  | 32 +
 flang/lib/Lower/OpenMP/ClauseProcessor.h|  3 +-
 flang/test/Lower/OpenMP/Todo/map-mapper.f90 | 16 ---
 flang/test/Lower/OpenMP/map-mapper.f90  | 23 +++
 4 files changed, 52 insertions(+), 22 deletions(-)
 delete mode 100644 flang/test/Lower/OpenMP/Todo/map-mapper.f90
 create mode 100644 flang/test/Lower/OpenMP/map-mapper.f90

diff --git a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp 
b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
index febc6adcf9d6ff4..467a0dcebf2b8a9 100644
--- a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
+++ b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
@@ -969,8 +969,10 @@ void ClauseProcessor::processMapObjects(
 llvm::omp::OpenMPOffloadMappingFlags mapTypeBits,
 std::map &parentMemberIndices,
 llvm::SmallVectorImpl &mapVars,
-llvm::SmallVectorImpl &mapSyms) const {
+llvm::SmallVectorImpl &mapSyms,
+std::string mapperIdName) const {
   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  mlir::FlatSymbolRefAttr mapperId;
 
   for (const omp::Object &object : objects) {
 llvm::SmallVector bounds;
@@ -1003,6 +1005,20 @@ void ClauseProcessor::processMapObjects(
   }
 }
 
+if (!mapperIdName.empty()) {
+  if (mapperIdName == "default") {
+auto &typeSpec = object.sym()->owner().IsDerivedType()
+ ? *object.sym()->owner().derivedTypeSpec()
+ : object.sym()->GetType()->derivedTypeSpec();
+mapperIdName = typeSpec.name().ToString() + ".default";
+mapperIdName = converter.mangleName(mapperIdName, 
*typeSpec.GetScope());
+  }
+  assert(converter.getMLIRSymbolTable()->lookup(mapperIdName) &&
+ "mapper not found");
+  mapperId = mlir::FlatSymbolRefAttr::get(&converter.getMLIRContext(),
+  mapperIdName);
+  mapperIdName.clear();
+}
 // Explicit map captures are captured ByRef by default,
 // optimisation passes may alter this to ByCopy or other capture
 // types to optimise
@@ -1016,7 +1032,8 @@ void ClauseProcessor::processMapObjects(
 static_cast<
 std::underlying_type_t>(
 mapTypeBits),
-mlir::omp::VariableCaptureKind::ByRef, baseOp.getType());
+mlir::omp::VariableCaptureKind::ByRef, baseOp.getType(), false,
+mapperId);
 
 if (parentObj.has_value()) {
   parentMemberIndices[parentObj.value()].addChildIndexAndMapToParent(
@@ -1047,6 +1064,7 @@ bool ClauseProcessor::processMap(
 const auto &[mapType, typeMods, mappers, iterator, objects] = clause.t;
 llvm::omp::OpenMPOffloadMappingFlags mapTypeBits =
 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE;
+std::string mapperIdName;
 // If the map type is specified, then process it else Tofrom is the
 // default.
 Map::MapType type = mapType.value_or(Map::MapType::Tofrom);
@@ -1090,13 +1108,17 @@ bool ClauseProcessor::processMap(
"Support for iterator modifiers is not implemented yet");
 }
 if (mappers) {
-  TODO(currentLocation,
-   "Support for mapper modifiers is not implemented yet");
+  assert(mappers->size() == 1 && "more than one mapper");
+  mapperIdName = mappers->front().v.id().symbol->name().ToString();
+  if (mapperIdName != "default")
+mapperIdName = converter.mangleName(
+mapperIdName, mappers->front().v.id().symbol->owner());
 }
 
 processMapObjects(stmtCtx, clauseLocation,
   std::get(clause.t), mapTypeBits,
-  parentMemberIndices, result.mapVars, *ptrMapSyms);
+  parentMemberIndices, result.mapVars, *ptrMapSyms,
+  mapperIdName);
   };
 
   bool clauseFound = findRepeatableClause(process);
diff --git a/flang/lib/Lower/OpenMP/ClauseProcessor.h 
b/flang/lib/Lower/OpenMP/ClauseProcessor.h
index e05f66c7666844f..2b319e890a5adbe 100644
--- a/flang/lib/Lower/OpenMP/ClauseProcessor.h
+++ b/flang/lib/Lower/OpenMP/ClauseProcessor.h
@@ -175,7 +175,8 @@ class ClauseProcessor {
   llvm::omp::OpenMPOffloadMappingFlags mapTypeBits,
   std::map &parentMemberIndices,
   llvm::SmallVectorImpl &mapVars,
-  llvm::SmallVectorImpl &mapSyms) const;
+  llvm::SmallVectorImpl &mapSyms,
+  std::string mapperIdName = "") const;
 
   lower::AbstractConverter &converter;
   semantics::SemanticsContext &semaCtx;
diff --git a/flang/test/Lower/OpenMP/Todo/map-mapper.f90 
b/flang/test/Lower/OpenMP/Todo/map-mapper.f90
deleted file mode 100644
index 9554ffd5fda7bdd..000
--- a/fla

[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add OMP Mapper field to MapInfoOp (PR #120994)

2025-02-10 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/120994

>From f8642ec5b59e8617d2f1b8a87938ce2d6ba25205 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 20:53:47 +
Subject: [PATCH 1/2] Add mapper field to mapInfoOp.

---
 flang/lib/Lower/OpenMP/Utils.cpp| 3 ++-
 flang/lib/Lower/OpenMP/Utils.h  | 3 ++-
 flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp  | 5 -
 flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp | 1 +
 mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td   | 2 ++
 mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp| 2 +-
 mlir/test/Dialect/OpenMP/ops.mlir   | 4 ++--
 7 files changed, 14 insertions(+), 6 deletions(-)

diff --git a/flang/lib/Lower/OpenMP/Utils.cpp b/flang/lib/Lower/OpenMP/Utils.cpp
index 35722fa7d1b1206..fa1975dac789b12 100644
--- a/flang/lib/Lower/OpenMP/Utils.cpp
+++ b/flang/lib/Lower/OpenMP/Utils.cpp
@@ -125,7 +125,7 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
 llvm::ArrayRef members,
 mlir::ArrayAttr membersIndex, uint64_t mapType,
 mlir::omp::VariableCaptureKind mapCaptureType, mlir::Type 
retTy,
-bool partialMap) {
+bool partialMap, mlir::FlatSymbolRefAttr mapperId) {
   if (auto boxTy = llvm::dyn_cast(baseAddr.getType())) {
 baseAddr = builder.create(loc, baseAddr);
 retTy = baseAddr.getType();
@@ -144,6 +144,7 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
   mlir::omp::MapInfoOp op = builder.create(
   loc, retTy, baseAddr, varType, varPtrPtr, members, membersIndex, bounds,
   builder.getIntegerAttr(builder.getIntegerType(64, false), mapType),
+  mapperId,
   builder.getAttr(mapCaptureType),
   builder.getStringAttr(name), builder.getBoolAttr(partialMap));
   return op;
diff --git a/flang/lib/Lower/OpenMP/Utils.h b/flang/lib/Lower/OpenMP/Utils.h
index f2e378443e5f295..3943eb633b04e36 100644
--- a/flang/lib/Lower/OpenMP/Utils.h
+++ b/flang/lib/Lower/OpenMP/Utils.h
@@ -116,7 +116,8 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
 llvm::ArrayRef members,
 mlir::ArrayAttr membersIndex, uint64_t mapType,
 mlir::omp::VariableCaptureKind mapCaptureType, mlir::Type 
retTy,
-bool partialMap = false);
+bool partialMap = false,
+mlir::FlatSymbolRefAttr mapperId = mlir::FlatSymbolRefAttr());
 
 void insertChildMapInfoIntoParent(
 Fortran::lower::AbstractConverter &converter,
diff --git a/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp 
b/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
index e7c1d1d9d560f87..beea7543e54b324 100644
--- a/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
+++ b/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
@@ -184,6 +184,7 @@ class MapInfoFinalizationPass
 /*members=*/mlir::SmallVector{},
 /*membersIndex=*/mlir::ArrayAttr{}, bounds,
 builder.getIntegerAttr(builder.getIntegerType(64, false), mapType),
+/*mapperId*/ mlir::FlatSymbolRefAttr(),
 builder.getAttr(
 mlir::omp::VariableCaptureKind::ByRef),
 /*name=*/builder.getStringAttr(""),
@@ -329,7 +330,8 @@ class MapInfoFinalizationPass
 builder.getIntegerAttr(
 builder.getIntegerType(64, false),
 getDescriptorMapType(op.getMapType().value_or(0), target)),
-op.getMapCaptureTypeAttr(), op.getNameAttr(),
+/*mapperId*/ mlir::FlatSymbolRefAttr(), op.getMapCaptureTypeAttr(),
+op.getNameAttr(),
 /*partial_map=*/builder.getBoolAttr(false));
 op.replaceAllUsesWith(newDescParentMapOp.getResult());
 op->erase();
@@ -623,6 +625,7 @@ class MapInfoFinalizationPass
   /*members=*/mlir::ValueRange{},
   /*members_index=*/mlir::ArrayAttr{},
   /*bounds=*/bounds, op.getMapTypeAttr(),
+  /*mapperId*/ mlir::FlatSymbolRefAttr(),
   builder.getAttr(
   mlir::omp::VariableCaptureKind::ByRef),
   builder.getStringAttr(op.getNameAttr().strref() + "." +
diff --git a/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp 
b/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
index 963ae863c1fc5cb..97ea463a3c495df 100644
--- a/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
+++ b/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
@@ -91,6 +91,7 @@ class MapsForPrivatizedSymbolsPass
 /*bounds=*/ValueRange{},
 builder.getIntegerAttr(builder.getIntegerType(64, /*isSigned=*/false),
mapTypeTo),
+/*mapperId*/ mlir::FlatSymbolRefAttr(),
 builder.getAttr(
 omp::VariableCaptureKind::ByRef),
 StringAttr(), builder.getBoolAttr(false));
diff --git a/ml

[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add conversion support from FIR to LLVM Dialect for OMP DeclareMapper (PR #121005)

2025-02-10 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/121005

>From 879d8a1765b9176fce18c02bdcc29bb079b6ba7e Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 21:50:03 +
Subject: [PATCH 1/2] Add OpenMP to LLVM dialect conversion support for
 DeclareMapperOp.

---
 .../Fir/convert-to-llvm-openmp-and-fir.fir| 27 +--
 .../Conversion/OpenMPToLLVM/OpenMPToLLVM.cpp  | 48 +++
 .../OpenMPToLLVM/convert-to-llvmir.mlir   | 13 +
 3 files changed, 74 insertions(+), 14 deletions(-)

diff --git a/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir 
b/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
index 8e4e1fe824d9f5b..82f2aea3ad983c9 100644
--- a/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
+++ b/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
@@ -936,9 +936,9 @@ func.func @omp_map_info_descriptor_type_conversion(%arg0 : 
!fir.ref>, i32) 
map_clauses(tofrom) capture(ByRef) -> !fir.llvm_ptr> {name = ""}
   // CHECK: %[[DESC_MAP:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<(ptr, i64, i32, i8, i8, i8, i8)>) map_clauses(always, delete) 
capture(ByRef) members(%[[MEMBER_MAP]] : [0] : !llvm.ptr) -> !llvm.ptr {name = 
""}
   %2 = omp.map.info var_ptr(%arg0 : !fir.ref>>, 
!fir.box>) map_clauses(always, delete) capture(ByRef) members(%1 
: [0] : !fir.llvm_ptr>) -> !fir.ref>> 
{name = ""}
-  // CHECK: omp.target_exit_data map_entries(%[[DESC_MAP]] : !llvm.ptr) 
+  // CHECK: omp.target_exit_data map_entries(%[[DESC_MAP]] : !llvm.ptr)
   omp.target_exit_data   map_entries(%2 : !fir.ref>>)
-  return 
+  return
 }
 
 // -
@@ -956,8 +956,8 @@ func.func 
@omp_map_info_derived_type_explicit_member_conversion(%arg0 : !fir.ref
   %3 = fir.field_index real, 
!fir.type<_QFderived_type{real:f32,array:!fir.array<10xi32>,int:i32}>
   %4 = fir.coordinate_of %arg0, %3 : 
(!fir.ref,int:i32}>>,
 !fir.field) -> !fir.ref
   // CHECK: %[[MAP_MEMBER_2:.*]] = omp.map.info var_ptr(%[[GEP_2]] : 
!llvm.ptr, f32) map_clauses(tofrom) capture(ByRef) -> !llvm.ptr {name = 
"dtype%real"}
-  %5 = omp.map.info var_ptr(%4 : !fir.ref, f32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "dtype%real"}
-  // CHECK: %[[MAP_PARENT:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<"_QFderived_type", (f32, array<10 x i32>, i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[MAP_MEMBER_1]], %[[MAP_MEMBER_2]] 
: [2], [0] : !llvm.ptr, !llvm.ptr) -> !llvm.ptr {name = "dtype", partial_map = 
true} 
+  %5 = omp.map.info var_ptr(%4 : !fir.ref, f32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "dtype%real"}
+  // CHECK: %[[MAP_PARENT:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<"_QFderived_type", (f32, array<10 x i32>, i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[MAP_MEMBER_1]], %[[MAP_MEMBER_2]] 
: [2], [0] : !llvm.ptr, !llvm.ptr) -> !llvm.ptr {name = "dtype", partial_map = 
true}
   %6 = omp.map.info var_ptr(%arg0 : 
!fir.ref,int:i32}>>,
 !fir.type<_QFderived_type{real:f32,array:!fir.array<10xi32>,int:i32}>) 
map_clauses(tofrom) capture(ByRef) members(%2, %5 : [2], [0] : !fir.ref, 
!fir.ref) -> 
!fir.ref,int:i32}>> 
{name = "dtype", partial_map = true}
   // CHECK: omp.target map_entries(%[[MAP_MEMBER_1]] -> %[[ARG_1:.*]], 
%[[MAP_MEMBER_2]] -> %[[ARG_2:.*]], %[[MAP_PARENT]] -> %[[ARG_3:.*]] : 
!llvm.ptr, !llvm.ptr, !llvm.ptr) {
   omp.target map_entries(%2 -> %arg1, %5 -> %arg2, %6 -> %arg3 : 
!fir.ref, !fir.ref, 
!fir.ref,int:i32}>>)
 {
@@ -1275,3 +1275,22 @@ func.func @map_nested_dtype_alloca_mem2(%arg0 : 
!fir.ref {
+omp.declare_mapper @my_mapper : !fir.type<_QFdeclare_mapperTmy_type{data:i32}> 
{
+// CHECK: ^bb0(%[[VAL_0:.*]]: !llvm.ptr):
+^bb0(%0: !fir.ref>):
+// CHECK:   %[[VAL_1:.*]] = llvm.mlir.constant(0 : i32) : i32
+  %1 = fir.field_index data, !fir.type<_QFdeclare_mapperTmy_type{data:i32}>
+// CHECK:   %[[VAL_2:.*]] = llvm.getelementptr %[[VAL_0]][0, 0] : 
(!llvm.ptr) -> !llvm.ptr, !llvm.struct<"_QFdeclare_mapperTmy_type", (i32)>
+  %2 = fir.coordinate_of %0, %1 : 
(!fir.ref>, !fir.field) -> 
!fir.ref
+// CHECK:   %[[VAL_3:.*]] = omp.map.info var_ptr(%[[VAL_2]] : 
!llvm.ptr, i32) map_clauses(tofrom) capture(ByRef) -> !llvm.ptr {name = 
"var%[[VAL_4:.*]]"}
+  %3 = omp.map.info var_ptr(%2 : !fir.ref, i32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "var%data"}
+// CHECK:   %[[VAL_5:.*]] = omp.map.info var_ptr(%[[VAL_0]] : 
!llvm.ptr, !llvm.struct<"_QFdeclare_mapperTmy_type", (i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[VAL_3]] : [0] : !llvm.ptr) -> 
!llvm.ptr {name = "var", partial_map = true}
+  %4 = omp.map.info var_ptr(%0 : 
!fir.ref>, 
!fir.type<_QFdeclare_mapperTmy_type{data:i32}>) map_clauses(tofrom) 
capture(ByRef) members(%3 : [0] : !fir.ref) -> 
!fir.ref> {name = "var", 
partial_map = true}
+// CHECK:   omp.declare_mapper_info map_entries(%[[VAL_5]], %[[VAL_3]] 
: !llvm.ptr, !llvm.ptr)
+  omp.declare_m

[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2025-02-07 Thread Akash Banerjee via llvm-branch-commits


@@ -2612,7 +2612,52 @@ static void
 genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
const parser::OpenMPDeclareMapperConstruct &declareMapperConstruct) {
-  TODO(converter.getCurrentLocation(), "OpenMPDeclareMapperConstruct");
+  mlir::Location loc = converter.genLocation(declareMapperConstruct.source);
+  fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  lower::StatementContext stmtCtx;
+  const auto &spec =
+  std::get(declareMapperConstruct.t);
+  const auto &mapperName{std::get>(spec.t)};
+  const auto &varType{std::get(spec.t)};
+  const auto &varName{std::get(spec.t)};
+  assert(varType.declTypeSpec->category() ==
+ semantics::DeclTypeSpec::Category::TypeDerived &&
+ "Expected derived type");
+
+  std::string mapperNameStr;
+  if (mapperName.has_value()) {
+mapperNameStr = mapperName->ToString();
+mapperNameStr =
+converter.mangleName(mapperNameStr, mapperName->symbol->owner());
+  } else {
+mapperNameStr =
+varType.declTypeSpec->derivedTypeSpec().name().ToString() + ".default";
+mapperNameStr = converter.mangleName(
+mapperNameStr, *varType.declTypeSpec->derivedTypeSpec().GetScope());
+  }
+
+  // Save current insertion point before moving to the module scope to create
+  // the DeclareMapperOp
+  mlir::OpBuilder::InsertionGuard guard(firOpBuilder);
+
+  firOpBuilder.setInsertionPointToStart(converter.getModuleOp().getBody());

TIFitis wrote:

I have a test for this scenario in #124746.

https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2025-02-07 Thread Akash Banerjee via llvm-branch-commits


@@ -2612,7 +2612,52 @@ static void
 genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
const parser::OpenMPDeclareMapperConstruct &declareMapperConstruct) {
-  TODO(converter.getCurrentLocation(), "OpenMPDeclareMapperConstruct");
+  mlir::Location loc = converter.genLocation(declareMapperConstruct.source);
+  fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  lower::StatementContext stmtCtx;
+  const auto &spec =
+  std::get(declareMapperConstruct.t);
+  const auto &mapperName{std::get>(spec.t)};
+  const auto &varType{std::get(spec.t)};
+  const auto &varName{std::get(spec.t)};
+  assert(varType.declTypeSpec->category() ==
+ semantics::DeclTypeSpec::Category::TypeDerived &&
+ "Expected derived type");

TIFitis wrote:

I believe we have a semantics check in place for this.

https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add OMP Mapper field to MapInfoOp (PR #120994)

2025-02-07 Thread Akash Banerjee via llvm-branch-commits

TIFitis wrote:

> One small comment, though. Please trigger a not-yet-implemented error when 
> translating all operations taking `map` clauses if the new field is set. That 
> would be in `checkImplementationStatus`, in OpenMPToLLVMIRTranslation.cpp.

Is that necessary given I have the entire implementation in place? I am 
planning on merging the entire series in one go.

https://github.com/llvm/llvm-project/pull/120994
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP custom mappers in map clause (PR #121001)

2025-02-07 Thread Akash Banerjee via llvm-branch-commits


@@ -936,8 +936,10 @@ void ClauseProcessor::processMapObjects(
 llvm::omp::OpenMPOffloadMappingFlags mapTypeBits,
 std::map &parentMemberIndices,
 llvm::SmallVectorImpl &mapVars,
-llvm::SmallVectorImpl &mapSyms) const {
+llvm::SmallVectorImpl &mapSyms,
+std::string mapperIdName) const {

TIFitis wrote:

In this case, even we accept a `StringRef`, we would have to immediately copy 
it to a `std:string` as we need to pass an `lvalue` to `converter.mangleName`. 
As such, wouldn't it be better to accept it as a string.

https://github.com/llvm/llvm-project/pull/121001
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP custom mappers in map clause (PR #121001)

2025-02-10 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/121001

>From d7bb2309591d828756b7e1274ebcf592b992eb16 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 21:13:42 +
Subject: [PATCH 1/4] Add flang lowering changes for mapper field in map
 clause.

---
 flang/lib/Lower/OpenMP/ClauseProcessor.cpp  | 32 +
 flang/lib/Lower/OpenMP/ClauseProcessor.h|  3 +-
 flang/test/Lower/OpenMP/Todo/map-mapper.f90 | 16 ---
 flang/test/Lower/OpenMP/map-mapper.f90  | 23 +++
 4 files changed, 52 insertions(+), 22 deletions(-)
 delete mode 100644 flang/test/Lower/OpenMP/Todo/map-mapper.f90
 create mode 100644 flang/test/Lower/OpenMP/map-mapper.f90

diff --git a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp 
b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
index febc6adcf9d6ff4..467a0dcebf2b8a9 100644
--- a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
+++ b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
@@ -969,8 +969,10 @@ void ClauseProcessor::processMapObjects(
 llvm::omp::OpenMPOffloadMappingFlags mapTypeBits,
 std::map &parentMemberIndices,
 llvm::SmallVectorImpl &mapVars,
-llvm::SmallVectorImpl &mapSyms) const {
+llvm::SmallVectorImpl &mapSyms,
+std::string mapperIdName) const {
   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  mlir::FlatSymbolRefAttr mapperId;
 
   for (const omp::Object &object : objects) {
 llvm::SmallVector bounds;
@@ -1003,6 +1005,20 @@ void ClauseProcessor::processMapObjects(
   }
 }
 
+if (!mapperIdName.empty()) {
+  if (mapperIdName == "default") {
+auto &typeSpec = object.sym()->owner().IsDerivedType()
+ ? *object.sym()->owner().derivedTypeSpec()
+ : object.sym()->GetType()->derivedTypeSpec();
+mapperIdName = typeSpec.name().ToString() + ".default";
+mapperIdName = converter.mangleName(mapperIdName, 
*typeSpec.GetScope());
+  }
+  assert(converter.getMLIRSymbolTable()->lookup(mapperIdName) &&
+ "mapper not found");
+  mapperId = mlir::FlatSymbolRefAttr::get(&converter.getMLIRContext(),
+  mapperIdName);
+  mapperIdName.clear();
+}
 // Explicit map captures are captured ByRef by default,
 // optimisation passes may alter this to ByCopy or other capture
 // types to optimise
@@ -1016,7 +1032,8 @@ void ClauseProcessor::processMapObjects(
 static_cast<
 std::underlying_type_t>(
 mapTypeBits),
-mlir::omp::VariableCaptureKind::ByRef, baseOp.getType());
+mlir::omp::VariableCaptureKind::ByRef, baseOp.getType(), false,
+mapperId);
 
 if (parentObj.has_value()) {
   parentMemberIndices[parentObj.value()].addChildIndexAndMapToParent(
@@ -1047,6 +1064,7 @@ bool ClauseProcessor::processMap(
 const auto &[mapType, typeMods, mappers, iterator, objects] = clause.t;
 llvm::omp::OpenMPOffloadMappingFlags mapTypeBits =
 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE;
+std::string mapperIdName;
 // If the map type is specified, then process it else Tofrom is the
 // default.
 Map::MapType type = mapType.value_or(Map::MapType::Tofrom);
@@ -1090,13 +1108,17 @@ bool ClauseProcessor::processMap(
"Support for iterator modifiers is not implemented yet");
 }
 if (mappers) {
-  TODO(currentLocation,
-   "Support for mapper modifiers is not implemented yet");
+  assert(mappers->size() == 1 && "more than one mapper");
+  mapperIdName = mappers->front().v.id().symbol->name().ToString();
+  if (mapperIdName != "default")
+mapperIdName = converter.mangleName(
+mapperIdName, mappers->front().v.id().symbol->owner());
 }
 
 processMapObjects(stmtCtx, clauseLocation,
   std::get(clause.t), mapTypeBits,
-  parentMemberIndices, result.mapVars, *ptrMapSyms);
+  parentMemberIndices, result.mapVars, *ptrMapSyms,
+  mapperIdName);
   };
 
   bool clauseFound = findRepeatableClause(process);
diff --git a/flang/lib/Lower/OpenMP/ClauseProcessor.h 
b/flang/lib/Lower/OpenMP/ClauseProcessor.h
index e05f66c7666844f..2b319e890a5adbe 100644
--- a/flang/lib/Lower/OpenMP/ClauseProcessor.h
+++ b/flang/lib/Lower/OpenMP/ClauseProcessor.h
@@ -175,7 +175,8 @@ class ClauseProcessor {
   llvm::omp::OpenMPOffloadMappingFlags mapTypeBits,
   std::map &parentMemberIndices,
   llvm::SmallVectorImpl &mapVars,
-  llvm::SmallVectorImpl &mapSyms) const;
+  llvm::SmallVectorImpl &mapSyms,
+  std::string mapperIdName = "") const;
 
   lower::AbstractConverter &converter;
   semantics::SemanticsContext &semaCtx;
diff --git a/flang/test/Lower/OpenMP/Todo/map-mapper.f90 
b/flang/test/Lower/OpenMP/Todo/map-mapper.f90
deleted file mode 100644
index 9554ffd5fda7bdd..000
--- a/fla

[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add OMP Mapper field to MapInfoOp (PR #120994)

2025-02-10 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/120994

>From 95e8e2b18d9e5b35ec2ad13bd7ee58a1bd1b996d Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 20:53:47 +
Subject: [PATCH 1/2] Add mapper field to mapInfoOp.

---
 flang/lib/Lower/OpenMP/Utils.cpp| 3 ++-
 flang/lib/Lower/OpenMP/Utils.h  | 3 ++-
 flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp  | 5 -
 flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp | 1 +
 mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td   | 2 ++
 mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp| 2 +-
 mlir/test/Dialect/OpenMP/ops.mlir   | 4 ++--
 7 files changed, 14 insertions(+), 6 deletions(-)

diff --git a/flang/lib/Lower/OpenMP/Utils.cpp b/flang/lib/Lower/OpenMP/Utils.cpp
index 35722fa7d1b1206..fa1975dac789b12 100644
--- a/flang/lib/Lower/OpenMP/Utils.cpp
+++ b/flang/lib/Lower/OpenMP/Utils.cpp
@@ -125,7 +125,7 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
 llvm::ArrayRef members,
 mlir::ArrayAttr membersIndex, uint64_t mapType,
 mlir::omp::VariableCaptureKind mapCaptureType, mlir::Type 
retTy,
-bool partialMap) {
+bool partialMap, mlir::FlatSymbolRefAttr mapperId) {
   if (auto boxTy = llvm::dyn_cast(baseAddr.getType())) {
 baseAddr = builder.create(loc, baseAddr);
 retTy = baseAddr.getType();
@@ -144,6 +144,7 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
   mlir::omp::MapInfoOp op = builder.create(
   loc, retTy, baseAddr, varType, varPtrPtr, members, membersIndex, bounds,
   builder.getIntegerAttr(builder.getIntegerType(64, false), mapType),
+  mapperId,
   builder.getAttr(mapCaptureType),
   builder.getStringAttr(name), builder.getBoolAttr(partialMap));
   return op;
diff --git a/flang/lib/Lower/OpenMP/Utils.h b/flang/lib/Lower/OpenMP/Utils.h
index f2e378443e5f295..3943eb633b04e36 100644
--- a/flang/lib/Lower/OpenMP/Utils.h
+++ b/flang/lib/Lower/OpenMP/Utils.h
@@ -116,7 +116,8 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
 llvm::ArrayRef members,
 mlir::ArrayAttr membersIndex, uint64_t mapType,
 mlir::omp::VariableCaptureKind mapCaptureType, mlir::Type 
retTy,
-bool partialMap = false);
+bool partialMap = false,
+mlir::FlatSymbolRefAttr mapperId = mlir::FlatSymbolRefAttr());
 
 void insertChildMapInfoIntoParent(
 Fortran::lower::AbstractConverter &converter,
diff --git a/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp 
b/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
index e7c1d1d9d560f87..beea7543e54b324 100644
--- a/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
+++ b/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
@@ -184,6 +184,7 @@ class MapInfoFinalizationPass
 /*members=*/mlir::SmallVector{},
 /*membersIndex=*/mlir::ArrayAttr{}, bounds,
 builder.getIntegerAttr(builder.getIntegerType(64, false), mapType),
+/*mapperId*/ mlir::FlatSymbolRefAttr(),
 builder.getAttr(
 mlir::omp::VariableCaptureKind::ByRef),
 /*name=*/builder.getStringAttr(""),
@@ -329,7 +330,8 @@ class MapInfoFinalizationPass
 builder.getIntegerAttr(
 builder.getIntegerType(64, false),
 getDescriptorMapType(op.getMapType().value_or(0), target)),
-op.getMapCaptureTypeAttr(), op.getNameAttr(),
+/*mapperId*/ mlir::FlatSymbolRefAttr(), op.getMapCaptureTypeAttr(),
+op.getNameAttr(),
 /*partial_map=*/builder.getBoolAttr(false));
 op.replaceAllUsesWith(newDescParentMapOp.getResult());
 op->erase();
@@ -623,6 +625,7 @@ class MapInfoFinalizationPass
   /*members=*/mlir::ValueRange{},
   /*members_index=*/mlir::ArrayAttr{},
   /*bounds=*/bounds, op.getMapTypeAttr(),
+  /*mapperId*/ mlir::FlatSymbolRefAttr(),
   builder.getAttr(
   mlir::omp::VariableCaptureKind::ByRef),
   builder.getStringAttr(op.getNameAttr().strref() + "." +
diff --git a/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp 
b/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
index 963ae863c1fc5cb..97ea463a3c495df 100644
--- a/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
+++ b/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
@@ -91,6 +91,7 @@ class MapsForPrivatizedSymbolsPass
 /*bounds=*/ValueRange{},
 builder.getIntegerAttr(builder.getIntegerType(64, /*isSigned=*/false),
mapTypeTo),
+/*mapperId*/ mlir::FlatSymbolRefAttr(),
 builder.getAttr(
 omp::VariableCaptureKind::ByRef),
 StringAttr(), builder.getBoolAttr(false));
diff --git a/ml

[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add conversion support from FIR to LLVM Dialect for OMP DeclareMapper (PR #121005)

2025-02-10 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/121005

>From 14e666593f9966b24f11602104788c3501364574 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 21:50:03 +
Subject: [PATCH 1/2] Add OpenMP to LLVM dialect conversion support for
 DeclareMapperOp.

---
 .../Fir/convert-to-llvm-openmp-and-fir.fir| 27 +--
 .../Conversion/OpenMPToLLVM/OpenMPToLLVM.cpp  | 48 +++
 .../OpenMPToLLVM/convert-to-llvmir.mlir   | 13 +
 3 files changed, 74 insertions(+), 14 deletions(-)

diff --git a/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir 
b/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
index 8e4e1fe824d9f5b..82f2aea3ad983c9 100644
--- a/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
+++ b/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
@@ -936,9 +936,9 @@ func.func @omp_map_info_descriptor_type_conversion(%arg0 : 
!fir.ref>, i32) 
map_clauses(tofrom) capture(ByRef) -> !fir.llvm_ptr> {name = ""}
   // CHECK: %[[DESC_MAP:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<(ptr, i64, i32, i8, i8, i8, i8)>) map_clauses(always, delete) 
capture(ByRef) members(%[[MEMBER_MAP]] : [0] : !llvm.ptr) -> !llvm.ptr {name = 
""}
   %2 = omp.map.info var_ptr(%arg0 : !fir.ref>>, 
!fir.box>) map_clauses(always, delete) capture(ByRef) members(%1 
: [0] : !fir.llvm_ptr>) -> !fir.ref>> 
{name = ""}
-  // CHECK: omp.target_exit_data map_entries(%[[DESC_MAP]] : !llvm.ptr) 
+  // CHECK: omp.target_exit_data map_entries(%[[DESC_MAP]] : !llvm.ptr)
   omp.target_exit_data   map_entries(%2 : !fir.ref>>)
-  return 
+  return
 }
 
 // -
@@ -956,8 +956,8 @@ func.func 
@omp_map_info_derived_type_explicit_member_conversion(%arg0 : !fir.ref
   %3 = fir.field_index real, 
!fir.type<_QFderived_type{real:f32,array:!fir.array<10xi32>,int:i32}>
   %4 = fir.coordinate_of %arg0, %3 : 
(!fir.ref,int:i32}>>,
 !fir.field) -> !fir.ref
   // CHECK: %[[MAP_MEMBER_2:.*]] = omp.map.info var_ptr(%[[GEP_2]] : 
!llvm.ptr, f32) map_clauses(tofrom) capture(ByRef) -> !llvm.ptr {name = 
"dtype%real"}
-  %5 = omp.map.info var_ptr(%4 : !fir.ref, f32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "dtype%real"}
-  // CHECK: %[[MAP_PARENT:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<"_QFderived_type", (f32, array<10 x i32>, i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[MAP_MEMBER_1]], %[[MAP_MEMBER_2]] 
: [2], [0] : !llvm.ptr, !llvm.ptr) -> !llvm.ptr {name = "dtype", partial_map = 
true} 
+  %5 = omp.map.info var_ptr(%4 : !fir.ref, f32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "dtype%real"}
+  // CHECK: %[[MAP_PARENT:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<"_QFderived_type", (f32, array<10 x i32>, i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[MAP_MEMBER_1]], %[[MAP_MEMBER_2]] 
: [2], [0] : !llvm.ptr, !llvm.ptr) -> !llvm.ptr {name = "dtype", partial_map = 
true}
   %6 = omp.map.info var_ptr(%arg0 : 
!fir.ref,int:i32}>>,
 !fir.type<_QFderived_type{real:f32,array:!fir.array<10xi32>,int:i32}>) 
map_clauses(tofrom) capture(ByRef) members(%2, %5 : [2], [0] : !fir.ref, 
!fir.ref) -> 
!fir.ref,int:i32}>> 
{name = "dtype", partial_map = true}
   // CHECK: omp.target map_entries(%[[MAP_MEMBER_1]] -> %[[ARG_1:.*]], 
%[[MAP_MEMBER_2]] -> %[[ARG_2:.*]], %[[MAP_PARENT]] -> %[[ARG_3:.*]] : 
!llvm.ptr, !llvm.ptr, !llvm.ptr) {
   omp.target map_entries(%2 -> %arg1, %5 -> %arg2, %6 -> %arg3 : 
!fir.ref, !fir.ref, 
!fir.ref,int:i32}>>)
 {
@@ -1275,3 +1275,22 @@ func.func @map_nested_dtype_alloca_mem2(%arg0 : 
!fir.ref {
+omp.declare_mapper @my_mapper : !fir.type<_QFdeclare_mapperTmy_type{data:i32}> 
{
+// CHECK: ^bb0(%[[VAL_0:.*]]: !llvm.ptr):
+^bb0(%0: !fir.ref>):
+// CHECK:   %[[VAL_1:.*]] = llvm.mlir.constant(0 : i32) : i32
+  %1 = fir.field_index data, !fir.type<_QFdeclare_mapperTmy_type{data:i32}>
+// CHECK:   %[[VAL_2:.*]] = llvm.getelementptr %[[VAL_0]][0, 0] : 
(!llvm.ptr) -> !llvm.ptr, !llvm.struct<"_QFdeclare_mapperTmy_type", (i32)>
+  %2 = fir.coordinate_of %0, %1 : 
(!fir.ref>, !fir.field) -> 
!fir.ref
+// CHECK:   %[[VAL_3:.*]] = omp.map.info var_ptr(%[[VAL_2]] : 
!llvm.ptr, i32) map_clauses(tofrom) capture(ByRef) -> !llvm.ptr {name = 
"var%[[VAL_4:.*]]"}
+  %3 = omp.map.info var_ptr(%2 : !fir.ref, i32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "var%data"}
+// CHECK:   %[[VAL_5:.*]] = omp.map.info var_ptr(%[[VAL_0]] : 
!llvm.ptr, !llvm.struct<"_QFdeclare_mapperTmy_type", (i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[VAL_3]] : [0] : !llvm.ptr) -> 
!llvm.ptr {name = "var", partial_map = true}
+  %4 = omp.map.info var_ptr(%0 : 
!fir.ref>, 
!fir.type<_QFdeclare_mapperTmy_type{data:i32}>) map_clauses(tofrom) 
capture(ByRef) members(%3 : [0] : !fir.ref) -> 
!fir.ref> {name = "var", 
partial_map = true}
+// CHECK:   omp.declare_mapper_info map_entries(%[[VAL_5]], %[[VAL_3]] 
: !llvm.ptr, !llvm.ptr)
+  omp.declare_m

[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add OMP Mapper field to MapInfoOp (PR #120994)

2025-02-11 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/120994

>From 57858d2e19897a72057464bd33311d2cd4d4f156 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 20:53:47 +
Subject: [PATCH 1/2] Add mapper field to mapInfoOp.

---
 flang/lib/Lower/OpenMP/Utils.cpp| 3 ++-
 flang/lib/Lower/OpenMP/Utils.h  | 3 ++-
 flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp  | 5 -
 flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp | 1 +
 mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td   | 2 ++
 mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp| 2 +-
 mlir/test/Dialect/OpenMP/ops.mlir   | 4 ++--
 7 files changed, 14 insertions(+), 6 deletions(-)

diff --git a/flang/lib/Lower/OpenMP/Utils.cpp b/flang/lib/Lower/OpenMP/Utils.cpp
index 35722fa7d1b12..fa1975dac789b 100644
--- a/flang/lib/Lower/OpenMP/Utils.cpp
+++ b/flang/lib/Lower/OpenMP/Utils.cpp
@@ -125,7 +125,7 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
 llvm::ArrayRef members,
 mlir::ArrayAttr membersIndex, uint64_t mapType,
 mlir::omp::VariableCaptureKind mapCaptureType, mlir::Type 
retTy,
-bool partialMap) {
+bool partialMap, mlir::FlatSymbolRefAttr mapperId) {
   if (auto boxTy = llvm::dyn_cast(baseAddr.getType())) {
 baseAddr = builder.create(loc, baseAddr);
 retTy = baseAddr.getType();
@@ -144,6 +144,7 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
   mlir::omp::MapInfoOp op = builder.create(
   loc, retTy, baseAddr, varType, varPtrPtr, members, membersIndex, bounds,
   builder.getIntegerAttr(builder.getIntegerType(64, false), mapType),
+  mapperId,
   builder.getAttr(mapCaptureType),
   builder.getStringAttr(name), builder.getBoolAttr(partialMap));
   return op;
diff --git a/flang/lib/Lower/OpenMP/Utils.h b/flang/lib/Lower/OpenMP/Utils.h
index f2e378443e5f2..3943eb633b04e 100644
--- a/flang/lib/Lower/OpenMP/Utils.h
+++ b/flang/lib/Lower/OpenMP/Utils.h
@@ -116,7 +116,8 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
 llvm::ArrayRef members,
 mlir::ArrayAttr membersIndex, uint64_t mapType,
 mlir::omp::VariableCaptureKind mapCaptureType, mlir::Type 
retTy,
-bool partialMap = false);
+bool partialMap = false,
+mlir::FlatSymbolRefAttr mapperId = mlir::FlatSymbolRefAttr());
 
 void insertChildMapInfoIntoParent(
 Fortran::lower::AbstractConverter &converter,
diff --git a/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp 
b/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
index e7c1d1d9d560f..beea7543e54b3 100644
--- a/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
+++ b/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
@@ -184,6 +184,7 @@ class MapInfoFinalizationPass
 /*members=*/mlir::SmallVector{},
 /*membersIndex=*/mlir::ArrayAttr{}, bounds,
 builder.getIntegerAttr(builder.getIntegerType(64, false), mapType),
+/*mapperId*/ mlir::FlatSymbolRefAttr(),
 builder.getAttr(
 mlir::omp::VariableCaptureKind::ByRef),
 /*name=*/builder.getStringAttr(""),
@@ -329,7 +330,8 @@ class MapInfoFinalizationPass
 builder.getIntegerAttr(
 builder.getIntegerType(64, false),
 getDescriptorMapType(op.getMapType().value_or(0), target)),
-op.getMapCaptureTypeAttr(), op.getNameAttr(),
+/*mapperId*/ mlir::FlatSymbolRefAttr(), op.getMapCaptureTypeAttr(),
+op.getNameAttr(),
 /*partial_map=*/builder.getBoolAttr(false));
 op.replaceAllUsesWith(newDescParentMapOp.getResult());
 op->erase();
@@ -623,6 +625,7 @@ class MapInfoFinalizationPass
   /*members=*/mlir::ValueRange{},
   /*members_index=*/mlir::ArrayAttr{},
   /*bounds=*/bounds, op.getMapTypeAttr(),
+  /*mapperId*/ mlir::FlatSymbolRefAttr(),
   builder.getAttr(
   mlir::omp::VariableCaptureKind::ByRef),
   builder.getStringAttr(op.getNameAttr().strref() + "." +
diff --git a/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp 
b/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
index 963ae863c1fc5..97ea463a3c495 100644
--- a/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
+++ b/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
@@ -91,6 +91,7 @@ class MapsForPrivatizedSymbolsPass
 /*bounds=*/ValueRange{},
 builder.getIntegerAttr(builder.getIntegerType(64, /*isSigned=*/false),
mapTypeTo),
+/*mapperId*/ mlir::FlatSymbolRefAttr(),
 builder.getAttr(
 omp::VariableCaptureKind::ByRef),
 StringAttr(), builder.getBoolAttr(false));
diff --git a/mlir/include/mlir/

[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add Lowering support for OpenMP custom mappers in map clause (PR #121001)

2025-02-11 Thread Akash Banerjee via llvm-branch-commits


@@ -1003,6 +1006,20 @@ void ClauseProcessor::processMapObjects(
   }
 }
 
+if (!mapperIdName.empty()) {

TIFitis wrote:

The if is contained in a loop and I want the if to execute only the first 
iteration. So this replacement won't be helpful here.

https://github.com/llvm/llvm-project/pull/121001
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2025-02-11 Thread Akash Banerjee via llvm-branch-commits


@@ -0,0 +1,85 @@
+! This test checks lowering of OpenMP declare mapper Directive.
+
+! RUN: split-file %s %t
+! RUN: %flang_fc1 -emit-hlfir -fopenmp -fopenmp-version=50 
%t/omp-declare-mapper-1.f90 -o - | FileCheck %t/omp-declare-mapper-1.f90
+! RUN: %flang_fc1 -emit-hlfir -fopenmp -fopenmp-version=50 
%t/omp-declare-mapper-2.f90 -o - | FileCheck %t/omp-declare-mapper-2.f90
+
+!--- omp-declare-mapper-1.f90
+subroutine declare_mapper_1
+   integer, parameter  :: nvals = 250
+   type my_type
+  integer  :: num_vals
+  integer, allocatable :: values(:)
+   end type
+
+   type my_type2
+  type(my_type):: my_type_var
+  type(my_type):: temp
+  real, dimension(nvals) :: unmapped
+  real, dimension(nvals) :: arr
+   end type
+   type(my_type2):: t
+   real   :: x, y(nvals)
+   !CHECK:omp.declare_mapper 
@[[MY_TYPE_MAPPER:_QQFdeclare_mapper_1my_type\.default]] : 
[[MY_TYPE:!fir\.type<_QFdeclare_mapper_1Tmy_type\{num_vals:i32,values:!fir\.box>>\}>]]
 {
+   !CHECK:  ^bb0(%[[VAL_0:.*]]: !fir.ref<[[MY_TYPE]]>):
+   !CHECK:%[[VAL_1:.*]]:2 = hlfir.declare %[[VAL_0]] {uniq_name = 
"_QFdeclare_mapper_1Evar"} : (!fir.ref<[[MY_TYPE]]>) -> (!fir.ref<[[MY_TYPE]]>, 
!fir.ref<[[MY_TYPE]]>)
+   !CHECK:%[[VAL_2:.*]] = hlfir.designate %[[VAL_1]]#0{"values"}   
{fortran_attrs = #fir.var_attrs} : (!fir.ref<[[MY_TYPE]]>) -> 
!fir.ref>>>
+   !CHECK:%[[VAL_3:.*]] = fir.load %[[VAL_2]] : 
!fir.ref>>>
+   !CHECK:%[[VAL_4:.*]] = fir.box_addr %[[VAL_3]] : 
(!fir.box>>) -> !fir.heap>
+   !CHECK:%[[VAL_5:.*]] = arith.constant 0 : index
+   !CHECK:%[[VAL_6:.*]]:3 = fir.box_dims %[[VAL_3]], %[[VAL_5]] : 
(!fir.box>>, index) -> (index, index, index)
+   !CHECK:%[[VAL_7:.*]] = arith.constant 0 : index
+   !CHECK:%[[VAL_8:.*]] = arith.constant 1 : index
+   !CHECK:%[[VAL_9:.*]] = arith.constant 1 : index
+   !CHECK:%[[VAL_10:.*]] = arith.subi %[[VAL_9]], %[[VAL_6]]#0 : index
+   !CHECK:%[[VAL_11:.*]] = hlfir.designate %[[VAL_1]]#0{"num_vals"}   
: (!fir.ref<[[MY_TYPE]]>) -> !fir.ref
+   !CHECK:%[[VAL_12:.*]] = fir.load %[[VAL_11]] : !fir.ref
+   !CHECK:%[[VAL_13:.*]] = fir.convert %[[VAL_12]] : (i32) -> i64
+   !CHECK:%[[VAL_14:.*]] = fir.convert %[[VAL_13]] : (i64) -> index
+   !CHECK:%[[VAL_15:.*]] = arith.subi %[[VAL_14]], %[[VAL_6]]#0 : index
+   !CHECK:%[[VAL_16:.*]] = omp.map.bounds lower_bound(%[[VAL_10]] : 
index) upper_bound(%[[VAL_15]] : index) extent(%[[VAL_6]]#1 : index) 
stride(%[[VAL_8]] : index) start_idx(%[[VAL_6]]#0 : index)
+   !CHECK:%[[VAL_17:.*]] = arith.constant 1 : index
+   !CHECK:%[[VAL_18:.*]] = fir.coordinate_of %[[VAL_1]]#0, %[[VAL_17]] 
: (!fir.ref<[[MY_TYPE]]>, index) -> 
!fir.ref>>>
+   !CHECK:%[[VAL_19:.*]] = fir.box_offset %[[VAL_18]] base_addr : 
(!fir.ref>>>) -> 
!fir.llvm_ptr>>
+   !CHECK:%[[VAL_20:.*]] = omp.map.info var_ptr(%[[VAL_18]] : 
!fir.ref>>>, i32) var_ptr_ptr(%[[VAL_19]] 
: !fir.llvm_ptr>>) map_clauses(tofrom) 
capture(ByRef) bounds(%[[VAL_16]]) -> 
!fir.llvm_ptr>> {name = ""}
+   !CHECK:%[[VAL_21:.*]] = omp.map.info var_ptr(%[[VAL_18]] : 
!fir.ref>>>, 
!fir.box>>) map_clauses(to) capture(ByRef) -> 
!fir.ref>>> {name = 
"var%[[VAL_22:.*]](1:var%[[VAL_23:.*]])"}
+   !CHECK:%[[VAL_24:.*]] = omp.map.info var_ptr(%[[VAL_1]]#1 : 
!fir.ref<[[MY_TYPE]]>, [[MY_TYPE]]) map_clauses(tofrom) capture(ByRef) 
members(%[[VAL_21]], %[[VAL_20]] : [1], [1, 0] : 
!fir.ref>>>, 
!fir.llvm_ptr>>) -> !fir.ref<[[MY_TYPE]]> {name = 
"var"}
+   !CHECK:omp.declare_mapper.info map_entries(%[[VAL_24]], 
%[[VAL_21]], %[[VAL_20]] : !fir.ref<[[MY_TYPE]]>, 
!fir.ref>>>, 
!fir.llvm_ptr>>)
+   !CHECK:  }
+   !$omp declare mapper (my_type :: var) map (var, var%values (1:var%num_vals))
+end subroutine declare_mapper_1
+
+!--- omp-declare-mapper-2.f90
+subroutine declare_mapper_2
+   integer, parameter  :: nvals = 250
+   type my_type
+  integer  :: num_vals
+  integer, allocatable :: values(:)
+   end type
+
+   type my_type2
+  type(my_type):: my_type_var
+  type(my_type):: temp
+  real, dimension(nvals) :: unmapped
+  real, dimension(nvals) :: arr
+   end type
+   type(my_type2):: t
+   real  :: x, y(nvals)
+   !CHECK:omp.declare_mapper @[[MY_TYPE_MAPPER:_QQFdeclare_mapper_2my_mapper]] 
: 
[[MY_TYPE:!fir\.type<_QFdeclare_mapper_2Tmy_type2\{my_type_var:!fir\.type<_QFdeclare_mapper_2Tmy_type\{num_vals:i32,values:!fir\.box>>\}>,temp:!fir\.type<_QFdeclare_mapper_2Tmy_type\{num_vals:i32,values:!fir\.box>>\}>,unmapped:!fir\.array<250xf32>,arr:!fir\.array<250xf32>\}>]]
 {
+   !CHECK:  ^bb0(%[[VAL_0:.*]]: !fir.ref<[[MY_TYPE]]>):
+   !CHECK:%[[VAL_1:.*]]:2 = hlfir.declare %[[VAL_0]] {uniq_name = 
"_QFdeclare_mapper_2Ev"} : (!fir.ref<[[MY_TYPE]]>) -> (!fir.ref<[[MY_TYPE

[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP custom mappers in map clause (PR #121001)

2025-02-11 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/121001

>From 107f59d06dcb0523e373682b5879bb79c824bb2f Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 21:13:42 +
Subject: [PATCH 1/5] Add flang lowering changes for mapper field in map
 clause.

---
 flang/lib/Lower/OpenMP/ClauseProcessor.cpp  | 32 +
 flang/lib/Lower/OpenMP/ClauseProcessor.h|  3 +-
 flang/test/Lower/OpenMP/Todo/map-mapper.f90 | 16 ---
 flang/test/Lower/OpenMP/map-mapper.f90  | 23 +++
 4 files changed, 52 insertions(+), 22 deletions(-)
 delete mode 100644 flang/test/Lower/OpenMP/Todo/map-mapper.f90
 create mode 100644 flang/test/Lower/OpenMP/map-mapper.f90

diff --git a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp 
b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
index febc6adcf9d6f..467a0dcebf2b8 100644
--- a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
+++ b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
@@ -969,8 +969,10 @@ void ClauseProcessor::processMapObjects(
 llvm::omp::OpenMPOffloadMappingFlags mapTypeBits,
 std::map &parentMemberIndices,
 llvm::SmallVectorImpl &mapVars,
-llvm::SmallVectorImpl &mapSyms) const {
+llvm::SmallVectorImpl &mapSyms,
+std::string mapperIdName) const {
   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  mlir::FlatSymbolRefAttr mapperId;
 
   for (const omp::Object &object : objects) {
 llvm::SmallVector bounds;
@@ -1003,6 +1005,20 @@ void ClauseProcessor::processMapObjects(
   }
 }
 
+if (!mapperIdName.empty()) {
+  if (mapperIdName == "default") {
+auto &typeSpec = object.sym()->owner().IsDerivedType()
+ ? *object.sym()->owner().derivedTypeSpec()
+ : object.sym()->GetType()->derivedTypeSpec();
+mapperIdName = typeSpec.name().ToString() + ".default";
+mapperIdName = converter.mangleName(mapperIdName, 
*typeSpec.GetScope());
+  }
+  assert(converter.getMLIRSymbolTable()->lookup(mapperIdName) &&
+ "mapper not found");
+  mapperId = mlir::FlatSymbolRefAttr::get(&converter.getMLIRContext(),
+  mapperIdName);
+  mapperIdName.clear();
+}
 // Explicit map captures are captured ByRef by default,
 // optimisation passes may alter this to ByCopy or other capture
 // types to optimise
@@ -1016,7 +1032,8 @@ void ClauseProcessor::processMapObjects(
 static_cast<
 std::underlying_type_t>(
 mapTypeBits),
-mlir::omp::VariableCaptureKind::ByRef, baseOp.getType());
+mlir::omp::VariableCaptureKind::ByRef, baseOp.getType(), false,
+mapperId);
 
 if (parentObj.has_value()) {
   parentMemberIndices[parentObj.value()].addChildIndexAndMapToParent(
@@ -1047,6 +1064,7 @@ bool ClauseProcessor::processMap(
 const auto &[mapType, typeMods, mappers, iterator, objects] = clause.t;
 llvm::omp::OpenMPOffloadMappingFlags mapTypeBits =
 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE;
+std::string mapperIdName;
 // If the map type is specified, then process it else Tofrom is the
 // default.
 Map::MapType type = mapType.value_or(Map::MapType::Tofrom);
@@ -1090,13 +1108,17 @@ bool ClauseProcessor::processMap(
"Support for iterator modifiers is not implemented yet");
 }
 if (mappers) {
-  TODO(currentLocation,
-   "Support for mapper modifiers is not implemented yet");
+  assert(mappers->size() == 1 && "more than one mapper");
+  mapperIdName = mappers->front().v.id().symbol->name().ToString();
+  if (mapperIdName != "default")
+mapperIdName = converter.mangleName(
+mapperIdName, mappers->front().v.id().symbol->owner());
 }
 
 processMapObjects(stmtCtx, clauseLocation,
   std::get(clause.t), mapTypeBits,
-  parentMemberIndices, result.mapVars, *ptrMapSyms);
+  parentMemberIndices, result.mapVars, *ptrMapSyms,
+  mapperIdName);
   };
 
   bool clauseFound = findRepeatableClause(process);
diff --git a/flang/lib/Lower/OpenMP/ClauseProcessor.h 
b/flang/lib/Lower/OpenMP/ClauseProcessor.h
index e05f66c766684..2b319e890a5ad 100644
--- a/flang/lib/Lower/OpenMP/ClauseProcessor.h
+++ b/flang/lib/Lower/OpenMP/ClauseProcessor.h
@@ -175,7 +175,8 @@ class ClauseProcessor {
   llvm::omp::OpenMPOffloadMappingFlags mapTypeBits,
   std::map &parentMemberIndices,
   llvm::SmallVectorImpl &mapVars,
-  llvm::SmallVectorImpl &mapSyms) const;
+  llvm::SmallVectorImpl &mapSyms,
+  std::string mapperIdName = "") const;
 
   lower::AbstractConverter &converter;
   semantics::SemanticsContext &semaCtx;
diff --git a/flang/test/Lower/OpenMP/Todo/map-mapper.f90 
b/flang/test/Lower/OpenMP/Todo/map-mapper.f90
deleted file mode 100644
index 9554ffd5fda7b..0
--- a/flang/test/Lowe

[llvm-branch-commits] [clang] [flang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-02-11 Thread Akash Banerjee via llvm-branch-commits


@@ -3529,6 +3549,84 @@ static void genMapInfos(llvm::IRBuilderBase &builder,
   }
 }
 
+static llvm::Expected
+emitUserDefinedMapper(Operation *declMapperOp, llvm::IRBuilderBase &builder,
+  LLVM::ModuleTranslation &moduleTranslation);
+
+static llvm::Expected
+getOrCreateUserDefinedMapperFunc(Operation *declMapperOp,
+ llvm::IRBuilderBase &builder,
+ LLVM::ModuleTranslation &moduleTranslation) {
+  static llvm::DenseMap userDefMapperMap;

TIFitis wrote:

Thanks for the suggestion, I've reworked this bit of code.

https://github.com/llvm/llvm-project/pull/124746
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add conversion support from FIR to LLVM Dialect for OMP DeclareMapper (PR #121005)

2025-02-11 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/121005

>From 0cba204faac851d186470b74aab3601a987e0f2d Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 21:50:03 +
Subject: [PATCH 1/2] Add OpenMP to LLVM dialect conversion support for
 DeclareMapperOp.

---
 .../Fir/convert-to-llvm-openmp-and-fir.fir| 27 +--
 .../Conversion/OpenMPToLLVM/OpenMPToLLVM.cpp  | 48 +++
 .../OpenMPToLLVM/convert-to-llvmir.mlir   | 13 +
 3 files changed, 74 insertions(+), 14 deletions(-)

diff --git a/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir 
b/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
index 8e4e1fe824d9f..82f2aea3ad983 100644
--- a/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
+++ b/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
@@ -936,9 +936,9 @@ func.func @omp_map_info_descriptor_type_conversion(%arg0 : 
!fir.ref>, i32) 
map_clauses(tofrom) capture(ByRef) -> !fir.llvm_ptr> {name = ""}
   // CHECK: %[[DESC_MAP:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<(ptr, i64, i32, i8, i8, i8, i8)>) map_clauses(always, delete) 
capture(ByRef) members(%[[MEMBER_MAP]] : [0] : !llvm.ptr) -> !llvm.ptr {name = 
""}
   %2 = omp.map.info var_ptr(%arg0 : !fir.ref>>, 
!fir.box>) map_clauses(always, delete) capture(ByRef) members(%1 
: [0] : !fir.llvm_ptr>) -> !fir.ref>> 
{name = ""}
-  // CHECK: omp.target_exit_data map_entries(%[[DESC_MAP]] : !llvm.ptr) 
+  // CHECK: omp.target_exit_data map_entries(%[[DESC_MAP]] : !llvm.ptr)
   omp.target_exit_data   map_entries(%2 : !fir.ref>>)
-  return 
+  return
 }
 
 // -
@@ -956,8 +956,8 @@ func.func 
@omp_map_info_derived_type_explicit_member_conversion(%arg0 : !fir.ref
   %3 = fir.field_index real, 
!fir.type<_QFderived_type{real:f32,array:!fir.array<10xi32>,int:i32}>
   %4 = fir.coordinate_of %arg0, %3 : 
(!fir.ref,int:i32}>>,
 !fir.field) -> !fir.ref
   // CHECK: %[[MAP_MEMBER_2:.*]] = omp.map.info var_ptr(%[[GEP_2]] : 
!llvm.ptr, f32) map_clauses(tofrom) capture(ByRef) -> !llvm.ptr {name = 
"dtype%real"}
-  %5 = omp.map.info var_ptr(%4 : !fir.ref, f32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "dtype%real"}
-  // CHECK: %[[MAP_PARENT:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<"_QFderived_type", (f32, array<10 x i32>, i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[MAP_MEMBER_1]], %[[MAP_MEMBER_2]] 
: [2], [0] : !llvm.ptr, !llvm.ptr) -> !llvm.ptr {name = "dtype", partial_map = 
true} 
+  %5 = omp.map.info var_ptr(%4 : !fir.ref, f32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "dtype%real"}
+  // CHECK: %[[MAP_PARENT:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<"_QFderived_type", (f32, array<10 x i32>, i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[MAP_MEMBER_1]], %[[MAP_MEMBER_2]] 
: [2], [0] : !llvm.ptr, !llvm.ptr) -> !llvm.ptr {name = "dtype", partial_map = 
true}
   %6 = omp.map.info var_ptr(%arg0 : 
!fir.ref,int:i32}>>,
 !fir.type<_QFderived_type{real:f32,array:!fir.array<10xi32>,int:i32}>) 
map_clauses(tofrom) capture(ByRef) members(%2, %5 : [2], [0] : !fir.ref, 
!fir.ref) -> 
!fir.ref,int:i32}>> 
{name = "dtype", partial_map = true}
   // CHECK: omp.target map_entries(%[[MAP_MEMBER_1]] -> %[[ARG_1:.*]], 
%[[MAP_MEMBER_2]] -> %[[ARG_2:.*]], %[[MAP_PARENT]] -> %[[ARG_3:.*]] : 
!llvm.ptr, !llvm.ptr, !llvm.ptr) {
   omp.target map_entries(%2 -> %arg1, %5 -> %arg2, %6 -> %arg3 : 
!fir.ref, !fir.ref, 
!fir.ref,int:i32}>>)
 {
@@ -1275,3 +1275,22 @@ func.func @map_nested_dtype_alloca_mem2(%arg0 : 
!fir.ref {
+omp.declare_mapper @my_mapper : !fir.type<_QFdeclare_mapperTmy_type{data:i32}> 
{
+// CHECK: ^bb0(%[[VAL_0:.*]]: !llvm.ptr):
+^bb0(%0: !fir.ref>):
+// CHECK:   %[[VAL_1:.*]] = llvm.mlir.constant(0 : i32) : i32
+  %1 = fir.field_index data, !fir.type<_QFdeclare_mapperTmy_type{data:i32}>
+// CHECK:   %[[VAL_2:.*]] = llvm.getelementptr %[[VAL_0]][0, 0] : 
(!llvm.ptr) -> !llvm.ptr, !llvm.struct<"_QFdeclare_mapperTmy_type", (i32)>
+  %2 = fir.coordinate_of %0, %1 : 
(!fir.ref>, !fir.field) -> 
!fir.ref
+// CHECK:   %[[VAL_3:.*]] = omp.map.info var_ptr(%[[VAL_2]] : 
!llvm.ptr, i32) map_clauses(tofrom) capture(ByRef) -> !llvm.ptr {name = 
"var%[[VAL_4:.*]]"}
+  %3 = omp.map.info var_ptr(%2 : !fir.ref, i32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "var%data"}
+// CHECK:   %[[VAL_5:.*]] = omp.map.info var_ptr(%[[VAL_0]] : 
!llvm.ptr, !llvm.struct<"_QFdeclare_mapperTmy_type", (i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[VAL_3]] : [0] : !llvm.ptr) -> 
!llvm.ptr {name = "var", partial_map = true}
+  %4 = omp.map.info var_ptr(%0 : 
!fir.ref>, 
!fir.type<_QFdeclare_mapperTmy_type{data:i32}>) map_clauses(tofrom) 
capture(ByRef) members(%3 : [0] : !fir.ref) -> 
!fir.ref> {name = "var", 
partial_map = true}
+// CHECK:   omp.declare_mapper_info map_entries(%[[VAL_5]], %[[VAL_3]] 
: !llvm.ptr, !llvm.ptr)
+  omp.declare_mappe

[llvm-branch-commits] [clang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-01-30 Thread Akash Banerjee via llvm-branch-commits


@@ -3421,6 +3441,85 @@ static void genMapInfos(llvm::IRBuilderBase &builder,
   }
 }
 
+static llvm::Expected
+emitUserDefinedMapper(Operation *declMapperOp, llvm::IRBuilderBase &builder,
+  LLVM::ModuleTranslation &moduleTranslation);
+
+static llvm::Expected
+getOrCreateUserDefinedMapperFunc(Operation *declMapperOp,
+ llvm::IRBuilderBase &builder,
+ LLVM::ModuleTranslation &moduleTranslation) {
+  llvm::DenseMap userDefMapperMap;
+  auto iter = userDefMapperMap.find(declMapperOp);

TIFitis wrote:

Yes, the mapping is intended to be at the Module scope, across multiple 
`emitUserDefinedMapper` calls within the same Module.

https://github.com/llvm/llvm-project/pull/124746
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-01-30 Thread Akash Banerjee via llvm-branch-commits


@@ -3421,6 +3441,85 @@ static void genMapInfos(llvm::IRBuilderBase &builder,
   }
 }
 
+static llvm::Expected
+emitUserDefinedMapper(Operation *declMapperOp, llvm::IRBuilderBase &builder,
+  LLVM::ModuleTranslation &moduleTranslation);
+
+static llvm::Expected
+getOrCreateUserDefinedMapperFunc(Operation *declMapperOp,
+ llvm::IRBuilderBase &builder,
+ LLVM::ModuleTranslation &moduleTranslation) {
+  llvm::DenseMap userDefMapperMap;
+  auto iter = userDefMapperMap.find(declMapperOp);
+  if (iter != userDefMapperMap.end())
+return iter->second;
+  llvm::Expected mapperFunc =
+  emitUserDefinedMapper(declMapperOp, builder, moduleTranslation);
+  if (!mapperFunc)
+return mapperFunc.takeError();
+  userDefMapperMap.try_emplace(declMapperOp, *mapperFunc);
+  return userDefMapperMap.lookup(declMapperOp);
+}
+
+static llvm::Expected
+emitUserDefinedMapper(Operation *op, llvm::IRBuilderBase &builder,
+  LLVM::ModuleTranslation &moduleTranslation) {
+  auto declMapperOp = cast(op);
+  auto declMapperInfoOp =
+  *declMapperOp.getOps().begin();
+  DataLayout dl = DataLayout(declMapperOp->getParentOfType());
+  llvm::OpenMPIRBuilder *ompBuilder = moduleTranslation.getOpenMPBuilder();
+  llvm::Type *varType =
+  moduleTranslation.convertType(declMapperOp.getVarType());
+  std::string mapperName = ompBuilder->createPlatformSpecificName(
+  {"omp_mapper", declMapperOp.getSymName()});
+  SmallVector mapVars = declMapperInfoOp.getMapVars();
+
+  using InsertPointTy = llvm::OpenMPIRBuilder::InsertPointTy;
+
+  // Fill up the arrays with all the mapped variables.
+  MapInfosTy combinedInfo;
+  auto genMapInfoCB =
+  [&](InsertPointTy codeGenIP, llvm::Value *ptrPHI,
+  llvm::Value *unused2) -> llvm::OpenMPIRBuilder::MapInfosOrErrorTy {
+builder.restoreIP(codeGenIP);
+moduleTranslation.mapValue(declMapperOp.getRegion().getArgument(0), 
ptrPHI);
+moduleTranslation.mapBlock(&declMapperOp.getRegion().front(),
+   builder.GetInsertBlock());
+if (failed(moduleTranslation.convertBlock(declMapperOp.getRegion().front(),
+  /*ignoreArguments=*/true,
+  builder)))
+  return llvm::make_error();
+MapInfoData mapData;
+collectMapDataFromMapOperands(mapData, mapVars, moduleTranslation, dl,
+  builder);
+genMapInfos(builder, moduleTranslation, dl, combinedInfo, mapData);
+
+// Drop the mapping that is no longer necessary so that the same region can
+// be processed multiple times.
+moduleTranslation.forgetMapping(declMapperOp.getRegion());
+return combinedInfo;
+  };
+
+  auto customMapperCB = [&](unsigned i, llvm::Function **mapperFunc) {
+if (combinedInfo.Mappers[i]) {
+  // Call the corresponding mapper function.
+  llvm::Expected newFn = 
getOrCreateUserDefinedMapperFunc(

TIFitis wrote:

`getOrCreateUserDefinedMapperFunc` is the interface function for 
fetching/creating mapperFuncs. It does a lookup for the mapperFunc and emits 
one if not already present through the `emitUserDefinedMapper` function.

A declare mapper may refer to another mapper in it's mapping scheme, as such 
`emitUserDefinedMapper` may again make calls to 
`getOrCreateUserDefinedMapperFunc`. But I believe code flow disallows cycles, 
so we shouldn't go into any cyclic recursions.

https://github.com/llvm/llvm-project/pull/124746
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-01-30 Thread Akash Banerjee via llvm-branch-commits


@@ -2709,13 +2709,23 @@ getRefPtrIfDeclareTarget(mlir::Value value,
 }
 
 namespace {
+// Append customMappers information to existing MapInfosTy
+struct MapInfosTy : llvm::OpenMPIRBuilder::MapInfosTy {
+  SmallVector Mappers;

TIFitis wrote:

Technically it might be possible but probably not a good idea. `MapInfoData` is 
mean't to be used when coalescing the mapping data from the various map and 
bound ops.

`llvm::OpenMPIRBuilder::MapInfosTy` is used across MLIR, Clang and OMPIRBuilder 
for target codegen.

https://github.com/llvm/llvm-project/pull/124746
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2024-12-11 Thread Akash Banerjee via llvm-branch-commits

TIFitis wrote:

@kiranchandramohan @kparzysz I guess I must be using the name mangler in an 
incorrect way then. I've added the code snippets I am using when lowering and 
later performing a lookup. Please let me know what would be the correct way of 
doing this.

When lowering DeclMapperOp:
```
static void
genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
   semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
   const parser::OpenMPDeclareMapperConstruct &declareMapperConstruct) {
  fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
  const auto &spec =
  std::get(declareMapperConstruct.t);
  const auto &mapperName{std::get>(spec.t)};
  std::string mapperNameStr;
  if (mapperName.has_value())
mapperNameStr = mapperName->ToString();
  else
mapperNameStr =
"default_" + varType.declTypeSpec->derivedTypeSpec().name().ToString();

  // This is my current implementation.
  // It returns _QQFmy_mapper as mapperNameStr.
  mapperNameStr = converter.mangleName(*mapperName->symbol);

  auto declMapperOp = firOpBuilder.create(
  loc, mapperNameStr, mlirType);
  converter.getMLIRSymbolTable()->insert(declMapperOp);

  // This code produces the error:
  // LLVM ERROR: 
/home/akash/Documents/llvm-project/flang/lib/Lower/Mangler.cpp:184: not yet 
implemented: symbol mangling
  // mapperNameStr = converter.mangleName(*mapperName->symbol);
  
  // This code produces the error:
  // ** symbol not properly mapped **
  // symTable.lookupSymbol(mapperName->symbol).dump();
```

When trying to lookup DeclareMapper from the mapClause mapper:

```
  auto mapperIdName = mappers->front().v.id().symbol->name().ToString();
  mapperIdName = converter.mangleName(mapperIdName);

  // Here mapperIdName returns _QQFFtestmy_mapper which fails the
  // lookup inside the asser.

  // assert(converter.getMLIRSymbolTable()->lookup(mapperIdName) &&
  //"mapper not found");
  mapperId = mlir::FlatSymbolRefAttr::get(&converter.getMLIRContext(),
  mapperIdName);
```

https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2024-12-10 Thread Akash Banerjee via llvm-branch-commits

TIFitis wrote:

@kiranchandramohan I discussed the current approach with @skatrak today. When 
trying to implement the mapper lowering for the map clause, it became apparent 
that we need to add the `declMapperOp` name to the `SymbolTable`. As such, we 
would also need to hoist the `declareMapperOp` to the `ModuleOp`.

I am however struggling with name mangling the `declMapperOp` such that scoping 
information is preserved, and we don't have clashing `declMapperOps` from 
different nested scopes with the same name.

Take the following example:
```
program my_prog
   type my_type
  integer   :: num
   end type
   !$omp declare mapper (my_mapper : my_type :: my_var) map (my_var)
contains
   subroutine test
  type(my_type):: xyz
  !$omp target enter data map(mapper(my_mapper), to: xyz)
   end subroutine test
end program my_prog
```

Here after mangling the, `declMapperOp` symbol name becomes `_QQFmy_mapper`. 
But when trying to mangle the name that occurs in the mapClause before lookup 
results in `_QQFFtestmy_mapper`.

Do you know any mechanism in Fortran lowering that could help resolve this 
issue?

https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2024-11-21 Thread Akash Banerjee via llvm-branch-commits


@@ -21,7 +21,7 @@ subroutine declare_mapper_1
   type (my_type2):: t
   real   :: x, y(nvals)
   !$omp declare mapper (my_type :: var) map (var, var%values (1:var%num_vals))
-!CHECK: not yet implemented: OpenMPDeclareMapperConstruct
+!CHECK: not yet implemented: lowering symbol to HLFIR

TIFitis wrote:

This error is now from an unhandled form of map clause rather than declare 
mapper. As such, I believe it's out of scope for this PR.

I will however subsequently look into fixing it in a separate PR, hope that 
doesn't hold up this PR.

https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2024-11-22 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis edited 
https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2024-11-22 Thread Akash Banerjee via llvm-branch-commits


@@ -2701,7 +2702,39 @@ static void
 genOMP(lower::AbstractConverter &converter, lower::SymMap &symTable,
semantics::SemanticsContext &semaCtx, lower::pft::Evaluation &eval,
const parser::OpenMPDeclareMapperConstruct &declareMapperConstruct) {
-  TODO(converter.getCurrentLocation(), "OpenMPDeclareMapperConstruct");
+  fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  lower::StatementContext stmtCtx;
+  const auto &spec =
+  std::get(declareMapperConstruct.t);
+  const auto &mapperName{std::get>(spec.t)};
+  const auto &varType{std::get(spec.t)};
+  const auto &varName{std::get(spec.t)};
+  std::stringstream mapperNameStr;
+  if (mapperName.has_value()) {
+mapperNameStr << mapperName->ToString();
+  } else {
+mapperNameStr << "default_"
+  << varType.declTypeSpec->derivedTypeSpec().name().ToString();
+  }

TIFitis wrote:

Done.

https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add OMP Mapper field to MapInfoOp (PR #120994)

2025-01-28 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/120994

>From 002d7153f4029c02722b6a4f45bbde8fad83ba95 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 20:53:47 +
Subject: [PATCH 1/2] Add mapper field to mapInfoOp.

---
 flang/lib/Lower/OpenMP/Utils.cpp| 3 ++-
 flang/lib/Lower/OpenMP/Utils.h  | 3 ++-
 flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp  | 5 -
 flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp | 1 +
 mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td   | 2 ++
 mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp| 2 +-
 mlir/test/Dialect/OpenMP/ops.mlir   | 4 ++--
 7 files changed, 14 insertions(+), 6 deletions(-)

diff --git a/flang/lib/Lower/OpenMP/Utils.cpp b/flang/lib/Lower/OpenMP/Utils.cpp
index 9971dc8e0b0014..af3a3df825fb88 100644
--- a/flang/lib/Lower/OpenMP/Utils.cpp
+++ b/flang/lib/Lower/OpenMP/Utils.cpp
@@ -125,7 +125,7 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
 llvm::ArrayRef members,
 mlir::ArrayAttr membersIndex, uint64_t mapType,
 mlir::omp::VariableCaptureKind mapCaptureType, mlir::Type 
retTy,
-bool partialMap) {
+bool partialMap, mlir::FlatSymbolRefAttr mapperId) {
   if (auto boxTy = llvm::dyn_cast(baseAddr.getType())) {
 baseAddr = builder.create(loc, baseAddr);
 retTy = baseAddr.getType();
@@ -144,6 +144,7 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
   mlir::omp::MapInfoOp op = builder.create(
   loc, retTy, baseAddr, varType, varPtrPtr, members, membersIndex, bounds,
   builder.getIntegerAttr(builder.getIntegerType(64, false), mapType),
+  mapperId,
   builder.getAttr(mapCaptureType),
   builder.getStringAttr(name), builder.getBoolAttr(partialMap));
   return op;
diff --git a/flang/lib/Lower/OpenMP/Utils.h b/flang/lib/Lower/OpenMP/Utils.h
index f2e378443e5f29..3943eb633b04e3 100644
--- a/flang/lib/Lower/OpenMP/Utils.h
+++ b/flang/lib/Lower/OpenMP/Utils.h
@@ -116,7 +116,8 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
 llvm::ArrayRef members,
 mlir::ArrayAttr membersIndex, uint64_t mapType,
 mlir::omp::VariableCaptureKind mapCaptureType, mlir::Type 
retTy,
-bool partialMap = false);
+bool partialMap = false,
+mlir::FlatSymbolRefAttr mapperId = mlir::FlatSymbolRefAttr());
 
 void insertChildMapInfoIntoParent(
 Fortran::lower::AbstractConverter &converter,
diff --git a/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp 
b/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
index b08ccf3b88eb46..247ea6383cacda 100644
--- a/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
+++ b/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
@@ -171,6 +171,7 @@ class MapInfoFinalizationPass
 baseAddrAddr, /*members=*/mlir::SmallVector{},
 /*membersIndex=*/mlir::ArrayAttr{}, bounds,
 builder.getIntegerAttr(builder.getIntegerType(64, false), mapType),
+/*mapperId*/ mlir::FlatSymbolRefAttr(),
 builder.getAttr(
 mlir::omp::VariableCaptureKind::ByRef),
 /*name=*/builder.getStringAttr(""),
@@ -316,7 +317,8 @@ class MapInfoFinalizationPass
 builder.getIntegerAttr(
 builder.getIntegerType(64, false),
 getDescriptorMapType(op.getMapType().value_or(0), target)),
-op.getMapCaptureTypeAttr(), op.getNameAttr(),
+/*mapperId*/ mlir::FlatSymbolRefAttr(), op.getMapCaptureTypeAttr(),
+op.getNameAttr(),
 /*partial_map=*/builder.getBoolAttr(false));
 op.replaceAllUsesWith(newDescParentMapOp.getResult());
 op->erase();
@@ -611,6 +613,7 @@ class MapInfoFinalizationPass
   /*members=*/mlir::ValueRange{},
   /*members_index=*/mlir::ArrayAttr{},
   /*bounds=*/bounds, op.getMapTypeAttr(),
+  /*mapperId*/ mlir::FlatSymbolRefAttr(),
   builder.getAttr(
   mlir::omp::VariableCaptureKind::ByRef),
   builder.getStringAttr(op.getNameAttr().strref() + "." +
diff --git a/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp 
b/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
index c990bebcabde42..9f3b4dcdd898f4 100644
--- a/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
+++ b/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
@@ -89,6 +89,7 @@ class MapsForPrivatizedSymbolsPass
 /*bounds=*/ValueRange{},
 builder.getIntegerAttr(builder.getIntegerType(64, /*isSigned=*/false),
mapTypeTo),
+/*mapperId*/ mlir::FlatSymbolRefAttr(),
 builder.getAttr(
 omp::VariableCaptureKind::ByRef),
 StringAttr(), builder.getBoolAttr(false));
diff --gi

[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP custom mappers in map clause (PR #121001)

2025-01-28 Thread Akash Banerjee via llvm-branch-commits


@@ -970,6 +972,20 @@ void ClauseProcessor::processMapObjects(
   }
 }
 
+if (!mapperIdName.empty()) {
+  if (mapperIdName == "default") {
+auto &typeSpec = object.sym()->owner().IsDerivedType()
+ ? *object.sym()->owner().derivedTypeSpec()
+ : object.sym()->GetType()->derivedTypeSpec();

TIFitis wrote:

Yes, the `object.sym()` type is expected to be derivedType here. There is a 
check inside `derivedTypeSpec()` just in case.

https://github.com/llvm/llvm-project/pull/121001
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP custom mappers in map clause (PR #121001)

2025-01-28 Thread Akash Banerjee via llvm-branch-commits


@@ -1057,13 +1075,17 @@ bool ClauseProcessor::processMap(
"Support for iterator modifiers is not implemented yet");
 }
 if (mappers) {
-  TODO(currentLocation,
-   "Support for mapper modifiers is not implemented yet");
+  assert(mappers->size() == 1 && "more than one mapper");
+  mapperIdName = mappers->front().v.id().symbol->name().ToString();
+  if (mapperIdName != "default")

TIFitis wrote:

We would then have to pass the `mappers` element from the parser struct to the 
`processMapObjects` function. I guess it's better to just pass the string.

Also, in a future patch when adding support for implicit default mapping, I 
expect to consolidate all the process here, and remove the code inside 
`processMapObjects`.

https://github.com/llvm/llvm-project/pull/121001
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-01-28 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/124746

>From 6bba19e7df6da05f77e5e1ac5fb06c4fb2a1bda0 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Tue, 28 Jan 2025 13:38:13 +
Subject: [PATCH 1/2] [MLIR][OpenMP] Add LLVM translation support for OpenMP
 UserDefinedMappers

This patch adds OpenMPToLLVMIRTranslation support for the OpenMP Declare Mapper 
directive.

Since both MLIR and Clang now support custom mappers, I've made the relative 
params required instead of optional as well.

Depends on #121005
---
 clang/lib/CodeGen/CGOpenMPRuntime.cpp |  20 +-
 .../llvm/Frontend/OpenMP/OMPIRBuilder.h   |  49 +++--
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp |  78 +++
 .../Frontend/OpenMPIRBuilderTest.cpp  |  56 +++--
 .../OpenMP/OpenMPToLLVMIRTranslation.cpp  | 198 ++
 mlir/test/Target/LLVMIR/omptarget-llvm.mlir   | 117 +++
 .../fortran/target-custom-mapper.f90  |  46 
 7 files changed, 443 insertions(+), 121 deletions(-)
 create mode 100644 offload/test/offloading/fortran/target-custom-mapper.f90

diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index 30c3834de139c3..0a13581dcb1700 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -32,10 +32,12 @@
 #include "llvm/Bitcode/BitcodeReader.h"
 #include "llvm/IR/Constants.h"
 #include "llvm/IR/DerivedTypes.h"
+#include "llvm/IR/Function.h"
 #include "llvm/IR/GlobalValue.h"
 #include "llvm/IR/InstrTypes.h"
 #include "llvm/IR/Value.h"
 #include "llvm/Support/AtomicOrdering.h"
+#include "llvm/Support/Error.h"
 #include "llvm/Support/raw_ostream.h"
 #include 
 #include 
@@ -,8 +8890,8 @@ static void emitOffloadingArraysAndArgs(
 return MFunc;
   };
   OMPBuilder.emitOffloadingArraysAndArgs(
-  AllocaIP, CodeGenIP, Info, Info.RTArgs, CombinedInfo, IsNonContiguous,
-  ForEndCall, DeviceAddrCB, CustomMapperCB);
+  AllocaIP, CodeGenIP, Info, Info.RTArgs, CombinedInfo, CustomMapperCB,
+  IsNonContiguous, ForEndCall, DeviceAddrCB);
 }
 
 /// Check for inner distribute directive.
@@ -9098,9 +9100,10 @@ void CGOpenMPRuntime::emitUserDefinedMapper(const 
OMPDeclareMapperDecl *D,
   CGM.getCXXABI().getMangleContext().mangleCanonicalTypeName(Ty, Out);
   std::string Name = getName({"omp_mapper", TyStr, D->getName()});
 
-  auto *NewFn = OMPBuilder.emitUserDefinedMapper(PrivatizeAndGenMapInfoCB,
- ElemTy, Name, CustomMapperCB);
-  UDMMap.try_emplace(D, NewFn);
+  llvm::Expected NewFn = OMPBuilder.emitUserDefinedMapper(
+  PrivatizeAndGenMapInfoCB, ElemTy, Name, CustomMapperCB);
+  assert(NewFn && "Unexpected error in emitUserDefinedMapper");
+  UDMMap.try_emplace(D, *NewFn);
   if (CGF)
 FunctionUDMMap[CGF->CurFn].push_back(D);
 }
@@ -10092,9 +10095,10 @@ void CGOpenMPRuntime::emitTargetDataCalls(
   CGF.Builder.GetInsertPoint());
   llvm::OpenMPIRBuilder::LocationDescription OmpLoc(CodeGenIP);
   llvm::OpenMPIRBuilder::InsertPointOrErrorTy AfterIP =
-  OMPBuilder.createTargetData(
-  OmpLoc, AllocaIP, CodeGenIP, DeviceID, IfCondVal, Info, GenMapInfoCB,
-  /*MapperFunc=*/nullptr, BodyCB, DeviceAddrCB, CustomMapperCB, RTLoc);
+  OMPBuilder.createTargetData(OmpLoc, AllocaIP, CodeGenIP, DeviceID,
+  IfCondVal, Info, GenMapInfoCB, 
CustomMapperCB,
+  /*MapperFunc=*/nullptr, BodyCB, DeviceAddrCB,
+  RTLoc);
   assert(AfterIP && "unexpected error creating target data");
   CGF.Builder.restoreIP(*AfterIP);
 }
diff --git a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h 
b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
index 4ce47b1c05d9b0..4e80bff6db4553 100644
--- a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
+++ b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
@@ -22,6 +22,7 @@
 #include "llvm/IR/IRBuilder.h"
 #include "llvm/IR/Module.h"
 #include "llvm/Support/Allocator.h"
+#include "llvm/Support/Error.h"
 #include "llvm/TargetParser/Triple.h"
 #include 
 #include 
@@ -2355,6 +2356,7 @@ class OpenMPIRBuilder {
CurInfo.NonContigInfo.Strides.end());
 }
   };
+  using MapInfosOrErrorTy = Expected;
 
   /// Callback function type for functions emitting the host fallback code that
   /// is executed when the kernel launch fails. It takes an insertion point as
@@ -2431,9 +2433,9 @@ class OpenMPIRBuilder {
   /// including base pointers, pointers, sizes, map types, user-defined 
mappers.
   void emitOffloadingArrays(
   InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy 
&CombinedInfo,
-  TargetDataInfo &Info, bool IsNonContiguous = false,
-  function_ref DeviceAddrCB = nullptr,
-  function_ref CustomMapperCB = nullptr);
+  TargetDataInfo &Info, function_ref CustomMapperCB,
+  bool IsNonContiguo

[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add conversion support from FIR to LLVM Dialect for OMP DeclareMapper (PR #121005)

2025-01-28 Thread Akash Banerjee via llvm-branch-commits


@@ -186,6 +186,32 @@ struct MapInfoOpConversion : public 
ConvertOpToLLVMPattern {
   }
 };
 
+struct DeclMapperOpConversion

TIFitis wrote:

Hi, sorry for the late reply, I've just returned from my vacation.

Can we use a specialised `forwardOpAttrs` to convert the type for the `VarType` 
`TypeAttr`?

Looking at the code, `MapInfoOp` uses a similar OpConversion for converting the 
type for it's `TypeAttr`.

https://github.com/llvm/llvm-project/pull/121005
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP custom mappers in map clause (PR #121001)

2025-01-28 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis edited 
https://github.com/llvm/llvm-project/pull/121001
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP custom mappers in map clause (PR #121001)

2025-01-28 Thread Akash Banerjee via llvm-branch-commits


@@ -0,0 +1,23 @@
+! RUN: %flang_fc1 -emit-hlfir -fopenmp -fopenmp-version=50 %s -o - | FileCheck 
%s
+program p
+   integer, parameter :: n = 256
+   type t1
+  integer :: x(256)
+   end type t1
+
+   !$omp declare mapper(xx : t1 :: nn) map(to: nn, nn%x)
+   !$omp declare mapper(t1 :: nn) map(from: nn)
+
+   !CHECK-LABEL: omp.declare_mapper @_QQFt1.default : 
!fir.type<_QFTt1{x:!fir.array<256xi32>}>
+   !CHECK-LABEL: omp.declare_mapper @_QQFxx : 
!fir.type<_QFTt1{x:!fir.array<256xi32>}>
+
+   type(t1) :: a, b
+   !CHECK: %[[MAP_A:.*]] = omp.map.info var_ptr(%{{.*}} : {{.*}}, {{.*}}) 
mapper(@_QQFxx) map_clauses(tofrom) capture(ByRef) -> {{.*}} {name = "a"}
+   !CHECK: %[[MAP_B:.*]] = omp.map.info var_ptr(%{{.*}} : {{.*}}, {{.*}}) 
mapper(@_QQFt1.default) map_clauses(tofrom) capture(ByRef) -> {{.*}} {name = 
"b"}
+   !CHECK: omp.target map_entries(%[[MAP_A]] -> %{{.*}}, %[[MAP_B]] -> 
%{{.*}}, %{{.*}} -> %{{.*}}, %{{.*}} -> %{{.*}} : {{.*}}, {{.*}}, {{.*}}, 
{{.*}}) {
+   !$omp target map(mapper(xx) : a) map(mapper(default) : b)

TIFitis wrote:

Updated :)

https://github.com/llvm/llvm-project/pull/121001
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP custom mappers in map clause (PR #121001)

2025-01-28 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/121001

>From 30611f81421028ccc8fceed006e06f8afc6848b9 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 19:05:30 +
Subject: [PATCH 1/3] Add mapper field to mapInfoOp.

---
 flang/test/Lower/OpenMP/map-mapper.f90 | 15 +++
 1 file changed, 15 insertions(+)
 create mode 100644 flang/test/Lower/OpenMP/map-mapper.f90

diff --git a/flang/test/Lower/OpenMP/map-mapper.f90 
b/flang/test/Lower/OpenMP/map-mapper.f90
new file mode 100644
index 00..e7fded3034406e
--- /dev/null
+++ b/flang/test/Lower/OpenMP/map-mapper.f90
@@ -0,0 +1,15 @@
+! RUN: %flang_fc1 -emit-hlfir -fopenmp -fopenmp-version=50 %s -o - | FileCheck 
%s
+program p
+   integer, parameter :: n = 256
+   real(8) :: a(256)
+   type t1
+  integer :: x
+   end type t1
+   !$omp declare mapper(xx : t1 :: nn) map(nn, nn%x)
+   !$omp target map(mapper(xx), from:a)
+!CHECK: not yet implemented: Support for mapper modifiers is not implemented 
yet
+   do i = 1, n
+  a(i) = 4.2
+   end do
+   !$omp end target
+end program p

>From ea048f78cdec2ea749562f17ae6d3614c2ef1f46 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 21:13:42 +
Subject: [PATCH 2/3] Add flang lowering changes for mapper field in map
 clause.

---
 flang/lib/Lower/OpenMP/ClauseProcessor.cpp  | 32 +
 flang/lib/Lower/OpenMP/ClauseProcessor.h|  3 +-
 flang/test/Lower/OpenMP/Todo/map-mapper.f90 | 16 ---
 flang/test/Lower/OpenMP/map-mapper.f90  | 20 +
 4 files changed, 43 insertions(+), 28 deletions(-)
 delete mode 100644 flang/test/Lower/OpenMP/Todo/map-mapper.f90

diff --git a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp 
b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
index 3c9831120351ee..0bc9f4919330e4 100644
--- a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
+++ b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
@@ -936,8 +936,10 @@ void ClauseProcessor::processMapObjects(
 llvm::omp::OpenMPOffloadMappingFlags mapTypeBits,
 std::map &parentMemberIndices,
 llvm::SmallVectorImpl &mapVars,
-llvm::SmallVectorImpl &mapSyms) const {
+llvm::SmallVectorImpl &mapSyms,
+std::string mapperIdName) const {
   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  mlir::FlatSymbolRefAttr mapperId;
 
   for (const omp::Object &object : objects) {
 llvm::SmallVector bounds;
@@ -970,6 +972,20 @@ void ClauseProcessor::processMapObjects(
   }
 }
 
+if (!mapperIdName.empty()) {
+  if (mapperIdName == "default") {
+auto &typeSpec = object.sym()->owner().IsDerivedType()
+ ? *object.sym()->owner().derivedTypeSpec()
+ : object.sym()->GetType()->derivedTypeSpec();
+mapperIdName = typeSpec.name().ToString() + ".default";
+mapperIdName = converter.mangleName(mapperIdName, 
*typeSpec.GetScope());
+  }
+  assert(converter.getMLIRSymbolTable()->lookup(mapperIdName) &&
+ "mapper not found");
+  mapperId = mlir::FlatSymbolRefAttr::get(&converter.getMLIRContext(),
+  mapperIdName);
+  mapperIdName.clear();
+}
 // Explicit map captures are captured ByRef by default,
 // optimisation passes may alter this to ByCopy or other capture
 // types to optimise
@@ -983,7 +999,8 @@ void ClauseProcessor::processMapObjects(
 static_cast<
 std::underlying_type_t>(
 mapTypeBits),
-mlir::omp::VariableCaptureKind::ByRef, baseOp.getType());
+mlir::omp::VariableCaptureKind::ByRef, baseOp.getType(), false,
+mapperId);
 
 if (parentObj.has_value()) {
   parentMemberIndices[parentObj.value()].addChildIndexAndMapToParent(
@@ -1014,6 +1031,7 @@ bool ClauseProcessor::processMap(
 const auto &[mapType, typeMods, mappers, iterator, objects] = clause.t;
 llvm::omp::OpenMPOffloadMappingFlags mapTypeBits =
 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE;
+std::string mapperIdName;
 // If the map type is specified, then process it else Tofrom is the
 // default.
 Map::MapType type = mapType.value_or(Map::MapType::Tofrom);
@@ -1057,13 +1075,17 @@ bool ClauseProcessor::processMap(
"Support for iterator modifiers is not implemented yet");
 }
 if (mappers) {
-  TODO(currentLocation,
-   "Support for mapper modifiers is not implemented yet");
+  assert(mappers->size() == 1 && "more than one mapper");
+  mapperIdName = mappers->front().v.id().symbol->name().ToString();
+  if (mapperIdName != "default")
+mapperIdName = converter.mangleName(
+mapperIdName, mappers->front().v.id().symbol->owner());
 }
 
 processMapObjects(stmtCtx, clauseLocation,
   std::get(clause.t), mapTypeBits,
-  parentMemberIndices, result.mapVars, *ptrMapSyms);
+ 

[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add conversion support from FIR to LLVM Dialect for OMP DeclareMapper (PR #121005)

2025-01-28 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis edited 
https://github.com/llvm/llvm-project/pull/121005
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-01-28 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis edited 
https://github.com/llvm/llvm-project/pull/124746
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add OMP Mapper field to MapInfoOp (PR #120994)

2025-01-28 Thread Akash Banerjee via llvm-branch-commits


@@ -1000,6 +1000,7 @@ def MapInfoOp : OpenMP_Op<"map.info", 
[AttrSizedOperandSegments]> {
OptionalAttr:$members_index,
Variadic:$bounds, /* rank-0 to 
rank-{n-1} */
OptionalAttr:$map_type,
+   OptionalAttr:$mapper_id,

TIFitis wrote:

Sorry for the delay, I was on vacation.

I've updated the description and also added a verifier check.

https://github.com/llvm/llvm-project/pull/120994
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP Declare Mapper directive (PR #117046)

2025-01-28 Thread Akash Banerjee via llvm-branch-commits

TIFitis wrote:

@kiranchandramohan @skatrak @agozillon Hi everyone! I was on vacation these 
last couple of weeks, apologies for the delay.

I have added PR #124746 with which we have all the implementation in place for 
declare mappers.

It would be great to resume the review process for this PR stack.

Thanks :)

Note: I'll add a couple of patches to support the implicit default mapping 
support for declare mappers.

https://github.com/llvm/llvm-project/pull/117046
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add conversion support from FIR to LLVM Dialect for OMP DeclareMapper (PR #121005)

2025-01-29 Thread Akash Banerjee via llvm-branch-commits


@@ -186,6 +186,32 @@ struct MapInfoOpConversion : public 
ConvertOpToLLVMPattern {
   }
 };
 
+struct DeclMapperOpConversion

TIFitis wrote:

I tried to use the `MultiRegionOpConversion` but it doesn't support Ops with a 
single region, and `RegionOpConversion` doesn't seem to have something like 
`forwardOpAttrs`.

Let me know if I'm missing something, otherwise the current approach seems like 
the only viable option to me :)

https://github.com/llvm/llvm-project/pull/121005
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [mlir] [MLIR][OpenMP] Add OMP Mapper field to MapInfoOp (PR #120994)

2024-12-23 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis created 
https://github.com/llvm/llvm-project/pull/120994

This patch adds the mapper field to the omp.map.info op.

>From 21178b07176869e000f7e027bc5c9593b715b5ad Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 19:05:30 +
Subject: [PATCH] Add mapper field to mapInfoOp.

---
 mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td | 2 ++
 mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp  | 2 +-
 mlir/test/Dialect/OpenMP/ops.mlir | 4 ++--
 3 files changed, 5 insertions(+), 3 deletions(-)

diff --git a/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td 
b/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
index 881f28d42e6312..7cc2c8fa8ce1e1 100644
--- a/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
+++ b/mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td
@@ -1000,6 +1000,7 @@ def MapInfoOp : OpenMP_Op<"map.info", 
[AttrSizedOperandSegments]> {
OptionalAttr:$members_index,
Variadic:$bounds, /* rank-0 to 
rank-{n-1} */
OptionalAttr:$map_type,
+   OptionalAttr:$mapper_id,
OptionalAttr:$map_capture_type,
OptionalAttr:$name,
DefaultValuedAttr:$partial_map);
@@ -1064,6 +1065,7 @@ def MapInfoOp : OpenMP_Op<"map.info", 
[AttrSizedOperandSegments]> {
 `var_ptr` `(` $var_ptr `:` type($var_ptr) `,` $var_type `)`
 oilist(
 `var_ptr_ptr` `(` $var_ptr_ptr `:` type($var_ptr_ptr) `)`
+  | `mapper` `(` $mapper_id `)`
   | `map_clauses` `(` custom($map_type) `)`
   | `capture` `(` custom($map_capture_type) `)`
   | `members` `(` $members `:` custom($members_index) `:` 
type($members) `)`
diff --git a/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp 
b/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
index b15d6ed15244ed..92233654ba1ddc 100644
--- a/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
+++ b/mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp
@@ -1592,7 +1592,7 @@ static LogicalResult verifyMapClause(Operation *op, 
OperandRange mapVars) {
 
 to ? updateToVars.insert(updateVar) : updateFromVars.insert(updateVar);
   }
-} else {
+} else if (!isa(op)) {
   emitError(op->getLoc(), "map argument is not a map entry operation");
 }
   }
diff --git a/mlir/test/Dialect/OpenMP/ops.mlir 
b/mlir/test/Dialect/OpenMP/ops.mlir
index a167c8bd1abbf9..97ef132f6dfa53 100644
--- a/mlir/test/Dialect/OpenMP/ops.mlir
+++ b/mlir/test/Dialect/OpenMP/ops.mlir
@@ -2523,13 +2523,13 @@ func.func @omp_targets_with_map_bounds(%arg0: 
!llvm.ptr, %arg1: !llvm.ptr) -> ()
   // CHECK: %[[C_12:.*]] = llvm.mlir.constant(2 : index) : i64
   // CHECK: %[[C_13:.*]] = llvm.mlir.constant(2 : index) : i64
   // CHECK: %[[BOUNDS1:.*]] = omp.map.bounds   lower_bound(%[[C_11]] : i64) 
upper_bound(%[[C_10]] : i64) stride(%[[C_12]] : i64) start_idx(%[[C_13]] : i64)
-  // CHECK: %[[MAP1:.*]] = omp.map.info var_ptr(%[[ARG1]] : !llvm.ptr, 
!llvm.array<10 x i32>)   map_clauses(exit_release_or_enter_alloc) 
capture(ByCopy) bounds(%[[BOUNDS1]]) -> !llvm.ptr {name = ""}
+  // CHECK: %[[MAP1:.*]] = omp.map.info var_ptr(%[[ARG1]] : !llvm.ptr, 
!llvm.array<10 x i32>)   mapper(@my_mapper) 
map_clauses(exit_release_or_enter_alloc) capture(ByCopy) bounds(%[[BOUNDS1]]) 
-> !llvm.ptr {name = ""}
 %6 = llvm.mlir.constant(9 : index) : i64
 %7 = llvm.mlir.constant(1 : index) : i64
 %8 = llvm.mlir.constant(2 : index) : i64
 %9 = llvm.mlir.constant(2 : index) : i64
 %10 = omp.map.bounds   lower_bound(%7 : i64) upper_bound(%6 : i64) 
stride(%8 : i64) start_idx(%9 : i64)
-%mapv2 = omp.map.info var_ptr(%arg1 : !llvm.ptr, !llvm.array<10 x i32>)   
map_clauses(exit_release_or_enter_alloc) capture(ByCopy) bounds(%10) -> 
!llvm.ptr {name = ""}
+%mapv2 = omp.map.info var_ptr(%arg1 : !llvm.ptr, !llvm.array<10 x i32>)   
mapper(@my_mapper) map_clauses(exit_release_or_enter_alloc) capture(ByCopy) 
bounds(%10) -> !llvm.ptr {name = ""}
 
 // CHECK: omp.target map_entries(%[[MAP0]] -> {{.*}}, %[[MAP1]] -> {{.*}} 
: !llvm.ptr, !llvm.ptr)
 omp.target map_entries(%mapv1 -> %arg2, %mapv2 -> %arg3 : !llvm.ptr, 
!llvm.ptr) {

___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add OMP Mapper field to MapInfoOp (PR #120994)

2024-12-23 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/120994

>From 0b54cafc829119b931d04d1d9ec3e790e50f7b08 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 19:05:30 +
Subject: [PATCH] Add mapper field to mapInfoOp.

---
 flang/lib/Lower/OpenMP/Utils.cpp  |  3 ++-
 flang/lib/Lower/OpenMP/Utils.h|  3 ++-
 .../lib/Optimizer/OpenMP/MapInfoFinalization.cpp  |  5 -
 .../Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp |  1 +
 flang/test/Lower/OpenMP/map-mapper.f90| 15 +++
 mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td |  2 ++
 mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp  |  2 +-
 mlir/test/Dialect/OpenMP/ops.mlir |  4 ++--
 8 files changed, 29 insertions(+), 6 deletions(-)
 create mode 100644 flang/test/Lower/OpenMP/map-mapper.f90

diff --git a/flang/lib/Lower/OpenMP/Utils.cpp b/flang/lib/Lower/OpenMP/Utils.cpp
index 9971dc8e0b0014..af3a3df825fb88 100644
--- a/flang/lib/Lower/OpenMP/Utils.cpp
+++ b/flang/lib/Lower/OpenMP/Utils.cpp
@@ -125,7 +125,7 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
 llvm::ArrayRef members,
 mlir::ArrayAttr membersIndex, uint64_t mapType,
 mlir::omp::VariableCaptureKind mapCaptureType, mlir::Type 
retTy,
-bool partialMap) {
+bool partialMap, mlir::FlatSymbolRefAttr mapperId) {
   if (auto boxTy = llvm::dyn_cast(baseAddr.getType())) {
 baseAddr = builder.create(loc, baseAddr);
 retTy = baseAddr.getType();
@@ -144,6 +144,7 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
   mlir::omp::MapInfoOp op = builder.create(
   loc, retTy, baseAddr, varType, varPtrPtr, members, membersIndex, bounds,
   builder.getIntegerAttr(builder.getIntegerType(64, false), mapType),
+  mapperId,
   builder.getAttr(mapCaptureType),
   builder.getStringAttr(name), builder.getBoolAttr(partialMap));
   return op;
diff --git a/flang/lib/Lower/OpenMP/Utils.h b/flang/lib/Lower/OpenMP/Utils.h
index f2e378443e5f29..3943eb633b04e3 100644
--- a/flang/lib/Lower/OpenMP/Utils.h
+++ b/flang/lib/Lower/OpenMP/Utils.h
@@ -116,7 +116,8 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
 llvm::ArrayRef members,
 mlir::ArrayAttr membersIndex, uint64_t mapType,
 mlir::omp::VariableCaptureKind mapCaptureType, mlir::Type 
retTy,
-bool partialMap = false);
+bool partialMap = false,
+mlir::FlatSymbolRefAttr mapperId = mlir::FlatSymbolRefAttr());
 
 void insertChildMapInfoIntoParent(
 Fortran::lower::AbstractConverter &converter,
diff --git a/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp 
b/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
index b08ccf3b88eb46..247ea6383cacda 100644
--- a/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
+++ b/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
@@ -171,6 +171,7 @@ class MapInfoFinalizationPass
 baseAddrAddr, /*members=*/mlir::SmallVector{},
 /*membersIndex=*/mlir::ArrayAttr{}, bounds,
 builder.getIntegerAttr(builder.getIntegerType(64, false), mapType),
+/*mapperId*/ mlir::FlatSymbolRefAttr(),
 builder.getAttr(
 mlir::omp::VariableCaptureKind::ByRef),
 /*name=*/builder.getStringAttr(""),
@@ -316,7 +317,8 @@ class MapInfoFinalizationPass
 builder.getIntegerAttr(
 builder.getIntegerType(64, false),
 getDescriptorMapType(op.getMapType().value_or(0), target)),
-op.getMapCaptureTypeAttr(), op.getNameAttr(),
+/*mapperId*/ mlir::FlatSymbolRefAttr(), op.getMapCaptureTypeAttr(),
+op.getNameAttr(),
 /*partial_map=*/builder.getBoolAttr(false));
 op.replaceAllUsesWith(newDescParentMapOp.getResult());
 op->erase();
@@ -611,6 +613,7 @@ class MapInfoFinalizationPass
   /*members=*/mlir::ValueRange{},
   /*members_index=*/mlir::ArrayAttr{},
   /*bounds=*/bounds, op.getMapTypeAttr(),
+  /*mapperId*/ mlir::FlatSymbolRefAttr(),
   builder.getAttr(
   mlir::omp::VariableCaptureKind::ByRef),
   builder.getStringAttr(op.getNameAttr().strref() + "." +
diff --git a/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp 
b/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
index c990bebcabde42..9f3b4dcdd898f4 100644
--- a/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
+++ b/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
@@ -89,6 +89,7 @@ class MapsForPrivatizedSymbolsPass
 /*bounds=*/ValueRange{},
 builder.getIntegerAttr(builder.getIntegerType(64, /*isSigned=*/false),
mapTypeTo),
+/*mapperId*/ mlir::FlatSymbolRefAttr(),
 builder.getAttr(
 omp

[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add OMP Mapper field to MapInfoOp (PR #120994)

2024-12-23 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/120994

>From 002d7153f4029c02722b6a4f45bbde8fad83ba95 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 20:53:47 +
Subject: [PATCH] Add mapper field to mapInfoOp.

---
 flang/lib/Lower/OpenMP/Utils.cpp| 3 ++-
 flang/lib/Lower/OpenMP/Utils.h  | 3 ++-
 flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp  | 5 -
 flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp | 1 +
 mlir/include/mlir/Dialect/OpenMP/OpenMPOps.td   | 2 ++
 mlir/lib/Dialect/OpenMP/IR/OpenMPDialect.cpp| 2 +-
 mlir/test/Dialect/OpenMP/ops.mlir   | 4 ++--
 7 files changed, 14 insertions(+), 6 deletions(-)

diff --git a/flang/lib/Lower/OpenMP/Utils.cpp b/flang/lib/Lower/OpenMP/Utils.cpp
index 9971dc8e0b0014..af3a3df825fb88 100644
--- a/flang/lib/Lower/OpenMP/Utils.cpp
+++ b/flang/lib/Lower/OpenMP/Utils.cpp
@@ -125,7 +125,7 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
 llvm::ArrayRef members,
 mlir::ArrayAttr membersIndex, uint64_t mapType,
 mlir::omp::VariableCaptureKind mapCaptureType, mlir::Type 
retTy,
-bool partialMap) {
+bool partialMap, mlir::FlatSymbolRefAttr mapperId) {
   if (auto boxTy = llvm::dyn_cast(baseAddr.getType())) {
 baseAddr = builder.create(loc, baseAddr);
 retTy = baseAddr.getType();
@@ -144,6 +144,7 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
   mlir::omp::MapInfoOp op = builder.create(
   loc, retTy, baseAddr, varType, varPtrPtr, members, membersIndex, bounds,
   builder.getIntegerAttr(builder.getIntegerType(64, false), mapType),
+  mapperId,
   builder.getAttr(mapCaptureType),
   builder.getStringAttr(name), builder.getBoolAttr(partialMap));
   return op;
diff --git a/flang/lib/Lower/OpenMP/Utils.h b/flang/lib/Lower/OpenMP/Utils.h
index f2e378443e5f29..3943eb633b04e3 100644
--- a/flang/lib/Lower/OpenMP/Utils.h
+++ b/flang/lib/Lower/OpenMP/Utils.h
@@ -116,7 +116,8 @@ createMapInfoOp(fir::FirOpBuilder &builder, mlir::Location 
loc,
 llvm::ArrayRef members,
 mlir::ArrayAttr membersIndex, uint64_t mapType,
 mlir::omp::VariableCaptureKind mapCaptureType, mlir::Type 
retTy,
-bool partialMap = false);
+bool partialMap = false,
+mlir::FlatSymbolRefAttr mapperId = mlir::FlatSymbolRefAttr());
 
 void insertChildMapInfoIntoParent(
 Fortran::lower::AbstractConverter &converter,
diff --git a/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp 
b/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
index b08ccf3b88eb46..247ea6383cacda 100644
--- a/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
+++ b/flang/lib/Optimizer/OpenMP/MapInfoFinalization.cpp
@@ -171,6 +171,7 @@ class MapInfoFinalizationPass
 baseAddrAddr, /*members=*/mlir::SmallVector{},
 /*membersIndex=*/mlir::ArrayAttr{}, bounds,
 builder.getIntegerAttr(builder.getIntegerType(64, false), mapType),
+/*mapperId*/ mlir::FlatSymbolRefAttr(),
 builder.getAttr(
 mlir::omp::VariableCaptureKind::ByRef),
 /*name=*/builder.getStringAttr(""),
@@ -316,7 +317,8 @@ class MapInfoFinalizationPass
 builder.getIntegerAttr(
 builder.getIntegerType(64, false),
 getDescriptorMapType(op.getMapType().value_or(0), target)),
-op.getMapCaptureTypeAttr(), op.getNameAttr(),
+/*mapperId*/ mlir::FlatSymbolRefAttr(), op.getMapCaptureTypeAttr(),
+op.getNameAttr(),
 /*partial_map=*/builder.getBoolAttr(false));
 op.replaceAllUsesWith(newDescParentMapOp.getResult());
 op->erase();
@@ -611,6 +613,7 @@ class MapInfoFinalizationPass
   /*members=*/mlir::ValueRange{},
   /*members_index=*/mlir::ArrayAttr{},
   /*bounds=*/bounds, op.getMapTypeAttr(),
+  /*mapperId*/ mlir::FlatSymbolRefAttr(),
   builder.getAttr(
   mlir::omp::VariableCaptureKind::ByRef),
   builder.getStringAttr(op.getNameAttr().strref() + "." +
diff --git a/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp 
b/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
index c990bebcabde42..9f3b4dcdd898f4 100644
--- a/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
+++ b/flang/lib/Optimizer/OpenMP/MapsForPrivatizedSymbols.cpp
@@ -89,6 +89,7 @@ class MapsForPrivatizedSymbolsPass
 /*bounds=*/ValueRange{},
 builder.getIntegerAttr(builder.getIntegerType(64, /*isSigned=*/false),
mapTypeTo),
+/*mapperId*/ mlir::FlatSymbolRefAttr(),
 builder.getAttr(
 omp::VariableCaptureKind::ByRef),
 StringAttr(), builder.getBoolAttr(false));
diff --git a/

[llvm-branch-commits] [flang] [MLIR][OpenMP] Add Lowering support for OpenMP custom mappers in map clause (PR #121001)

2024-12-23 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis created 
https://github.com/llvm/llvm-project/pull/121001

Add Lowering support for OpenMP mapper field in mapInfoOp.

Depends on #120994.

>From 30611f81421028ccc8fceed006e06f8afc6848b9 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 19:05:30 +
Subject: [PATCH 1/2] Add mapper field to mapInfoOp.

---
 flang/test/Lower/OpenMP/map-mapper.f90 | 15 +++
 1 file changed, 15 insertions(+)
 create mode 100644 flang/test/Lower/OpenMP/map-mapper.f90

diff --git a/flang/test/Lower/OpenMP/map-mapper.f90 
b/flang/test/Lower/OpenMP/map-mapper.f90
new file mode 100644
index 00..e7fded3034406e
--- /dev/null
+++ b/flang/test/Lower/OpenMP/map-mapper.f90
@@ -0,0 +1,15 @@
+! RUN: %flang_fc1 -emit-hlfir -fopenmp -fopenmp-version=50 %s -o - | FileCheck 
%s
+program p
+   integer, parameter :: n = 256
+   real(8) :: a(256)
+   type t1
+  integer :: x
+   end type t1
+   !$omp declare mapper(xx : t1 :: nn) map(nn, nn%x)
+   !$omp target map(mapper(xx), from:a)
+!CHECK: not yet implemented: Support for mapper modifiers is not implemented 
yet
+   do i = 1, n
+  a(i) = 4.2
+   end do
+   !$omp end target
+end program p

>From ea048f78cdec2ea749562f17ae6d3614c2ef1f46 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 21:13:42 +
Subject: [PATCH 2/2] Add flang lowering changes for mapper field in map
 clause.

---
 flang/lib/Lower/OpenMP/ClauseProcessor.cpp  | 32 +
 flang/lib/Lower/OpenMP/ClauseProcessor.h|  3 +-
 flang/test/Lower/OpenMP/Todo/map-mapper.f90 | 16 ---
 flang/test/Lower/OpenMP/map-mapper.f90  | 20 +
 4 files changed, 43 insertions(+), 28 deletions(-)
 delete mode 100644 flang/test/Lower/OpenMP/Todo/map-mapper.f90

diff --git a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp 
b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
index 3c9831120351ee..0bc9f4919330e4 100644
--- a/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
+++ b/flang/lib/Lower/OpenMP/ClauseProcessor.cpp
@@ -936,8 +936,10 @@ void ClauseProcessor::processMapObjects(
 llvm::omp::OpenMPOffloadMappingFlags mapTypeBits,
 std::map &parentMemberIndices,
 llvm::SmallVectorImpl &mapVars,
-llvm::SmallVectorImpl &mapSyms) const {
+llvm::SmallVectorImpl &mapSyms,
+std::string mapperIdName) const {
   fir::FirOpBuilder &firOpBuilder = converter.getFirOpBuilder();
+  mlir::FlatSymbolRefAttr mapperId;
 
   for (const omp::Object &object : objects) {
 llvm::SmallVector bounds;
@@ -970,6 +972,20 @@ void ClauseProcessor::processMapObjects(
   }
 }
 
+if (!mapperIdName.empty()) {
+  if (mapperIdName == "default") {
+auto &typeSpec = object.sym()->owner().IsDerivedType()
+ ? *object.sym()->owner().derivedTypeSpec()
+ : object.sym()->GetType()->derivedTypeSpec();
+mapperIdName = typeSpec.name().ToString() + ".default";
+mapperIdName = converter.mangleName(mapperIdName, 
*typeSpec.GetScope());
+  }
+  assert(converter.getMLIRSymbolTable()->lookup(mapperIdName) &&
+ "mapper not found");
+  mapperId = mlir::FlatSymbolRefAttr::get(&converter.getMLIRContext(),
+  mapperIdName);
+  mapperIdName.clear();
+}
 // Explicit map captures are captured ByRef by default,
 // optimisation passes may alter this to ByCopy or other capture
 // types to optimise
@@ -983,7 +999,8 @@ void ClauseProcessor::processMapObjects(
 static_cast<
 std::underlying_type_t>(
 mapTypeBits),
-mlir::omp::VariableCaptureKind::ByRef, baseOp.getType());
+mlir::omp::VariableCaptureKind::ByRef, baseOp.getType(), false,
+mapperId);
 
 if (parentObj.has_value()) {
   parentMemberIndices[parentObj.value()].addChildIndexAndMapToParent(
@@ -1014,6 +1031,7 @@ bool ClauseProcessor::processMap(
 const auto &[mapType, typeMods, mappers, iterator, objects] = clause.t;
 llvm::omp::OpenMPOffloadMappingFlags mapTypeBits =
 llvm::omp::OpenMPOffloadMappingFlags::OMP_MAP_NONE;
+std::string mapperIdName;
 // If the map type is specified, then process it else Tofrom is the
 // default.
 Map::MapType type = mapType.value_or(Map::MapType::Tofrom);
@@ -1057,13 +1075,17 @@ bool ClauseProcessor::processMap(
"Support for iterator modifiers is not implemented yet");
 }
 if (mappers) {
-  TODO(currentLocation,
-   "Support for mapper modifiers is not implemented yet");
+  assert(mappers->size() == 1 && "more than one mapper");
+  mapperIdName = mappers->front().v.id().symbol->name().ToString();
+  if (mapperIdName != "default")
+mapperIdName = converter.mangleName(
+mapperIdName, mappers->front().v.id().symbol->owner());
 }
 
 processMapObjects(stmtCtx, clauseLocation,
   std::get(clause.t), mapTypeBits,
-  

[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add OMP Mapper field to MapInfoOp (PR #120994)

2024-12-23 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis edited 
https://github.com/llvm/llvm-project/pull/120994
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [flang] [mlir] [MLIR][OpenMP] Add conversion support from FIR to LLVM Dialect for OMP DeclareMapper (PR #121005)

2024-12-23 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis created 
https://github.com/llvm/llvm-project/pull/121005

Add conversion support from FIR to LLVM Dialect for OMP DeclareMapper.

>From 8a90d208ace9b8fe34f427f6268968e8b4b08976 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Mon, 23 Dec 2024 21:50:03 +
Subject: [PATCH] Add OpenMP to LLVM dialect conversion support for
 DeclareMapperOp.

---
 .../Fir/convert-to-llvm-openmp-and-fir.fir| 27 --
 .../Conversion/OpenMPToLLVM/OpenMPToLLVM.cpp  | 50 +++
 .../OpenMPToLLVM/convert-to-llvmir.mlir   | 13 +
 3 files changed, 75 insertions(+), 15 deletions(-)

diff --git a/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir 
b/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
index 8e4e1fe824d9f5..82f2aea3ad983c 100644
--- a/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
+++ b/flang/test/Fir/convert-to-llvm-openmp-and-fir.fir
@@ -936,9 +936,9 @@ func.func @omp_map_info_descriptor_type_conversion(%arg0 : 
!fir.ref>, i32) 
map_clauses(tofrom) capture(ByRef) -> !fir.llvm_ptr> {name = ""}
   // CHECK: %[[DESC_MAP:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<(ptr, i64, i32, i8, i8, i8, i8)>) map_clauses(always, delete) 
capture(ByRef) members(%[[MEMBER_MAP]] : [0] : !llvm.ptr) -> !llvm.ptr {name = 
""}
   %2 = omp.map.info var_ptr(%arg0 : !fir.ref>>, 
!fir.box>) map_clauses(always, delete) capture(ByRef) members(%1 
: [0] : !fir.llvm_ptr>) -> !fir.ref>> 
{name = ""}
-  // CHECK: omp.target_exit_data map_entries(%[[DESC_MAP]] : !llvm.ptr) 
+  // CHECK: omp.target_exit_data map_entries(%[[DESC_MAP]] : !llvm.ptr)
   omp.target_exit_data   map_entries(%2 : !fir.ref>>)
-  return 
+  return
 }
 
 // -
@@ -956,8 +956,8 @@ func.func 
@omp_map_info_derived_type_explicit_member_conversion(%arg0 : !fir.ref
   %3 = fir.field_index real, 
!fir.type<_QFderived_type{real:f32,array:!fir.array<10xi32>,int:i32}>
   %4 = fir.coordinate_of %arg0, %3 : 
(!fir.ref,int:i32}>>,
 !fir.field) -> !fir.ref
   // CHECK: %[[MAP_MEMBER_2:.*]] = omp.map.info var_ptr(%[[GEP_2]] : 
!llvm.ptr, f32) map_clauses(tofrom) capture(ByRef) -> !llvm.ptr {name = 
"dtype%real"}
-  %5 = omp.map.info var_ptr(%4 : !fir.ref, f32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "dtype%real"}
-  // CHECK: %[[MAP_PARENT:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<"_QFderived_type", (f32, array<10 x i32>, i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[MAP_MEMBER_1]], %[[MAP_MEMBER_2]] 
: [2], [0] : !llvm.ptr, !llvm.ptr) -> !llvm.ptr {name = "dtype", partial_map = 
true} 
+  %5 = omp.map.info var_ptr(%4 : !fir.ref, f32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "dtype%real"}
+  // CHECK: %[[MAP_PARENT:.*]] = omp.map.info var_ptr(%[[ARG_0]] : !llvm.ptr, 
!llvm.struct<"_QFderived_type", (f32, array<10 x i32>, i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[MAP_MEMBER_1]], %[[MAP_MEMBER_2]] 
: [2], [0] : !llvm.ptr, !llvm.ptr) -> !llvm.ptr {name = "dtype", partial_map = 
true}
   %6 = omp.map.info var_ptr(%arg0 : 
!fir.ref,int:i32}>>,
 !fir.type<_QFderived_type{real:f32,array:!fir.array<10xi32>,int:i32}>) 
map_clauses(tofrom) capture(ByRef) members(%2, %5 : [2], [0] : !fir.ref, 
!fir.ref) -> 
!fir.ref,int:i32}>> 
{name = "dtype", partial_map = true}
   // CHECK: omp.target map_entries(%[[MAP_MEMBER_1]] -> %[[ARG_1:.*]], 
%[[MAP_MEMBER_2]] -> %[[ARG_2:.*]], %[[MAP_PARENT]] -> %[[ARG_3:.*]] : 
!llvm.ptr, !llvm.ptr, !llvm.ptr) {
   omp.target map_entries(%2 -> %arg1, %5 -> %arg2, %6 -> %arg3 : 
!fir.ref, !fir.ref, 
!fir.ref,int:i32}>>)
 {
@@ -1275,3 +1275,22 @@ func.func @map_nested_dtype_alloca_mem2(%arg0 : 
!fir.ref {
+omp.declare_mapper @my_mapper : !fir.type<_QFdeclare_mapperTmy_type{data:i32}> 
{
+// CHECK: ^bb0(%[[VAL_0:.*]]: !llvm.ptr):
+^bb0(%0: !fir.ref>):
+// CHECK:   %[[VAL_1:.*]] = llvm.mlir.constant(0 : i32) : i32
+  %1 = fir.field_index data, !fir.type<_QFdeclare_mapperTmy_type{data:i32}>
+// CHECK:   %[[VAL_2:.*]] = llvm.getelementptr %[[VAL_0]][0, 0] : 
(!llvm.ptr) -> !llvm.ptr, !llvm.struct<"_QFdeclare_mapperTmy_type", (i32)>
+  %2 = fir.coordinate_of %0, %1 : 
(!fir.ref>, !fir.field) -> 
!fir.ref
+// CHECK:   %[[VAL_3:.*]] = omp.map.info var_ptr(%[[VAL_2]] : 
!llvm.ptr, i32) map_clauses(tofrom) capture(ByRef) -> !llvm.ptr {name = 
"var%[[VAL_4:.*]]"}
+  %3 = omp.map.info var_ptr(%2 : !fir.ref, i32) map_clauses(tofrom) 
capture(ByRef) -> !fir.ref {name = "var%data"}
+// CHECK:   %[[VAL_5:.*]] = omp.map.info var_ptr(%[[VAL_0]] : 
!llvm.ptr, !llvm.struct<"_QFdeclare_mapperTmy_type", (i32)>) 
map_clauses(tofrom) capture(ByRef) members(%[[VAL_3]] : [0] : !llvm.ptr) -> 
!llvm.ptr {name = "var", partial_map = true}
+  %4 = omp.map.info var_ptr(%0 : 
!fir.ref>, 
!fir.type<_QFdeclare_mapperTmy_type{data:i32}>) map_clauses(tofrom) 
capture(ByRef) members(%3 : [0] : !fir.ref) -> 
!fir.ref> {name = "var", 
partial_map = true}
+// CHECK:   omp.declare_mapper_info map_entries

[llvm-branch-commits] [clang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-02-12 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/124746

>From 7b5c918249a9c29ae586d9f1ccae6b7359fcd793 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Tue, 28 Jan 2025 13:38:13 +
Subject: [PATCH 1/7] [MLIR][OpenMP] Add LLVM translation support for OpenMP
 UserDefinedMappers

This patch adds OpenMPToLLVMIRTranslation support for the OpenMP Declare Mapper 
directive.

Since both MLIR and Clang now support custom mappers, I've made the relative 
params required instead of optional as well.

Depends on #121005
---
 clang/lib/CodeGen/CGOpenMPRuntime.cpp |  11 +-
 .../llvm/Frontend/OpenMP/OMPIRBuilder.h   |  31 +--
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp |  70 +++---
 .../Frontend/OpenMPIRBuilderTest.cpp  |  46 ++--
 .../OpenMP/OpenMPToLLVMIRTranslation.cpp  | 215 +++---
 mlir/test/Target/LLVMIR/omptarget-llvm.mlir   | 117 ++
 .../fortran/target-custom-mapper.f90  |  46 
 7 files changed, 437 insertions(+), 99 deletions(-)
 create mode 100644 offload/test/offloading/fortran/target-custom-mapper.f90

diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index cafaaa364cb76..b919c1f6ac627 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -8889,8 +8889,8 @@ static void emitOffloadingArraysAndArgs(
 return MFunc;
   };
   OMPBuilder.emitOffloadingArraysAndArgs(
-  AllocaIP, CodeGenIP, Info, Info.RTArgs, CombinedInfo, IsNonContiguous,
-  ForEndCall, DeviceAddrCB, CustomMapperCB);
+  AllocaIP, CodeGenIP, Info, Info.RTArgs, CombinedInfo, CustomMapperCB,
+  IsNonContiguous, ForEndCall, DeviceAddrCB);
 }
 
 /// Check for inner distribute directive.
@@ -9099,9 +9099,10 @@ void CGOpenMPRuntime::emitUserDefinedMapper(const 
OMPDeclareMapperDecl *D,
   CGM.getCXXABI().getMangleContext().mangleCanonicalTypeName(Ty, Out);
   std::string Name = getName({"omp_mapper", TyStr, D->getName()});
 
-  auto *NewFn = OMPBuilder.emitUserDefinedMapper(PrivatizeAndGenMapInfoCB,
- ElemTy, Name, CustomMapperCB);
-  UDMMap.try_emplace(D, NewFn);
+  llvm::Expected NewFn = OMPBuilder.emitUserDefinedMapper(
+  PrivatizeAndGenMapInfoCB, ElemTy, Name, CustomMapperCB);
+  assert(NewFn && "Unexpected error in emitUserDefinedMapper");
+  UDMMap.try_emplace(D, *NewFn);
   if (CGF)
 FunctionUDMMap[CGF->CurFn].push_back(D);
 }
diff --git a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h 
b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
index d25077cae63e4..151bd36aadaf0 100644
--- a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
+++ b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
@@ -2399,6 +2399,7 @@ class OpenMPIRBuilder {
CurInfo.NonContigInfo.Strides.end());
 }
   };
+  using MapInfosOrErrorTy = Expected;
 
   /// Callback function type for functions emitting the host fallback code that
   /// is executed when the kernel launch fails. It takes an insertion point as
@@ -2475,9 +2476,9 @@ class OpenMPIRBuilder {
   /// including base pointers, pointers, sizes, map types, user-defined 
mappers.
   void emitOffloadingArrays(
   InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy 
&CombinedInfo,
-  TargetDataInfo &Info, bool IsNonContiguous = false,
-  function_ref DeviceAddrCB = nullptr,
-  function_ref CustomMapperCB = nullptr);
+  TargetDataInfo &Info, function_ref CustomMapperCB,
+  bool IsNonContiguous = false,
+  function_ref DeviceAddrCB = nullptr);
 
   /// Allocates memory for and populates the arrays required for offloading
   /// (offload_{baseptrs|ptrs|mappers|sizes|maptypes|mapnames}). Then, it
@@ -2488,9 +2489,9 @@ class OpenMPIRBuilder {
   void emitOffloadingArraysAndArgs(
   InsertPointTy AllocaIP, InsertPointTy CodeGenIP, TargetDataInfo &Info,
   TargetDataRTArgs &RTArgs, MapInfosTy &CombinedInfo,
+  function_ref CustomMapperCB,
   bool IsNonContiguous = false, bool ForEndCall = false,
-  function_ref DeviceAddrCB = nullptr,
-  function_ref CustomMapperCB = nullptr);
+  function_ref DeviceAddrCB = nullptr);
 
   /// Creates offloading entry for the provided entry ID \a ID, address \a
   /// Addr, size \a Size, and flags \a Flags.
@@ -2950,12 +2951,12 @@ class OpenMPIRBuilder {
   /// \param FuncName Optional param to specify mapper function name.
   /// \param CustomMapperCB Optional callback to generate code related to
   /// custom mappers.
-  Function *emitUserDefinedMapper(
-  function_ref
+  Expected emitUserDefinedMapper(
+  function_ref
   PrivAndGenMapInfoCB,
   llvm::Type *ElemTy, StringRef FuncName,
-  function_ref CustomMapperCB = nullptr);
+  function_ref CustomMapperCB);
 
   /// Generator for '#omp target data'
   ///
@@ -2969,21 +2970,21 @@ class OpenMPIRBuilder {
   /// \param IfCond Value which corresponds to the if clause

[llvm-branch-commits] [clang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-02-12 Thread Akash Banerjee via llvm-branch-commits


@@ -3529,6 +3549,84 @@ static void genMapInfos(llvm::IRBuilderBase &builder,
   }
 }
 
+static llvm::Expected
+emitUserDefinedMapper(Operation *declMapperOp, llvm::IRBuilderBase &builder,
+  LLVM::ModuleTranslation &moduleTranslation);
+
+static llvm::Expected
+getOrCreateUserDefinedMapperFunc(Operation *declMapperOp,
+ llvm::IRBuilderBase &builder,
+ LLVM::ModuleTranslation &moduleTranslation) {
+  static llvm::DenseMap userDefMapperMap;

TIFitis wrote:

Oops, fixed now.


https://github.com/llvm/llvm-project/pull/124746
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


[llvm-branch-commits] [clang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-02-17 Thread Akash Banerjee via llvm-branch-commits

https://github.com/TIFitis updated 
https://github.com/llvm/llvm-project/pull/124746

>From 7b5c918249a9c29ae586d9f1ccae6b7359fcd793 Mon Sep 17 00:00:00 2001
From: Akash Banerjee 
Date: Tue, 28 Jan 2025 13:38:13 +
Subject: [PATCH 1/8] [MLIR][OpenMP] Add LLVM translation support for OpenMP
 UserDefinedMappers

This patch adds OpenMPToLLVMIRTranslation support for the OpenMP Declare Mapper 
directive.

Since both MLIR and Clang now support custom mappers, I've made the relative 
params required instead of optional as well.

Depends on #121005
---
 clang/lib/CodeGen/CGOpenMPRuntime.cpp |  11 +-
 .../llvm/Frontend/OpenMP/OMPIRBuilder.h   |  31 +--
 llvm/lib/Frontend/OpenMP/OMPIRBuilder.cpp |  70 +++---
 .../Frontend/OpenMPIRBuilderTest.cpp  |  46 ++--
 .../OpenMP/OpenMPToLLVMIRTranslation.cpp  | 215 +++---
 mlir/test/Target/LLVMIR/omptarget-llvm.mlir   | 117 ++
 .../fortran/target-custom-mapper.f90  |  46 
 7 files changed, 437 insertions(+), 99 deletions(-)
 create mode 100644 offload/test/offloading/fortran/target-custom-mapper.f90

diff --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp 
b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index cafaaa364cb76..b919c1f6ac627 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -8889,8 +8889,8 @@ static void emitOffloadingArraysAndArgs(
 return MFunc;
   };
   OMPBuilder.emitOffloadingArraysAndArgs(
-  AllocaIP, CodeGenIP, Info, Info.RTArgs, CombinedInfo, IsNonContiguous,
-  ForEndCall, DeviceAddrCB, CustomMapperCB);
+  AllocaIP, CodeGenIP, Info, Info.RTArgs, CombinedInfo, CustomMapperCB,
+  IsNonContiguous, ForEndCall, DeviceAddrCB);
 }
 
 /// Check for inner distribute directive.
@@ -9099,9 +9099,10 @@ void CGOpenMPRuntime::emitUserDefinedMapper(const 
OMPDeclareMapperDecl *D,
   CGM.getCXXABI().getMangleContext().mangleCanonicalTypeName(Ty, Out);
   std::string Name = getName({"omp_mapper", TyStr, D->getName()});
 
-  auto *NewFn = OMPBuilder.emitUserDefinedMapper(PrivatizeAndGenMapInfoCB,
- ElemTy, Name, CustomMapperCB);
-  UDMMap.try_emplace(D, NewFn);
+  llvm::Expected NewFn = OMPBuilder.emitUserDefinedMapper(
+  PrivatizeAndGenMapInfoCB, ElemTy, Name, CustomMapperCB);
+  assert(NewFn && "Unexpected error in emitUserDefinedMapper");
+  UDMMap.try_emplace(D, *NewFn);
   if (CGF)
 FunctionUDMMap[CGF->CurFn].push_back(D);
 }
diff --git a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h 
b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
index d25077cae63e4..151bd36aadaf0 100644
--- a/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
+++ b/llvm/include/llvm/Frontend/OpenMP/OMPIRBuilder.h
@@ -2399,6 +2399,7 @@ class OpenMPIRBuilder {
CurInfo.NonContigInfo.Strides.end());
 }
   };
+  using MapInfosOrErrorTy = Expected;
 
   /// Callback function type for functions emitting the host fallback code that
   /// is executed when the kernel launch fails. It takes an insertion point as
@@ -2475,9 +2476,9 @@ class OpenMPIRBuilder {
   /// including base pointers, pointers, sizes, map types, user-defined 
mappers.
   void emitOffloadingArrays(
   InsertPointTy AllocaIP, InsertPointTy CodeGenIP, MapInfosTy 
&CombinedInfo,
-  TargetDataInfo &Info, bool IsNonContiguous = false,
-  function_ref DeviceAddrCB = nullptr,
-  function_ref CustomMapperCB = nullptr);
+  TargetDataInfo &Info, function_ref CustomMapperCB,
+  bool IsNonContiguous = false,
+  function_ref DeviceAddrCB = nullptr);
 
   /// Allocates memory for and populates the arrays required for offloading
   /// (offload_{baseptrs|ptrs|mappers|sizes|maptypes|mapnames}). Then, it
@@ -2488,9 +2489,9 @@ class OpenMPIRBuilder {
   void emitOffloadingArraysAndArgs(
   InsertPointTy AllocaIP, InsertPointTy CodeGenIP, TargetDataInfo &Info,
   TargetDataRTArgs &RTArgs, MapInfosTy &CombinedInfo,
+  function_ref CustomMapperCB,
   bool IsNonContiguous = false, bool ForEndCall = false,
-  function_ref DeviceAddrCB = nullptr,
-  function_ref CustomMapperCB = nullptr);
+  function_ref DeviceAddrCB = nullptr);
 
   /// Creates offloading entry for the provided entry ID \a ID, address \a
   /// Addr, size \a Size, and flags \a Flags.
@@ -2950,12 +2951,12 @@ class OpenMPIRBuilder {
   /// \param FuncName Optional param to specify mapper function name.
   /// \param CustomMapperCB Optional callback to generate code related to
   /// custom mappers.
-  Function *emitUserDefinedMapper(
-  function_ref
+  Expected emitUserDefinedMapper(
+  function_ref
   PrivAndGenMapInfoCB,
   llvm::Type *ElemTy, StringRef FuncName,
-  function_ref CustomMapperCB = nullptr);
+  function_ref CustomMapperCB);
 
   /// Generator for '#omp target data'
   ///
@@ -2969,21 +2970,21 @@ class OpenMPIRBuilder {
   /// \param IfCond Value which corresponds to the if clause

[llvm-branch-commits] [clang] [llvm] [mlir] [MLIR][OpenMP] Add LLVM translation support for OpenMP UserDefinedMappers (PR #124746)

2025-02-17 Thread Akash Banerjee via llvm-branch-commits


@@ -4673,7 +4804,8 @@ convertHostOrTargetOperation(Operation *op, 
llvm::IRBuilderBase &builder,
   .Case([&](omp::TaskwaitOp op) {
 return convertOmpTaskwaitOp(op, builder, moduleTranslation);
   })
-  .Casehttps://github.com/llvm/llvm-project/pull/124746
___
llvm-branch-commits mailing list
llvm-branch-commits@lists.llvm.org
https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-branch-commits


  1   2   >