[clang] 8de3392 - [OpenMP] Add 'target loop' directive (#238448)

via cfe-commits cfe-commits at lists.llvm.org
Mon Nov 9 11:59:37 PST 2026


Author: Zahira Ammarguellat
Date: 2026-11-09T14:59:29-05:00
New Revision: 8de3392ce6ae0e98a2897e0a5690805320d14831

URL: https://github.com/llvm/llvm-project/commit/8de3392ce6ae0e98a2897e0a5690805320d14831
DIFF: https://github.com/llvm/llvm-project/commit/8de3392ce6ae0e98a2897e0a5690805320d14831.diff

LOG: [OpenMP] Add 'target loop' directive (#238448)

`#pragma omp target loop` has no AST node and crashes in clang. See
https://godbolt.org/z/6b64T91Gh
This PR adds the support. It is lowered like `target simd`: SPMD on the
device, one team, one thread.

Added: 
    clang/test/OpenMP/target_generic_loop_ast_print.cpp
    clang/test/OpenMP/target_generic_loop_codegen.cpp
    clang/test/OpenMP/target_generic_loop_messages.cpp

Modified: 
    clang/bindings/python/clang/cindex.py
    clang/docs/ReleaseNotes.md
    clang/include/clang-c/Index.h
    clang/include/clang/AST/RecursiveASTVisitor.h
    clang/include/clang/AST/StmtOpenMP.h
    clang/include/clang/Basic/StmtNodes.td
    clang/include/clang/Sema/SemaOpenMP.h
    clang/include/clang/Serialization/ASTBitCodes.h
    clang/lib/AST/StmtOpenMP.cpp
    clang/lib/AST/StmtPrinter.cpp
    clang/lib/AST/StmtProfile.cpp
    clang/lib/Basic/OpenMPKinds.cpp
    clang/lib/CIR/CodeGen/CIRGenFunction.h
    clang/lib/CIR/CodeGen/CIRGenStmt.cpp
    clang/lib/CIR/CodeGen/CIRGenStmtOpenMP.cpp
    clang/lib/CodeGen/CGOpenMPRuntime.cpp
    clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
    clang/lib/CodeGen/CGStmt.cpp
    clang/lib/CodeGen/CGStmtOpenMP.cpp
    clang/lib/CodeGen/CodeGenFunction.h
    clang/lib/Sema/SemaExceptionSpec.cpp
    clang/lib/Sema/SemaOpenMP.cpp
    clang/lib/Sema/TreeTransform.h
    clang/lib/Serialization/ASTReaderStmt.cpp
    clang/lib/Serialization/ASTWriterStmt.cpp
    clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
    clang/tools/libclang/CIndex.cpp
    clang/tools/libclang/CXCursor.cpp

Removed: 
    


################################################################################
diff  --git a/clang/bindings/python/clang/cindex.py b/clang/bindings/python/clang/cindex.py
index 0a3e7de7a884ae..c9567e73e10d5f 100644
--- a/clang/bindings/python/clang/cindex.py
+++ b/clang/bindings/python/clang/cindex.py
@@ -1475,6 +1475,9 @@ def is_unexposed(self):
     # OpenMP flatten directive.
     OMP_FLATTEN_DIRECTIVE = 314
 
+    # OpenMP target loop directive.
+    OMP_TARGET_GENERIC_LOOP_DIRECTIVE = 315
+
     # OpenACC Compute Construct.
     OPEN_ACC_COMPUTE_DIRECTIVE = 320
 

diff  --git a/clang/docs/ReleaseNotes.md b/clang/docs/ReleaseNotes.md
index 88546d7c95d5dd..95a866fcee1896 100644
--- a/clang/docs/ReleaseNotes.md
+++ b/clang/docs/ReleaseNotes.md
@@ -1632,6 +1632,10 @@ The `alpha.cplusplus.UseAfterLifetimeEnd` checker was renamed to `alpha.core.Use
 - Fixed `-fopenmp` and `-fopenmp-simd` host compilations dropping diagnostics when no
   offload target was configured, which accepted `try`/`throw` with exceptions disabled
   and let an invalid inline asm constraint crash CodeGen. (#GH147515)
+
+- Added support for the combined `#pragma omp target loop` construct, which
+  previously crashed the compiler. It is lowered like `#pragma omp target simd`.
+
 - Fixed variables shared by an enclosing region (e.g. `parallel`) being
   captured by copy when a nested construct has `default(firstprivate)` or
   `default(private)`, which could silently lose writes such as the result of

diff  --git a/clang/include/clang-c/Index.h b/clang/include/clang-c/Index.h
index f83db6a428ccf2..6f9928535ffc65 100644
--- a/clang/include/clang-c/Index.h
+++ b/clang/include/clang-c/Index.h
@@ -2178,6 +2178,10 @@ enum CXCursorKind {
    */
   CXCursor_OMPFlattenDirective = 314,
 
+  /** OpenMP target loop directive.
+   */
+  CXCursor_OMPTargetGenericLoopDirective = 315,
+
   /** OpenACC Compute Construct.
    */
   CXCursor_OpenACCComputeConstruct = 320,

diff  --git a/clang/include/clang/AST/RecursiveASTVisitor.h b/clang/include/clang/AST/RecursiveASTVisitor.h
index 13dd5eda84fa65..56aa9b772b1e75 100644
--- a/clang/include/clang/AST/RecursiveASTVisitor.h
+++ b/clang/include/clang/AST/RecursiveASTVisitor.h
@@ -3456,6 +3456,9 @@ DEF_TRAVERSE_STMT(OMPParallelGenericLoopDirective,
 DEF_TRAVERSE_STMT(OMPTargetParallelGenericLoopDirective,
                   { TRY_TO(TraverseOMPExecutableDirective(S)); })
 
+DEF_TRAVERSE_STMT(OMPTargetGenericLoopDirective,
+                  { TRY_TO(TraverseOMPExecutableDirective(S)); })
+
 DEF_TRAVERSE_STMT(OMPAssumeDirective,
                   { TRY_TO(TraverseOMPExecutableDirective(S)); })
 

diff  --git a/clang/include/clang/AST/StmtOpenMP.h b/clang/include/clang/AST/StmtOpenMP.h
index 66e5da218da822..5e6af8324fe8df 100644
--- a/clang/include/clang/AST/StmtOpenMP.h
+++ b/clang/include/clang/AST/StmtOpenMP.h
@@ -1642,6 +1642,7 @@ class OMPLoopDirective : public OMPLoopBasedDirective {
            T->getStmtClass() == OMPTargetTeamsGenericLoopDirectiveClass ||
            T->getStmtClass() == OMPParallelGenericLoopDirectiveClass ||
            T->getStmtClass() == OMPTargetParallelGenericLoopDirectiveClass ||
+           T->getStmtClass() == OMPTargetGenericLoopDirectiveClass ||
            T->getStmtClass() == OMPParallelMaskedTaskLoopDirectiveClass ||
            T->getStmtClass() == OMPParallelMaskedTaskLoopSimdDirectiveClass ||
            T->getStmtClass() == OMPParallelMasterTaskLoopDirectiveClass ||
@@ -7034,6 +7035,71 @@ class OMPTargetParallelGenericLoopDirective final : public OMPLoopDirective {
   }
 };
 
+/// This represents '#pragma omp target loop' directive.
+///
+/// \code
+/// #pragma omp target loop private(a,b) order(concurrent)
+/// \endcode
+/// In this example directive '#pragma omp target loop' has
+/// clauses 'private' with the variables 'a' and 'b', and order(concurrent).
+///
+class OMPTargetGenericLoopDirective final : public OMPLoopDirective {
+  friend class ASTStmtReader;
+  friend class OMPExecutableDirective;
+  /// Build directive with the given start and end location.
+  ///
+  /// \param StartLoc Starting location of the directive kind.
+  /// \param EndLoc Ending location of the directive.
+  /// \param CollapsedNum Number of collapsed nested loops.
+  ///
+  OMPTargetGenericLoopDirective(SourceLocation StartLoc, SourceLocation EndLoc,
+                                unsigned CollapsedNum)
+      : OMPLoopDirective(OMPTargetGenericLoopDirectiveClass,
+                         llvm::omp::OMPD_target_loop, StartLoc, EndLoc,
+                         CollapsedNum) {}
+
+  /// Build an empty directive.
+  ///
+  /// \param CollapsedNum Number of collapsed nested loops.
+  ///
+  explicit OMPTargetGenericLoopDirective(unsigned CollapsedNum)
+      : OMPLoopDirective(OMPTargetGenericLoopDirectiveClass,
+                         llvm::omp::OMPD_target_loop, SourceLocation(),
+                         SourceLocation(), CollapsedNum) {}
+
+public:
+  /// Creates directive with a list of \p Clauses.
+  ///
+  /// \param C AST context.
+  /// \param StartLoc Starting location of the directive kind.
+  /// \param EndLoc Ending Location of the directive.
+  /// \param CollapsedNum Number of collapsed loops.
+  /// \param Clauses List of clauses.
+  /// \param AssociatedStmt Statement, associated with the directive.
+  /// \param Exprs Helper expressions for CodeGen.
+  ///
+  static OMPTargetGenericLoopDirective *
+  Create(const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
+         unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses,
+         Stmt *AssociatedStmt, const HelperExprs &Exprs);
+
+  /// Creates an empty directive with the place
+  /// for \a NumClauses clauses.
+  ///
+  /// \param C AST context.
+  /// \param CollapsedNum Number of collapsed nested loops.
+  /// \param NumClauses Number of clauses.
+  ///
+  static OMPTargetGenericLoopDirective *CreateEmpty(const ASTContext &C,
+                                                    unsigned NumClauses,
+                                                    unsigned CollapsedNum,
+                                                    EmptyShell);
+
+  static bool classof(const Stmt *T) {
+    return T->getStmtClass() == OMPTargetGenericLoopDirectiveClass;
+  }
+};
+
 /// This represents '#pragma omp error' directive.
 ///
 /// \code

diff  --git a/clang/include/clang/Basic/StmtNodes.td b/clang/include/clang/Basic/StmtNodes.td
index 96f7a0080f20d6..2094a1acfb5a8e 100644
--- a/clang/include/clang/Basic/StmtNodes.td
+++ b/clang/include/clang/Basic/StmtNodes.td
@@ -328,6 +328,7 @@ def OMPTeamsGenericLoopDirective : StmtNode<OMPLoopDirective>;
 def OMPTargetTeamsGenericLoopDirective : StmtNode<OMPLoopDirective>;
 def OMPParallelGenericLoopDirective : StmtNode<OMPLoopDirective>;
 def OMPTargetParallelGenericLoopDirective : StmtNode<OMPLoopDirective>;
+def OMPTargetGenericLoopDirective : StmtNode<OMPLoopDirective>;
 def OMPAssumeDirective : StmtNode<OMPExecutableDirective>;
 def OMPErrorDirective : StmtNode<OMPExecutableDirective>;
 

diff  --git a/clang/include/clang/Sema/SemaOpenMP.h b/clang/include/clang/Sema/SemaOpenMP.h
index 6750f6a9ce4c23..a8a291d02722ce 100644
--- a/clang/include/clang/Sema/SemaOpenMP.h
+++ b/clang/include/clang/Sema/SemaOpenMP.h
@@ -667,6 +667,11 @@ class SemaOpenMP : public SemaBase {
   StmtResult ActOnOpenMPTargetParallelGenericLoopDirective(
       ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
       SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
+  /// Called on well-formed '\#pragma omp target loop' after parsing of the
+  /// associated statement.
+  StmtResult ActOnOpenMPTargetGenericLoopDirective(
+      ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
+      SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA);
   /// Called on well-formed '\#pragma omp cancellation point'.
   StmtResult
   ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,

diff  --git a/clang/include/clang/Serialization/ASTBitCodes.h b/clang/include/clang/Serialization/ASTBitCodes.h
index ae3a2fad6ebe7f..04cc0c5af89d15 100644
--- a/clang/include/clang/Serialization/ASTBitCodes.h
+++ b/clang/include/clang/Serialization/ASTBitCodes.h
@@ -2067,6 +2067,7 @@ enum StmtCode {
   STMT_OMP_TARGET_TEAMS_GENERIC_LOOP_DIRECTIVE,
   STMT_OMP_PARALLEL_GENERIC_LOOP_DIRECTIVE,
   STMT_OMP_TARGET_PARALLEL_GENERIC_LOOP_DIRECTIVE,
+  STMT_OMP_TARGET_GENERIC_LOOP_DIRECTIVE,
   STMT_OMP_ASSUME_DIRECTIVE,
   EXPR_ARRAY_SECTION,
   EXPR_OMP_ARRAY_SHAPING,

diff  --git a/clang/lib/AST/StmtOpenMP.cpp b/clang/lib/AST/StmtOpenMP.cpp
index 6efa0a4a801823..4f0b6ea85e2f8a 100644
--- a/clang/lib/AST/StmtOpenMP.cpp
+++ b/clang/lib/AST/StmtOpenMP.cpp
@@ -2048,3 +2048,47 @@ OMPTargetParallelGenericLoopDirective::CreateEmpty(const ASTContext &C,
       C, NumClauses, /*HasAssociatedStmt=*/true,
       numLoopChildren(CollapsedNum, OMPD_target_parallel_loop), CollapsedNum);
 }
+
+OMPTargetGenericLoopDirective *OMPTargetGenericLoopDirective::Create(
+    const ASTContext &C, SourceLocation StartLoc, SourceLocation EndLoc,
+    unsigned CollapsedNum, ArrayRef<OMPClause *> Clauses, Stmt *AssociatedStmt,
+    const HelperExprs &Exprs) {
+  auto *Dir = createDirective<OMPTargetGenericLoopDirective>(
+      C, Clauses, AssociatedStmt,
+      numLoopChildren(CollapsedNum, OMPD_target_loop), StartLoc, EndLoc,
+      CollapsedNum);
+  Dir->setIterationVariable(Exprs.IterationVarRef);
+  Dir->setLastIteration(Exprs.LastIteration);
+  Dir->setCalcLastIteration(Exprs.CalcLastIteration);
+  Dir->setPreCond(Exprs.PreCond);
+  Dir->setCond(Exprs.Cond);
+  Dir->setInit(Exprs.Init);
+  Dir->setInc(Exprs.Inc);
+  Dir->setIsLastIterVariable(Exprs.IL);
+  Dir->setLowerBoundVariable(Exprs.LB);
+  Dir->setUpperBoundVariable(Exprs.UB);
+  Dir->setStrideVariable(Exprs.ST);
+  Dir->setEnsureUpperBound(Exprs.EUB);
+  Dir->setNextLowerBound(Exprs.NLB);
+  Dir->setNextUpperBound(Exprs.NUB);
+  Dir->setNumIterations(Exprs.NumIterations);
+  Dir->setCounters(Exprs.Counters);
+  Dir->setPrivateCounters(Exprs.PrivateCounters);
+  Dir->setInits(Exprs.Inits);
+  Dir->setUpdates(Exprs.Updates);
+  Dir->setFinals(Exprs.Finals);
+  Dir->setDependentCounters(Exprs.DependentCounters);
+  Dir->setDependentInits(Exprs.DependentInits);
+  Dir->setFinalsConditions(Exprs.FinalsConditions);
+  Dir->setPreInits(Exprs.PreInits);
+  return Dir;
+}
+
+OMPTargetGenericLoopDirective *
+OMPTargetGenericLoopDirective::CreateEmpty(const ASTContext &C,
+                                           unsigned NumClauses,
+                                           unsigned CollapsedNum, EmptyShell) {
+  return createEmptyDirective<OMPTargetGenericLoopDirective>(
+      C, NumClauses, /*HasAssociatedStmt=*/true,
+      numLoopChildren(CollapsedNum, OMPD_target_loop), CollapsedNum);
+}

diff  --git a/clang/lib/AST/StmtPrinter.cpp b/clang/lib/AST/StmtPrinter.cpp
index bed934a70ab519..54085aa8d96d02 100644
--- a/clang/lib/AST/StmtPrinter.cpp
+++ b/clang/lib/AST/StmtPrinter.cpp
@@ -1277,6 +1277,12 @@ void StmtPrinter::VisitOMPTargetParallelGenericLoopDirective(
   PrintOMPExecutableDirective(Node);
 }
 
+void StmtPrinter::VisitOMPTargetGenericLoopDirective(
+    OMPTargetGenericLoopDirective *Node) {
+  Indent() << "#pragma omp target loop";
+  PrintOMPExecutableDirective(Node);
+}
+
 //===----------------------------------------------------------------------===//
 //  OpenACC construct printing methods
 //===----------------------------------------------------------------------===//

diff  --git a/clang/lib/AST/StmtProfile.cpp b/clang/lib/AST/StmtProfile.cpp
index b24aaf2b9cc422..476610b9956c71 100644
--- a/clang/lib/AST/StmtProfile.cpp
+++ b/clang/lib/AST/StmtProfile.cpp
@@ -1445,6 +1445,11 @@ void StmtProfiler::VisitOMPTargetParallelGenericLoopDirective(
   VisitOMPLoopDirective(S);
 }
 
+void StmtProfiler::VisitOMPTargetGenericLoopDirective(
+    const OMPTargetGenericLoopDirective *S) {
+  VisitOMPLoopDirective(S);
+}
+
 void StmtProfiler::VisitExpr(const Expr *S) {
   VisitStmt(S);
 }

diff  --git a/clang/lib/Basic/OpenMPKinds.cpp b/clang/lib/Basic/OpenMPKinds.cpp
index 8049e5d7c1be9c..3d06da48b03dcf 100644
--- a/clang/lib/Basic/OpenMPKinds.cpp
+++ b/clang/lib/Basic/OpenMPKinds.cpp
@@ -879,7 +879,7 @@ bool clang::needsTaskBasedThreadLimit(OpenMPDirectiveKind DKind) {
   return DKind == OMPD_target || DKind == OMPD_target_parallel ||
          DKind == OMPD_target_parallel_for ||
          DKind == OMPD_target_parallel_for_simd || DKind == OMPD_target_simd ||
-         DKind == OMPD_target_parallel_loop;
+         DKind == OMPD_target_parallel_loop || DKind == OMPD_target_loop;
 }
 
 bool clang::isOpenMPExecutableDirective(OpenMPDirectiveKind DKind) {
@@ -1002,10 +1002,8 @@ void clang::getOpenMPCaptureRegions(
     case OMPD_loop:
       // TODO: 'loop' may require 
diff erent capture regions depending on the
       // bind clause or the parent directive when there is no bind clause.
-      // If any of the directives that push regions here are parents of 'loop',
-      // assume 'parallel'. Otherwise do nothing.
-      if (!CaptureRegions.empty() &&
-          !llvm::is_contained(CaptureRegions, OMPD_parallel))
+      // Only 'teams' parents get 'parallel'; 'target loop' is emitted as simd.
+      if (!CaptureRegions.empty() && CaptureRegions.back() == OMPD_teams)
         CaptureRegions.push_back(OMPD_parallel);
       else
         return true;

diff  --git a/clang/lib/CIR/CodeGen/CIRGenFunction.h b/clang/lib/CIR/CodeGen/CIRGenFunction.h
index f9483d9aac8ce1..3ebbaecaecba54 100644
--- a/clang/lib/CIR/CodeGen/CIRGenFunction.h
+++ b/clang/lib/CIR/CodeGen/CIRGenFunction.h
@@ -2955,6 +2955,8 @@ class CIRGenFunction : public CIRGenTypeCache {
   emitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &s);
   mlir::LogicalResult emitOMPTargetParallelGenericLoopDirective(
       const OMPTargetParallelGenericLoopDirective &s);
+  mlir::LogicalResult
+  emitOMPTargetGenericLoopDirective(const OMPTargetGenericLoopDirective &s);
   mlir::LogicalResult emitOMPTargetParallelForSimdDirective(
       const OMPTargetParallelForSimdDirective &s);
   mlir::LogicalResult

diff  --git a/clang/lib/CIR/CodeGen/CIRGenStmt.cpp b/clang/lib/CIR/CodeGen/CIRGenStmt.cpp
index 9f6972454cdd50..dc33685944600e 100644
--- a/clang/lib/CIR/CodeGen/CIRGenStmt.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenStmt.cpp
@@ -436,6 +436,9 @@ mlir::LogicalResult CIRGenFunction::emitStmt(const Stmt *s,
   case Stmt::OMPTargetParallelGenericLoopDirectiveClass:
     return emitOMPTargetParallelGenericLoopDirective(
         cast<OMPTargetParallelGenericLoopDirective>(*s));
+  case Stmt::OMPTargetGenericLoopDirectiveClass:
+    return emitOMPTargetGenericLoopDirective(
+        cast<OMPTargetGenericLoopDirective>(*s));
   case Stmt::OMPTargetParallelForSimdDirectiveClass:
     return emitOMPTargetParallelForSimdDirective(
         cast<OMPTargetParallelForSimdDirective>(*s));

diff  --git a/clang/lib/CIR/CodeGen/CIRGenStmtOpenMP.cpp b/clang/lib/CIR/CodeGen/CIRGenStmtOpenMP.cpp
index 9d937f5ed67f90..2b0e6819898374 100644
--- a/clang/lib/CIR/CodeGen/CIRGenStmtOpenMP.cpp
+++ b/clang/lib/CIR/CodeGen/CIRGenStmtOpenMP.cpp
@@ -601,6 +601,11 @@ mlir::LogicalResult CIRGenFunction::emitOMPTargetParallelGenericLoopDirective(
                              "OpenMP OMPTargetParallelGenericLoopDirective");
   return mlir::failure();
 }
+mlir::LogicalResult CIRGenFunction::emitOMPTargetGenericLoopDirective(
+    const OMPTargetGenericLoopDirective &s) {
+  cgm.errorNYI(s.getSourceRange(), "OpenMP OMPTargetGenericLoopDirective");
+  return mlir::failure();
+}
 mlir::LogicalResult CIRGenFunction::emitOMPTargetParallelForSimdDirective(
     const OMPTargetParallelForSimdDirective &s) {
   getCIRGenModule().errorNYI(s.getSourceRange(),

diff  --git a/clang/lib/CodeGen/CGOpenMPRuntime.cpp b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
index f19e2b227a2b9f..62a537c885fc31 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntime.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntime.cpp
@@ -6758,6 +6758,7 @@ const Expr *CGOpenMPRuntime::getNumTeamsExprForTargetDirective(
   case OMPD_target_parallel_for_simd:
   case OMPD_target_parallel_loop:
   case OMPD_target_simd:
+  case OMPD_target_loop:
     MinTeamsVal = MaxTeamsVal = 1;
     return nullptr;
   case OMPD_parallel:
@@ -7144,6 +7145,7 @@ const Expr *CGOpenMPRuntime::getNumThreadsExprForTargetDirective(
   }
   case OMPD_target_teams_distribute_simd:
   case OMPD_target_simd:
+  case OMPD_target_loop:
     return ReturnSequential();
   default:
     break;
@@ -10741,6 +10743,7 @@ getNestedDistributeDirective(ASTContext &Ctx, const OMPExecutableDirective &D) {
       return nullptr;
     case OMPD_target_parallel:
     case OMPD_target_simd:
+    case OMPD_target_loop:
     case OMPD_target_parallel_for:
     case OMPD_target_parallel_for_simd:
       return nullptr;
@@ -11492,8 +11495,9 @@ void CGOpenMPRuntime::scanForTargetRegionsFunctions(const Stmt *S,
           CGM, ParentName, cast<OMPTargetParallelForSimdDirective>(E));
       break;
     case OMPD_target_simd:
+    case OMPD_target_loop:
       CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
-          CGM, ParentName, cast<OMPTargetSimdDirective>(E));
+          CGM, ParentName, cast<OMPLoopDirective>(E));
       break;
     case OMPD_target_teams_distribute_parallel_for:
       CodeGenFunction::EmitOMPTargetTeamsDistributeParallelForDeviceFunction(

diff  --git a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
index 4b9bf00ae5efe5..bf8cd97e10166f 100644
--- a/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
+++ b/clang/lib/CodeGen/CGOpenMPRuntimeGPU.cpp
@@ -635,6 +635,7 @@ static bool supportsSPMDExecutionMode(ASTContext &Ctx,
   case OMPD_target_teams_distribute_parallel_for:
   case OMPD_target_teams_distribute_parallel_for_simd:
   case OMPD_target_simd:
+  case OMPD_target_loop:
   case OMPD_target_teams_distribute_simd:
     return true;
   case OMPD_target_teams_distribute:

diff  --git a/clang/lib/CodeGen/CGStmt.cpp b/clang/lib/CodeGen/CGStmt.cpp
index d87cbee8db40c1..455c4352661043 100644
--- a/clang/lib/CodeGen/CGStmt.cpp
+++ b/clang/lib/CodeGen/CGStmt.cpp
@@ -468,6 +468,9 @@ void CodeGenFunction::EmitStmt(const Stmt *S, ArrayRef<const Attr *> Attrs) {
     EmitOMPTargetParallelGenericLoopDirective(
         cast<OMPTargetParallelGenericLoopDirective>(*S));
     break;
+  case Stmt::OMPTargetGenericLoopDirectiveClass:
+    EmitOMPTargetSimdDirective(cast<OMPTargetGenericLoopDirective>(*S));
+    break;
   case Stmt::OMPParallelMaskedDirectiveClass:
     EmitOMPParallelMaskedDirective(cast<OMPParallelMaskedDirective>(*S));
     break;

diff  --git a/clang/lib/CodeGen/CGStmtOpenMP.cpp b/clang/lib/CodeGen/CGStmtOpenMP.cpp
index 9df06fd2a77c9d..af2f75f337170d 100644
--- a/clang/lib/CodeGen/CGStmtOpenMP.cpp
+++ b/clang/lib/CodeGen/CGStmtOpenMP.cpp
@@ -355,7 +355,7 @@ class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
         }
       }
     }
-    if (!isOpenMPSimdDirective(getEffectiveDirectiveKind(S)))
+    if (!isOpenMPSimdDirective(S.getDirectiveKind()))
       CGF.EmitOMPPrivateClause(S, InlinedShareds);
     if (const auto *TG = dyn_cast<OMPTaskgroupDirective>(&S)) {
       if (const Expr *E = TG->getReductionRef())
@@ -396,14 +396,16 @@ class OMPSimdLexicalScope : public CodeGenFunction::LexicalScope {
 
 } // namespace
 
-// Map `loop` with a bind clause, `teams loop`, and `target teams loop` to the
-// construct CodeGen emits.
+// Map `loop` with a bind clause, `teams loop`, `target loop`, and
+// `target teams loop` to the construct CodeGen emits.
 static OpenMPDirectiveKind
 getEffectiveDirectiveKind(const OMPExecutableDirective &S) {
   OpenMPDirectiveKind Kind = S.getDirectiveKind();
 
   if (Kind == OMPD_teams_loop)
     return OMPD_teams_distribute;
+  if (Kind == OMPD_target_loop)
+    return OMPD_target_simd;
   if (Kind == OMPD_target_teams_loop)
     return cast<OMPTargetTeamsGenericLoopDirective>(S).canBeParallelFor()
                ? OMPD_target_teams_distribute_parallel_for
@@ -3210,8 +3212,7 @@ static void emitCommonSimdLoop(CodeGenFunction &CGF, const OMPLoopDirective &S,
     BodyCodeGen(CGF);
   };
   const Expr *IfCond = nullptr;
-  OpenMPDirectiveKind EKind = getEffectiveDirectiveKind(S);
-  if (isOpenMPSimdDirective(EKind)) {
+  if (isOpenMPSimdDirective(S.getDirectiveKind())) {
     for (const auto *C : S.getClausesOfKind<OMPIfClause>()) {
       if (CGF.getLangOpts().OpenMP >= 50 &&
           (C->getNameModifier() == OMPD_unknown ||
@@ -4013,7 +4014,7 @@ void CodeGenFunction::EmitOMPDistributeSimdDirective(
 }
 
 void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
-    CodeGenModule &CGM, StringRef ParentName, const OMPTargetSimdDirective &S) {
+    CodeGenModule &CGM, StringRef ParentName, const OMPLoopDirective &S) {
   // Emit SPMD target parallel for region as a standalone region.
   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
     emitOMPSimdRegion(CGF, S, Action);
@@ -4026,8 +4027,7 @@ void CodeGenFunction::EmitOMPTargetSimdDeviceFunction(
   assert(Fn && Addr && "Target device function emission failed.");
 }
 
-void CodeGenFunction::EmitOMPTargetSimdDirective(
-    const OMPTargetSimdDirective &S) {
+void CodeGenFunction::EmitOMPTargetSimdDirective(const OMPLoopDirective &S) {
   auto &&CodeGen = [&S](CodeGenFunction &CGF, PrePostActionTy &Action) {
     emitOMPSimdRegion(CGF, S, Action);
   };

diff  --git a/clang/lib/CodeGen/CodeGenFunction.h b/clang/lib/CodeGen/CodeGenFunction.h
index e6ecf3bca3e94c..ef3719ca94aaf0 100644
--- a/clang/lib/CodeGen/CodeGenFunction.h
+++ b/clang/lib/CodeGen/CodeGenFunction.h
@@ -4096,7 +4096,8 @@ class CodeGenFunction : public CodeGenTypeCache {
   void EmitOMPDistributeSimdDirective(const OMPDistributeSimdDirective &S);
   void EmitOMPTargetParallelForSimdDirective(
       const OMPTargetParallelForSimdDirective &S);
-  void EmitOMPTargetSimdDirective(const OMPTargetSimdDirective &S);
+  /// Also emits 'target loop'.
+  void EmitOMPTargetSimdDirective(const OMPLoopDirective &S);
   void EmitOMPTeamsDistributeDirective(const OMPTeamsDistributeDirective &S);
   void
   EmitOMPTeamsDistributeSimdDirective(const OMPTeamsDistributeSimdDirective &S);
@@ -4151,10 +4152,10 @@ class CodeGenFunction : public CodeGenTypeCache {
   static void EmitOMPTargetTeamsDistributeSimdDeviceFunction(
       CodeGenModule &CGM, StringRef ParentName,
       const OMPTargetTeamsDistributeSimdDirective &S);
-  /// Emit device code for the target simd directive.
+  /// Emit device code for the target simd and target loop directives.
   static void EmitOMPTargetSimdDeviceFunction(CodeGenModule &CGM,
                                               StringRef ParentName,
-                                              const OMPTargetSimdDirective &S);
+                                              const OMPLoopDirective &S);
   /// Emit device code for the target teams distribute parallel for simd
   /// directive.
   static void EmitOMPTargetTeamsDistributeParallelForSimdDeviceFunction(

diff  --git a/clang/lib/Sema/SemaExceptionSpec.cpp b/clang/lib/Sema/SemaExceptionSpec.cpp
index 56fe626f8192fe..a0d3d1c2df371f 100644
--- a/clang/lib/Sema/SemaExceptionSpec.cpp
+++ b/clang/lib/Sema/SemaExceptionSpec.cpp
@@ -1552,6 +1552,7 @@ CanThrowResult Sema::canThrow(const Stmt *S) {
   case Stmt::OMPTargetTeamsGenericLoopDirectiveClass:
   case Stmt::OMPParallelGenericLoopDirectiveClass:
   case Stmt::OMPTargetParallelGenericLoopDirectiveClass:
+  case Stmt::OMPTargetGenericLoopDirectiveClass:
   case Stmt::ReturnStmtClass:
   case Stmt::SEHExceptStmtClass:
   case Stmt::SEHFinallyStmtClass:

diff  --git a/clang/lib/Sema/SemaOpenMP.cpp b/clang/lib/Sema/SemaOpenMP.cpp
index 6f4c71b118d590..505ebc0ab69331 100644
--- a/clang/lib/Sema/SemaOpenMP.cpp
+++ b/clang/lib/Sema/SemaOpenMP.cpp
@@ -7239,6 +7239,10 @@ StmtResult SemaOpenMP::ActOnOpenMPExecutableDirective(
     Res = ActOnOpenMPTargetParallelGenericLoopDirective(
         ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
     break;
+  case OMPD_target_loop:
+    Res = ActOnOpenMPTargetGenericLoopDirective(
+        ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
+    break;
   case OMPD_declare_target:
   case OMPD_end_declare_target:
   case OMPD_threadprivate:
@@ -12115,17 +12119,21 @@ StmtResult SemaOpenMP::ActOnOpenMPParallelGenericLoopDirective(
       getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
 }
 
-StmtResult SemaOpenMP::ActOnOpenMPTargetParallelGenericLoopDirective(
+/// Shared by 'target loop' and 'target parallel loop'.
+template <typename DirectiveTy>
+static StmtResult actOnTargetGenericLoopDirective(
+    SemaOpenMP &S, DSAStackTy *Stack, OpenMPDirectiveKind DKind,
     ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
-    SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
+    SourceLocation EndLoc,
+    SemaOpenMP::VarsWithInheritedDSAType &VarsWithImplicitDSA) {
   if (!AStmt)
     return StmtError();
 
-  if (validateMultidimClauses(*this, Clauses))
+  if (validateMultidimClauses(S, Clauses))
     return StmtError();
 
-  if (checkClausesForDecompositionConflicts(SemaRef, OMPD_target_parallel_loop,
-                                            Clauses))
+  Sema &SemaRef = S.SemaRef;
+  if (checkClausesForDecompositionConflicts(SemaRef, DKind, Clauses))
     return StmtError();
 
   if (checkOriginalVarMappedButOnlyBindingsUsed(SemaRef, Clauses, AStmt))
@@ -12134,27 +12142,54 @@ StmtResult SemaOpenMP::ActOnOpenMPTargetParallelGenericLoopDirective(
   // OpenMP 5.1 [2.11.7, loop construct, Restrictions]
   // A list item may not appear in a lastprivate clause unless it is the
   // loop iteration variable of a loop that is associated with the construct.
-  if (checkGenericLoopLastprivate(SemaRef, Clauses, OMPD_target_parallel_loop,
-                                  DSAStack))
+  if (checkGenericLoopLastprivate(SemaRef, Clauses, DKind, Stack))
     return StmtError();
 
-  CapturedStmt *CS =
-      setBranchProtectedScope(SemaRef, OMPD_target_parallel_loop, AStmt);
+  CapturedStmt *CS = setBranchProtectedScope(SemaRef, DKind, AStmt);
 
   OMPLoopDirective::HelperExprs B;
   // In presence of clause 'collapse', it will define the nested loops number.
-  unsigned NestedLoopCount =
-      checkOpenMPLoop(OMPD_target_parallel_loop, getCollapseNumberExpr(Clauses),
-                      /*OrderedLoopCountExpr=*/nullptr, CS, SemaRef, *DSAStack,
-                      VarsWithImplicitDSA, B);
+  unsigned NestedLoopCount = checkOpenMPLoop(
+      DKind, getCollapseNumberExpr(Clauses), /*OrderedLoopCountExpr=*/nullptr,
+      CS, SemaRef, *Stack, VarsWithImplicitDSA, B);
   if (NestedLoopCount == 0)
     return StmtError();
 
   assert((SemaRef.CurContext->isDependentContext() || B.builtAll()) &&
          "omp loop exprs were not built");
 
-  return OMPTargetParallelGenericLoopDirective::Create(
-      getASTContext(), StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
+  return DirectiveTy::Create(S.getASTContext(), StartLoc, EndLoc,
+                             NestedLoopCount, Clauses, AStmt, B);
+}
+
+StmtResult SemaOpenMP::ActOnOpenMPTargetParallelGenericLoopDirective(
+    ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
+    SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
+  return actOnTargetGenericLoopDirective<OMPTargetParallelGenericLoopDirective>(
+      *this, DSAStack, OMPD_target_parallel_loop, Clauses, AStmt, StartLoc,
+      EndLoc, VarsWithImplicitDSA);
+}
+
+StmtResult SemaOpenMP::ActOnOpenMPTargetGenericLoopDirective(
+    ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
+    SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
+  // OpenMP 5.1 [2.11.7, loop Construct, Restrictions]
+  // If the bind clause is present on the loop construct and binding is teams
+  // then the corresponding loop region must be strictly nested inside a teams
+  // region.
+  if (const auto *BC =
+          OMPExecutableDirective::getSingleClause<OMPBindClause>(Clauses);
+      BC && BC->getBindKind() == OMPC_BIND_teams) {
+    llvm::omp::Version OMPVersion = getLangOpts().getOpenMPVersion();
+    Diag(StartLoc, diag::err_omp_prohibited_region)
+        << /*IsClose=*/true << getOpenMPDirectiveName(OMPD_target, OMPVersion)
+        << /*ShouldBeInTeamsRegion=*/4
+        << getOpenMPDirectiveName(OMPD_loop, OMPVersion);
+    return StmtError();
+  }
+  return actOnTargetGenericLoopDirective<OMPTargetGenericLoopDirective>(
+      *this, DSAStack, OMPD_target_loop, Clauses, AStmt, StartLoc, EndLoc,
+      VarsWithImplicitDSA);
 }
 
 StmtResult SemaOpenMP::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,

diff  --git a/clang/lib/Sema/TreeTransform.h b/clang/lib/Sema/TreeTransform.h
index 8dc79a88d19889..2912ed99df4617 100644
--- a/clang/lib/Sema/TreeTransform.h
+++ b/clang/lib/Sema/TreeTransform.h
@@ -11002,6 +11002,17 @@ TreeTransform<Derived>::TransformOMPTargetParallelGenericLoopDirective(
   return Res;
 }
 
+template <typename Derived>
+StmtResult TreeTransform<Derived>::TransformOMPTargetGenericLoopDirective(
+    OMPTargetGenericLoopDirective *D) {
+  DeclarationNameInfo DirName;
+  getDerived().getSema().OpenMP().StartOpenMPDSABlock(
+      OMPD_target_loop, DirName, nullptr, D->getBeginLoc());
+  StmtResult Res = getDerived().TransformOMPExecutableDirective(D);
+  getDerived().getSema().OpenMP().EndOpenMPDSABlock(Res.get());
+  return Res;
+}
+
 //===----------------------------------------------------------------------===//
 // OpenMP clause transformation
 //===----------------------------------------------------------------------===//

diff  --git a/clang/lib/Serialization/ASTReaderStmt.cpp b/clang/lib/Serialization/ASTReaderStmt.cpp
index b09471c13a48e2..bc915aa2578b27 100644
--- a/clang/lib/Serialization/ASTReaderStmt.cpp
+++ b/clang/lib/Serialization/ASTReaderStmt.cpp
@@ -2978,6 +2978,11 @@ void ASTStmtReader::VisitOMPTargetParallelGenericLoopDirective(
   VisitOMPLoopDirective(D);
 }
 
+void ASTStmtReader::VisitOMPTargetGenericLoopDirective(
+    OMPTargetGenericLoopDirective *D) {
+  VisitOMPLoopDirective(D);
+}
+
 //===----------------------------------------------------------------------===//
 // OpenACC Constructs/Directives.
 //===----------------------------------------------------------------------===//
@@ -4247,6 +4252,14 @@ Stmt *ASTReader::ReadStmtFromStream(ModuleFile &F) {
       break;
     }
 
+    case STMT_OMP_TARGET_GENERIC_LOOP_DIRECTIVE: {
+      unsigned CollapsedNum = Record[ASTStmtReader::NumStmtFields];
+      unsigned NumClauses = Record[ASTStmtReader::NumStmtFields + 1];
+      S = OMPTargetGenericLoopDirective::CreateEmpty(Context, NumClauses,
+                                                     CollapsedNum, Empty);
+      break;
+    }
+
     case STMT_OMP_ASSUME_DIRECTIVE: {
       unsigned NumClauses = Record[ASTStmtReader::NumStmtFields];
       S = OMPAssumeDirective::CreateEmpty(Context, NumClauses, Empty);

diff  --git a/clang/lib/Serialization/ASTWriterStmt.cpp b/clang/lib/Serialization/ASTWriterStmt.cpp
index f91f318426290c..335b8c046493c6 100644
--- a/clang/lib/Serialization/ASTWriterStmt.cpp
+++ b/clang/lib/Serialization/ASTWriterStmt.cpp
@@ -3128,6 +3128,12 @@ void ASTStmtWriter::VisitOMPTargetParallelGenericLoopDirective(
   Code = serialization::STMT_OMP_TARGET_PARALLEL_GENERIC_LOOP_DIRECTIVE;
 }
 
+void ASTStmtWriter::VisitOMPTargetGenericLoopDirective(
+    OMPTargetGenericLoopDirective *D) {
+  VisitOMPLoopDirective(D);
+  Code = serialization::STMT_OMP_TARGET_GENERIC_LOOP_DIRECTIVE;
+}
+
 //===----------------------------------------------------------------------===//
 // OpenACC Constructs/Directives.
 //===----------------------------------------------------------------------===//

diff  --git a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
index 1fe3dc0986b886..e19be8c3a7b376 100644
--- a/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
+++ b/clang/lib/StaticAnalyzer/Core/ExprEngine.cpp
@@ -1952,6 +1952,7 @@ void ExprEngine::Visit(const Stmt *S, ExplodedNode *Pred,
     case Stmt::OMPTargetTeamsGenericLoopDirectiveClass:
     case Stmt::OMPParallelGenericLoopDirectiveClass:
     case Stmt::OMPTargetParallelGenericLoopDirectiveClass:
+    case Stmt::OMPTargetGenericLoopDirectiveClass:
     case Stmt::CapturedStmtClass:
     case Stmt::SYCLKernelCallStmtClass:
     case Stmt::UnresolvedSYCLKernelCallStmtClass:

diff  --git a/clang/test/OpenMP/target_generic_loop_ast_print.cpp b/clang/test/OpenMP/target_generic_loop_ast_print.cpp
new file mode 100644
index 00000000000000..db198e7c344812
--- /dev/null
+++ b/clang/test/OpenMP/target_generic_loop_ast_print.cpp
@@ -0,0 +1,133 @@
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fopenmp -fopenmp-version=60 \
+// RUN:   -fsyntax-only -verify %s
+
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fopenmp -fopenmp-version=60 \
+// RUN:   -ast-print %s | FileCheck %s
+
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fopenmp -fopenmp-version=60 \
+// RUN:   -ast-dump %s | FileCheck %s --check-prefix=DUMP
+
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fopenmp -fopenmp-version=60 \
+// RUN:   -emit-pch -o %t %s
+
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -fopenmp -fopenmp-version=60 \
+// RUN:   -include-pch %t -ast-print %s | FileCheck %s
+
+// expected-no-diagnostics
+
+#ifndef HEADER
+#define HEADER
+
+typedef void **omp_allocator_handle_t;
+extern const omp_allocator_handle_t omp_null_allocator;
+extern const omp_allocator_handle_t omp_default_mem_alloc;
+extern const omp_allocator_handle_t omp_large_cap_mem_alloc;
+extern const omp_allocator_handle_t omp_const_mem_alloc;
+extern const omp_allocator_handle_t omp_high_bw_mem_alloc;
+extern const omp_allocator_handle_t omp_low_lat_mem_alloc;
+extern const omp_allocator_handle_t omp_cgroup_mem_alloc;
+extern const omp_allocator_handle_t omp_pteam_mem_alloc;
+extern const omp_allocator_handle_t omp_thread_mem_alloc;
+
+//CHECK: template <typename T, int C, int D> void templ_foo(T t) {
+//CHECK:   T j, z;
+//CHECK:   #pragma omp target loop device(D) collapse(C) reduction(+: z) lastprivate(j) bind(thread) thread_limit(C + 2)
+//CHECK:   for (T i = 0; i < t; ++i)
+//CHECK:       for (j = 0; j < t; ++j)
+//CHECK:           z += i + j;
+//CHECK: }
+
+//CHECK: template<> void templ_foo<int, 2, 0>(int t) {
+//CHECK:     int j, z;
+//CHECK:     #pragma omp target loop device(0) collapse(2) reduction(+: z) lastprivate(j) bind(thread) thread_limit(2 + 2)
+//CHECK:         for (int i = 0; i < t; ++i)
+//CHECK:             for (j = 0; j < t; ++j)
+//CHECK:                 z += i + j;
+//CHECK: }
+template <typename T, int C, int D>
+void templ_foo(T t) {
+
+  T j,z;
+  #pragma omp target loop device(D) collapse(C) reduction(+:z) lastprivate(j) bind(thread) thread_limit(C+2)
+  for (T i = 0; i<t; ++i)
+    for (j = 0; j<t; ++j)
+      z += i+j;
+}
+
+
+//CHECK: void test() {
+void test() {
+  constexpr int N = 100;
+  float MTX[N][N];
+  int aaa[1000];
+
+  //CHECK: #pragma omp target loop map(tofrom: MTX)
+  #pragma omp target loop map(MTX)
+  for (auto j = 0; j < N; ++j) {
+    MTX[0][j] = 0;
+  }
+
+  int j, z, z1;
+  //CHECK: #pragma omp target loop collapse(2) private(z) lastprivate(j) order(concurrent) reduction(+: z1) bind(parallel)
+  #pragma omp target loop collapse(2) private(z) lastprivate(j) \
+                         order(concurrent) reduction(+:z1) bind(parallel)
+  for (auto i = 0; i < N; ++i) {
+    for (j = 0; j < N; ++j) {
+      z = i+j;
+      MTX[i][j] = z;
+      z1 += z;
+    }
+  }
+
+  //CHECK: #pragma omp target loop bind(parallel) thread_limit(16) defaultmap(tofrom: scalar)
+  #pragma omp target loop bind(parallel) thread_limit(16) defaultmap(tofrom:scalar)
+  for (auto i = 0; i < N; ++i) { }
+
+  int pr;
+  int zzz;
+  //CHECK: #pragma omp target loop private(zzz) uses_allocators(omp_default_mem_alloc) allocate(omp_default_mem_alloc: zzz) if(1) device(0) map(tofrom: pr)
+  #pragma omp target loop private(zzz) uses_allocators(omp_default_mem_alloc) allocate(omp_default_mem_alloc:zzz) if(1) device(0) map(tofrom:pr)
+  for (int i=0; i<1000; ++i) {
+    zzz = i + 1;
+    pr = 33;
+  }
+
+  int fpr = 10;
+  int k;
+  //CHECK: #pragma omp target loop bind(thread) private(pr) firstprivate(fpr) allocate(k) reduction(+: k)
+  #pragma omp target loop bind(thread) private(pr) firstprivate(fpr) \
+                        allocate(k)  reduction(+:k)
+  for (auto i = 0; i < N; ++i) {
+    pr = i + fpr;
+  }
+
+  short y = 3;
+  //CHECK: #pragma omp target loop map(tofrom: y) depend(out : y) nowait
+  #pragma omp target loop map(tofrom:y) depend(out:y) nowait
+  for (int i=0; i<10; ++i) {
+    y = 3+i;
+  }
+}
+
+//CHECK: void nobindingfunc() {
+//DUMP-LABEL: FunctionDecl {{.*}} nobindingfunc
+void nobindingfunc()
+{
+  //CHECK: #pragma omp target loop
+  //DUMP: OMPTargetGenericLoopDirective
+  // No implicit bind clause; only task and target capture regions.
+  //DUMP-NEXT: CapturedStmt
+  //DUMP-NEXT: CapturedDecl
+  //DUMP-NEXT: CapturedStmt
+  //DUMP-NEXT: CapturedDecl
+  //DUMP-NEXT: ForStmt
+  #pragma omp target loop
+  for (int i=0; i<10; ++i) { }
+}
+
+void bar()
+{
+  templ_foo<int,2,0>(8);
+}
+
+#endif // HEADER

diff  --git a/clang/test/OpenMP/target_generic_loop_codegen.cpp b/clang/test/OpenMP/target_generic_loop_codegen.cpp
new file mode 100644
index 00000000000000..0dfa3549fef26d
--- /dev/null
+++ b/clang/test/OpenMP/target_generic_loop_codegen.cpp
@@ -0,0 +1,129 @@
+// Check that 'target loop' is lowered like 'target simd'.
+
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=60 -x c++ \
+// RUN:   -triple x86_64-unknown-linux-gnu \
+// RUN:   -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm %s -o - \
+// RUN:   | FileCheck %s --check-prefix=HOST
+
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=60 -x c++ \
+// RUN:   -triple x86_64-unknown-linux-gnu \
+// RUN:   -fopenmp-targets=nvptx64-nvidia-cuda -emit-llvm-bc %s -o %t-host.bc
+// RUN: %clang_cc1 -verify -fopenmp -fopenmp-version=60 -x c++ \
+// RUN:   -triple nvptx64-nvidia-cuda -aux-triple x86_64-unknown-linux-gnu \
+// RUN:   -fopenmp-targets=nvptx64-nvidia-cuda -fopenmp-is-target-device \
+// RUN:   -fopenmp-host-ir-file-path %t-host.bc -emit-llvm %s -o - \
+// RUN:   | FileCheck %s --check-prefix=DEV
+
+// RUN: %clang_cc1 -verify -fopenmp-simd -fopenmp-version=60 -x c++ \
+// RUN:   -triple x86_64-unknown-linux-gnu -emit-llvm %s -o - \
+// RUN:   | FileCheck %s --check-prefix=SIMD \
+// RUN:     --implicit-check-not="{{__kmpc|__tgt|parallel_accesses|vectorize}}"
+
+// expected-no-diagnostics
+
+// One team, one thread, SPMD, with a vectorizable loop.
+// HOST-LABEL: define {{.*}}void @_Z2tlPii(
+// HOST: call i32 @__tgt_target_kernel({{.*}}, i64 -1, i32 1, i32 1,
+// HOST-SAME: ptr @.{{.*}}_Z2tlPii_l{{[0-9]+}}.region_id,
+// HOST: define internal void @{{.*}}_Z2tlPii_l{{[0-9]+}}(
+// HOST: br label %omp.inner.for.cond, !llvm.loop ![[HLOOP1:[0-9]+]]
+
+// DEV: @{{.*}}_Z2tlPii_l{{[0-9]+}}_kernel_environment =
+// DEV-SAME: { i8 0, i8 1, i8 2, i32 1, i32 1, i32 1, i32 1, i32 0 }
+// DEV: @{{.*}}_Z7tl_bindPii_l{{[0-9]+}}_kernel_environment =
+// DEV-SAME: { i8 0, i8 1, i8 2, i32 1, i32 1, i32 1, i32 1, i32 0 }
+// DEV: define {{.*}}void @{{.*}}_Z2tlPii_l{{[0-9]+}}(
+// DEV: br label %omp.inner.for.cond, !llvm.loop ![[DLOOP1:[0-9]+]]
+
+// 'loop' is not a simd construct; -fopenmp-simd emits a plain loop.
+// SIMD-LABEL: define {{.*}}void @_Z2tlPii(
+// SIMD: br label %for.cond, !llvm.loop
+void tl(int *a, int n) {
+#pragma omp target loop map(tofrom: a[0:n])
+  for (int i = 0; i < n; ++i)
+    a[i] += 1;
+}
+
+// bind(parallel) binds to the implicit parallel region of 'target'.
+// HOST-LABEL: define {{.*}}void @_Z7tl_bindPii(
+// HOST: call i32 @__tgt_target_kernel({{.*}}, i64 -1, i32 1, i32 1,
+// HOST-SAME: ptr @.{{.*}}_Z7tl_bindPii_l{{[0-9]+}}.region_id,
+// HOST: define internal void @{{.*}}_Z7tl_bindPii_l{{[0-9]+}}(
+// HOST: br label %omp.inner.for.cond, !llvm.loop ![[HLOOP2:[0-9]+]]
+
+// DEV: define {{.*}}void @{{.*}}_Z7tl_bindPii_l{{[0-9]+}}(
+// DEV: br label %omp.inner.for.cond, !llvm.loop ![[DLOOP2:[0-9]+]]
+
+// SIMD-LABEL: define {{.*}}void @_Z7tl_bindPii(
+// SIMD: br label %for.cond, !llvm.loop
+void tl_bind(int *a, int n) {
+#pragma omp target loop bind(parallel) map(tofrom: a[0:n])
+  for (int i = 0; i < n; ++i)
+    a[i] += 1;
+}
+
+// A nested loop transformation: the target body is a directive, not a loop.
+// HOST-LABEL: define {{.*}}void @_Z7tl_tilePii(
+// HOST: call i32 @__tgt_target_kernel({{.*}}, i64 -1, i32 1, i32 1,
+// HOST-SAME: ptr @.{{.*}}_Z7tl_tilePii_l{{[0-9]+}}.region_id,
+
+// DEV: define {{.*}}void @{{.*}}_Z7tl_tilePii_l{{[0-9]+}}(
+
+// SIMD-LABEL: define {{.*}}void @_Z7tl_tilePii(
+void tl_tile(int *a, int n) {
+#pragma omp target loop map(tofrom: a[0:n])
+#pragma omp tile sizes(4)
+  for (int i = 0; i < n; ++i)
+    a[i] += 1;
+}
+
+// 'if' applies only to 'target', not to the loop.
+// HOST-LABEL: define {{.*}}void @_Z5tl_ifPiii(
+// HOST: br i1 %{{.*}}, label %omp_if.then, label %omp_if.else
+// HOST: define internal void @{{.*}}_Z5tl_ifPiii_l{{[0-9]+}}(
+// HOST-NOT: omp_if
+// HOST: br label %omp.inner.for.cond, !llvm.loop
+// HOST-NOT: omp_if
+// HOST: ret void
+
+// DEV: define {{.*}}void @{{.*}}_Z5tl_ifPiii_l{{[0-9]+}}(
+// DEV-NOT: omp_if
+// DEV: br label %omp.inner.for.cond, !llvm.loop
+// DEV-NOT: omp_if
+// DEV: ret void
+
+// SIMD-LABEL: define {{.*}}void @_Z5tl_ifPiii(
+void tl_if(int *a, int m, int n) {
+#pragma omp target loop if(n > 10) map(tofrom: a[0:m])
+  for (int i = 0; i < m; ++i)
+    a[i] += 1;
+}
+
+// -fopenmp-simd must still privatize 'x'.
+// SIMD-LABEL: define {{.*}}void @_Z10tl_privatePii(
+// SIMD: %x = alloca i32
+// SIMD: %[[XP:x[0-9]+]] = alloca i32
+// SIMD-NOT: store i32 {{.*}}, ptr %x,
+// SIMD: store i32 {{.*}}, ptr %[[XP]],
+void tl_private(int *a, int n) {
+  int x;
+#pragma omp target loop private(x) map(tofrom: a[0:n])
+  for (int i = 0; i < n; ++i) {
+    x = i;
+    a[i] += x;
+  }
+}
+
+// HOST: ![[HLOOP1]] = distinct !{![[HLOOP1]], ![[HPA1:[0-9]+]],
+// HOST-SAME: ![[VEC:[0-9]+]]}
+// HOST: ![[HPA1]] = !{!"llvm.loop.parallel_accesses", !{{[0-9]+}}}
+// HOST: ![[VEC]] = !{!"llvm.loop.vectorize.enable"}
+// HOST: ![[HLOOP2]] = distinct !{![[HLOOP2]], ![[HPA2:[0-9]+]], ![[VEC]]}
+// HOST: ![[HPA2]] = !{!"llvm.loop.parallel_accesses", !{{[0-9]+}}}
+
+// DEV: ![[DLOOP1]] = distinct !{![[DLOOP1]], ![[DPA1:[0-9]+]],
+// DEV-SAME: ![[DVEC:[0-9]+]]}
+// DEV: ![[DPA1]] = !{!"llvm.loop.parallel_accesses", !{{[0-9]+}}}
+// DEV: ![[DVEC]] = !{!"llvm.loop.vectorize.enable"}
+// DEV: ![[DLOOP2]] = distinct !{![[DLOOP2]], ![[DPA2:[0-9]+]], ![[DVEC]]}
+// DEV: ![[DPA2]] = !{!"llvm.loop.parallel_accesses", !{{[0-9]+}}}

diff  --git a/clang/test/OpenMP/target_generic_loop_messages.cpp b/clang/test/OpenMP/target_generic_loop_messages.cpp
new file mode 100644
index 00000000000000..a72a883bb94c91
--- /dev/null
+++ b/clang/test/OpenMP/target_generic_loop_messages.cpp
@@ -0,0 +1,174 @@
+// RUN: %clang_cc1 -triple x86_64-pc-linux-gnu -verify -fopenmp \
+// RUN:  -fopenmp-version=60 -Wuninitialized %s
+
+void foo()
+{
+  int i,j,k;
+  int z;
+
+  // expected-error at +2 {{statement after '#pragma omp target loop' must be a for loop}}
+  #pragma omp target loop bind(thread)
+  i = 0;
+
+  // OpenMP 5.1 [2.22 Nesting of regions]
+  //
+  // A barrier region may not be closely nested inside a worksharing, loop,
+  // task, taskloop, critical, ordered, atomic, or masked region.
+
+  // expected-error at +3 {{region cannot be closely nested inside 'target loop' region}}
+  #pragma omp target loop bind(thread)
+  for (i=0; i<1000; ++i) {
+    #pragma omp barrier
+  }
+
+  // A masked region may not be closely nested inside a worksharing, loop,
+  // atomic, task, or taskloop region.
+
+  // expected-error at +3 {{region cannot be closely nested inside 'target loop' region}}
+  #pragma omp target loop bind(thread)
+  for (i=0; i<1000; ++i) {
+    #pragma omp masked filter(2)
+    { }
+  }
+
+  // An ordered region that corresponds to an ordered construct without any
+  // clause or with the threads or depend clause may not be closely nested
+  // inside a critical, ordered, loop, atomic, task, or taskloop region.
+
+  // expected-error at +3 {{region cannot be closely nested inside 'target loop' region; perhaps you forget to enclose 'omp ordered' directive into a for or a parallel for region with 'ordered' clause?}}
+  #pragma omp target loop bind(thread)
+  for (i=0; i<1000; ++i) {
+    #pragma omp ordered
+    { }
+  }
+
+  // expected-error at +3 {{region cannot be closely nested inside 'target loop' region; perhaps you forget to enclose 'omp ordered' directive into a for or a parallel for region with 'ordered' clause?}}
+  #pragma omp target loop bind(thread)
+  for (i=0; i<1000; ++i) {
+    #pragma omp ordered threads
+    { }
+  }
+
+  // bind clause
+
+  // expected-error at +1 {{directive '#pragma omp target loop' cannot contain more than one 'bind' clause}}
+  #pragma omp target loop bind(thread) bind(thread)
+  for (i=0; i<1000; ++i) {
+  }
+
+  // expected-error at +1 {{expected 'teams', 'parallel' or 'thread' in OpenMP clause 'bind'}}
+  #pragma omp target loop bind(other)
+  for (i=0; i<1000; ++i) {
+  }
+
+  // expected-error at +1 {{region cannot be closely nested inside 'target' region; perhaps you forget to enclose 'omp loop' directive into a teams region?}}
+  #pragma omp target loop bind(teams)
+  for (i=0; i<1000; ++i) {
+  }
+
+  // collapse clause
+
+  // expected-error at +4 {{expected 2 for loops after '#pragma omp target loop', but found only 1}}
+  // expected-note at +1 {{as specified in 'collapse' clause}}
+  #pragma omp target loop collapse(2) bind(thread)
+  for (i=0; i<1000; ++i)
+    z = i+11;
+
+  // expected-error at +1 {{directive '#pragma omp target loop' cannot contain more than one 'collapse' clause}}
+  #pragma omp target loop collapse(2) collapse(2) bind(thread)
+  for (i=0; i<1000; ++i)
+    for (j=0; j<1000; ++j)
+      z = i+j+11;
+
+  // order clause
+
+  // expected-error at +1 {{expected 'concurrent' in OpenMP clause 'order'}}
+  #pragma omp target loop order(foo) bind(thread)
+  for (i=0; i<1000; ++i)
+    z = i+11;
+
+  // private clause
+
+  // expected-error at +1 {{use of undeclared identifier 'undef_var'}}
+  #pragma omp target loop private(undef_var) bind(thread)
+  for (i=0; i<1000; ++i)
+    z = i+11;
+
+  // lastprivate
+
+  // A list item may not appear in a lastprivate clause unless it is the loop
+  // iteration variable of a loop that is associated with the construct.
+
+  // expected-error at +1 {{only loop iteration variables are allowed in 'lastprivate' clause in 'omp target loop' directives}}
+  #pragma omp target loop lastprivate(z) bind(thread)
+  for (i=0; i<1000; ++i) {
+    z = i+11;
+  }
+
+  // expected-error at +1 {{only loop iteration variables are allowed in 'lastprivate' clause in 'omp target loop' directives}}
+  #pragma omp target loop lastprivate(k) collapse(2) bind(thread)
+  for (i=0; i<1000; ++i)
+    for (j=0; j<1000; ++j)
+      for (k=0; k<1000; ++k)
+        z = i+j+k+11;
+
+  // reduction
+
+  // expected-error at +1 {{use of undeclared identifier 'undef_var'}}
+  #pragma omp target loop reduction(+:undef_var) bind(thread)
+  for (i=0; i<1000; ++i)
+    z = i+11;
+
+  // nowait
+
+  // expected-error at +1 {{directive '#pragma omp target loop' cannot contain more than one 'nowait' clause}}
+  #pragma omp target loop nowait nowait
+  for (i=0; i<1000; ++i)
+    z = i+11;
+
+  // thread_limit
+
+  // expected-error at +1 {{directive '#pragma omp target loop' cannot contain more than one 'thread_limit' clause}}
+  #pragma omp target loop thread_limit(4) thread_limit(4)
+  for (i=0; i<1000; ++i)
+    z = i+11;
+
+  // Clauses of 'target parallel loop' that 'target loop' does not accept.
+
+  // expected-error at +1 {{unexpected OpenMP clause 'num_threads' in directive '#pragma omp target loop'}}
+  #pragma omp target loop num_threads(4)
+  for (i=0; i<1000; ++i)
+    z = i+11;
+
+  // expected-error at +1 {{unexpected OpenMP clause 'proc_bind' in directive '#pragma omp target loop'}}
+  #pragma omp target loop proc_bind(close)
+  for (i=0; i<1000; ++i)
+    z = i+11;
+
+  // expected-error at +1 {{unexpected OpenMP clause 'shared' in directive '#pragma omp target loop'}}
+  #pragma omp target loop shared(z)
+  for (i=0; i<1000; ++i)
+    z = i+11;
+}
+
+template <typename T, int C>
+void templ_test(T t) {
+  T i,z;
+
+  // expected-error at +4 {{expected 2 for loops after '#pragma omp target loop', but found only 1}}
+  // expected-note at +1 {{as specified in 'collapse' clause}}
+  #pragma omp target loop collapse(C) bind(thread)
+  for (i=0; i<1000; ++i)
+    z = i+11;
+
+  // expected-error at +1 {{only loop iteration variables are allowed in 'lastprivate' clause in 'omp target loop' directives}}
+  #pragma omp target loop lastprivate(z) bind(thread)
+  for (i=0; i<1000; ++i) {
+    z = i+11;
+  }
+}
+
+void bar()
+{
+  templ_test<int, 2>(16); // expected-note {{in instantiation of function template specialization 'templ_test<int, 2>' requested here}}
+}

diff  --git a/clang/tools/libclang/CIndex.cpp b/clang/tools/libclang/CIndex.cpp
index 8d246d41f31f66..a80a61f6492767 100644
--- a/clang/tools/libclang/CIndex.cpp
+++ b/clang/tools/libclang/CIndex.cpp
@@ -6522,6 +6522,8 @@ CXString clang_getCursorKindSpelling(enum CXCursorKind Kind) {
     return cxstring::createRef("OMPParallelGenericLoopDirective");
   case CXCursor_OMPTargetParallelGenericLoopDirective:
     return cxstring::createRef("OMPTargetParallelGenericLoopDirective");
+  case CXCursor_OMPTargetGenericLoopDirective:
+    return cxstring::createRef("OMPTargetGenericLoopDirective");
   case CXCursor_OverloadCandidate:
     return cxstring::createRef("OverloadCandidate");
   case CXCursor_TypeAliasTemplateDecl:

diff  --git a/clang/tools/libclang/CXCursor.cpp b/clang/tools/libclang/CXCursor.cpp
index e042e12ea4c062..7bfa848a1cf866 100644
--- a/clang/tools/libclang/CXCursor.cpp
+++ b/clang/tools/libclang/CXCursor.cpp
@@ -959,6 +959,9 @@ CXCursor cxcursor::MakeCXCursor(const Stmt *S, const Decl *Parent,
   case Stmt::OMPTargetParallelGenericLoopDirectiveClass:
     K = CXCursor_OMPTargetParallelGenericLoopDirective;
     break;
+  case Stmt::OMPTargetGenericLoopDirectiveClass:
+    K = CXCursor_OMPTargetGenericLoopDirective;
+    break;
   case Stmt::BuiltinBitCastExprClass:
     K = CXCursor_BuiltinBitCastExpr;
     break;


        


More information about the cfe-commits mailing list