blob: df76b42ad7d4217393dc57d5300ef8f9ae1bddfd [file] [log] [blame]
Alexey Bataev9959db52014-05-06 10:08:46 +00001//===--- SemaOpenMP.cpp - Semantic Analysis for OpenMP constructs ---------===//
Alexey Bataeva769e072013-03-22 06:34:35 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexey Bataeva769e072013-03-22 06:34:35 +00006//
7//===----------------------------------------------------------------------===//
8/// \file
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00009/// This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000010/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000011///
12//===----------------------------------------------------------------------===//
13
Alexey Bataevb08f89f2015-08-14 12:25:37 +000014#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000015#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000016#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000017#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000018#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000019#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000020#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000021#include "clang/AST/StmtCXX.h"
22#include "clang/AST/StmtOpenMP.h"
23#include "clang/AST/StmtVisitor.h"
Patrick Lystere13b1e32019-01-02 19:28:48 +000024#include "clang/AST/TypeOrdering.h"
Alexey Bataevcb8e6912020-01-31 16:09:26 -050025#include "clang/Basic/DiagnosticSema.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000026#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev0ee89c12019-12-12 14:13:02 -050027#include "clang/Basic/PartialDiagnostic.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000028#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000029#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000030#include "clang/Sema/Scope.h"
31#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000032#include "clang/Sema/SemaInternal.h"
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060033#include "llvm/ADT/IndexedMap.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000034#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataev36635632020-01-17 20:39:04 -050035#include "llvm/ADT/STLExtras.h"
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060036#include "llvm/Frontend/OpenMP/OMPConstants.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000037using namespace clang;
Johannes Doerferteb3e81f2019-11-04 22:00:49 -060038using namespace llvm::omp;
Alexey Bataeva769e072013-03-22 06:34:35 +000039
Alexey Bataev758e55e2013-09-06 18:03:48 +000040//===----------------------------------------------------------------------===//
41// Stack of data-sharing attributes for variables
42//===----------------------------------------------------------------------===//
43
Alexey Bataeve3727102018-04-18 15:57:46 +000044static const Expr *checkMapClauseExpressionBase(
Alexey Bataevf47c4b42017-09-26 13:47:31 +000045 Sema &SemaRef, Expr *E,
46 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000047 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000048
Alexey Bataev758e55e2013-09-06 18:03:48 +000049namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000050/// Default data sharing attributes, which can be applied to directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +000051enum DefaultDataSharingAttributes {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000052 DSA_unspecified = 0, /// Data sharing attribute not specified.
53 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
54 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000055};
56
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000057/// Stack for tracking declarations used in OpenMP directives and
Alexey Bataev758e55e2013-09-06 18:03:48 +000058/// clauses and their data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000059class DSAStackTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +000060public:
Alexey Bataeve3727102018-04-18 15:57:46 +000061 struct DSAVarData {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000062 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
Alexey Bataeve3727102018-04-18 15:57:46 +000064 const Expr *RefExpr = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000065 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000066 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000067 DSAVarData() = default;
Alexey Bataeve3727102018-04-18 15:57:46 +000068 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
69 const Expr *RefExpr, DeclRefExpr *PrivateCopy,
70 SourceLocation ImplicitDSALoc)
Alexey Bataevf189cb72017-07-24 14:52:13 +000071 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
72 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000073 };
Alexey Bataeve3727102018-04-18 15:57:46 +000074 using OperatorOffsetTy =
75 llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>;
Alexey Bataevf138fda2018-08-13 19:04:24 +000076 using DoacrossDependMapTy =
77 llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>;
Alexey Bataeved09d242014-05-28 05:53:51 +000078
Alexey Bataev758e55e2013-09-06 18:03:48 +000079private:
Alexey Bataeve3727102018-04-18 15:57:46 +000080 struct DSAInfo {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000081 OpenMPClauseKind Attributes = OMPC_unknown;
82 /// Pointer to a reference expression and a flag which shows that the
83 /// variable is marked as lastprivate(true) or not (false).
Alexey Bataeve3727102018-04-18 15:57:46 +000084 llvm::PointerIntPair<const Expr *, 1, bool> RefExpr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000085 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000086 };
Alexey Bataeve3727102018-04-18 15:57:46 +000087 using DeclSAMapTy = llvm::SmallDenseMap<const ValueDecl *, DSAInfo, 8>;
Alexey Bataevb6e70842019-12-16 15:54:17 -050088 using UsedRefMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
Alexey Bataeve3727102018-04-18 15:57:46 +000089 using LCDeclInfo = std::pair<unsigned, VarDecl *>;
90 using LoopControlVariablesMapTy =
91 llvm::SmallDenseMap<const ValueDecl *, LCDeclInfo, 8>;
Samuel Antao6890b092016-07-28 14:25:09 +000092 /// Struct that associates a component with the clause kind where they are
93 /// found.
94 struct MappedExprComponentTy {
95 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
96 OpenMPClauseKind Kind = OMPC_unknown;
97 };
Alexey Bataeve3727102018-04-18 15:57:46 +000098 using MappedExprComponentsTy =
99 llvm::DenseMap<const ValueDecl *, MappedExprComponentTy>;
100 using CriticalsWithHintsTy =
101 llvm::StringMap<std::pair<const OMPCriticalDirective *, llvm::APSInt>>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000102 struct ReductionData {
Alexey Bataeve3727102018-04-18 15:57:46 +0000103 using BOKPtrType = llvm::PointerEmbeddedInt<BinaryOperatorKind, 16>;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000104 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000105 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000106 ReductionData() = default;
107 void set(BinaryOperatorKind BO, SourceRange RR) {
108 ReductionRange = RR;
109 ReductionOp = BO;
110 }
111 void set(const Expr *RefExpr, SourceRange RR) {
112 ReductionRange = RR;
113 ReductionOp = RefExpr;
114 }
115 };
Alexey Bataeve3727102018-04-18 15:57:46 +0000116 using DeclReductionMapTy =
117 llvm::SmallDenseMap<const ValueDecl *, ReductionData, 4>;
cchene06f3e02019-11-15 13:02:06 -0500118 struct DefaultmapInfo {
119 OpenMPDefaultmapClauseModifier ImplicitBehavior =
120 OMPC_DEFAULTMAP_MODIFIER_unknown;
121 SourceLocation SLoc;
122 DefaultmapInfo() = default;
123 DefaultmapInfo(OpenMPDefaultmapClauseModifier M, SourceLocation Loc)
124 : ImplicitBehavior(M), SLoc(Loc) {}
125 };
Alexey Bataev758e55e2013-09-06 18:03:48 +0000126
Alexey Bataeve3727102018-04-18 15:57:46 +0000127 struct SharingMapTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000128 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000129 DeclReductionMapTy ReductionMap;
Alexey Bataevb6e70842019-12-16 15:54:17 -0500130 UsedRefMapTy AlignedMap;
131 UsedRefMapTy NontemporalMap;
Samuel Antao90927002016-04-26 14:54:23 +0000132 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000133 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000134 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000135 SourceLocation DefaultAttrLoc;
cchene06f3e02019-11-15 13:02:06 -0500136 DefaultmapInfo DefaultmapMap[OMPC_DEFAULTMAP_unknown];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000137 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000138 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000139 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000140 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000141 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
142 /// get the data (loop counters etc.) about enclosing loop-based construct.
143 /// This data is required during codegen.
144 DoacrossDependMapTy DoacrossDepends;
Patrick Lyster16471942019-02-06 18:18:02 +0000145 /// First argument (Expr *) contains optional argument of the
Alexey Bataev346265e2015-09-25 10:37:12 +0000146 /// 'ordered' clause, the second one is true if the regions has 'ordered'
147 /// clause, false otherwise.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000148 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000149 unsigned AssociatedLoops = 1;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000150 bool HasMutipleLoops = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000151 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000152 bool NowaitRegion = false;
153 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000154 bool LoopStart = false;
Richard Smith0621a8f2019-05-31 00:45:10 +0000155 bool BodyComplete = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000156 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000157 /// Reference to the taskgroup task_reduction reference expression.
158 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000159 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataevf3c508f2020-01-23 10:47:16 -0500160 SmallVector<Expr *, 4> InnerUsedAllocators;
Alexey Bataeva495c642019-03-11 19:51:42 +0000161 /// List of globals marked as declare target link in this target region
162 /// (isOpenMPTargetExecutionDirective(Directive) == true).
163 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
Alexey Bataeved09d242014-05-28 05:53:51 +0000164 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000165 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000166 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
167 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000168 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000169 };
170
Alexey Bataeve3727102018-04-18 15:57:46 +0000171 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000172
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000173 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000174 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000175 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
176 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000177 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000178 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000179 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000180 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000181 bool ForceCapturing = false;
Alexey Bataevd1caf932019-09-30 14:05:26 +0000182 /// true if all the variables in the target executable directives must be
Alexey Bataev60705422018-10-30 15:50:12 +0000183 /// captured by reference.
184 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000185 CriticalsWithHintsTy Criticals;
Richard Smith0621a8f2019-05-31 00:45:10 +0000186 unsigned IgnoredStackElements = 0;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000187
Richard Smith375dec52019-05-30 23:21:14 +0000188 /// Iterators over the stack iterate in order from innermost to outermost
189 /// directive.
190 using const_iterator = StackTy::const_reverse_iterator;
191 const_iterator begin() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000192 return Stack.empty() ? const_iterator()
193 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000194 }
195 const_iterator end() const {
196 return Stack.empty() ? const_iterator() : Stack.back().first.rend();
197 }
198 using iterator = StackTy::reverse_iterator;
199 iterator begin() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000200 return Stack.empty() ? iterator()
201 : Stack.back().first.rbegin() + IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000202 }
203 iterator end() {
204 return Stack.empty() ? iterator() : Stack.back().first.rend();
205 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000206
Richard Smith375dec52019-05-30 23:21:14 +0000207 // Convenience operations to get at the elements of the stack.
Alexey Bataeved09d242014-05-28 05:53:51 +0000208
Alexey Bataev4b465392017-04-26 15:06:24 +0000209 bool isStackEmpty() const {
210 return Stack.empty() ||
211 Stack.back().second != CurrentNonCapturingFunctionScope ||
Richard Smith0621a8f2019-05-31 00:45:10 +0000212 Stack.back().first.size() <= IgnoredStackElements;
Alexey Bataev4b465392017-04-26 15:06:24 +0000213 }
Richard Smith375dec52019-05-30 23:21:14 +0000214 size_t getStackSize() const {
Richard Smith0621a8f2019-05-31 00:45:10 +0000215 return isStackEmpty() ? 0
216 : Stack.back().first.size() - IgnoredStackElements;
Richard Smith375dec52019-05-30 23:21:14 +0000217 }
218
219 SharingMapTy *getTopOfStackOrNull() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000220 size_t Size = getStackSize();
221 if (Size == 0)
Richard Smith375dec52019-05-30 23:21:14 +0000222 return nullptr;
Richard Smith0621a8f2019-05-31 00:45:10 +0000223 return &Stack.back().first[Size - 1];
Richard Smith375dec52019-05-30 23:21:14 +0000224 }
225 const SharingMapTy *getTopOfStackOrNull() const {
226 return const_cast<DSAStackTy&>(*this).getTopOfStackOrNull();
227 }
228 SharingMapTy &getTopOfStack() {
229 assert(!isStackEmpty() && "no current directive");
230 return *getTopOfStackOrNull();
231 }
232 const SharingMapTy &getTopOfStack() const {
233 return const_cast<DSAStackTy&>(*this).getTopOfStack();
234 }
235
236 SharingMapTy *getSecondOnStackOrNull() {
237 size_t Size = getStackSize();
238 if (Size <= 1)
239 return nullptr;
240 return &Stack.back().first[Size - 2];
241 }
242 const SharingMapTy *getSecondOnStackOrNull() const {
243 return const_cast<DSAStackTy&>(*this).getSecondOnStackOrNull();
244 }
245
246 /// Get the stack element at a certain level (previously returned by
247 /// \c getNestingLevel).
248 ///
249 /// Note that nesting levels count from outermost to innermost, and this is
250 /// the reverse of our iteration order where new inner levels are pushed at
251 /// the front of the stack.
252 SharingMapTy &getStackElemAtLevel(unsigned Level) {
253 assert(Level < getStackSize() && "no such stack element");
254 return Stack.back().first[Level];
255 }
256 const SharingMapTy &getStackElemAtLevel(unsigned Level) const {
257 return const_cast<DSAStackTy&>(*this).getStackElemAtLevel(Level);
258 }
259
260 DSAVarData getDSA(const_iterator &Iter, ValueDecl *D) const;
261
262 /// Checks if the variable is a local for OpenMP region.
263 bool isOpenMPLocal(VarDecl *D, const_iterator Iter) const;
Alexey Bataev4b465392017-04-26 15:06:24 +0000264
Kelvin Li1408f912018-09-26 04:28:39 +0000265 /// Vector of previously declared requires directives
266 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
Alexey Bataev27ef9512019-03-20 20:14:22 +0000267 /// omp_allocator_handle_t type.
268 QualType OMPAllocatorHandleT;
269 /// Expression for the predefined allocators.
270 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
271 nullptr};
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000272 /// Vector of previously encountered target directives
273 SmallVector<SourceLocation, 2> TargetLocations;
Kelvin Li1408f912018-09-26 04:28:39 +0000274
Alexey Bataev758e55e2013-09-06 18:03:48 +0000275public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000276 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000277
Alexey Bataev27ef9512019-03-20 20:14:22 +0000278 /// Sets omp_allocator_handle_t type.
279 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
280 /// Gets omp_allocator_handle_t type.
281 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
282 /// Sets the given default allocator.
283 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
284 Expr *Allocator) {
285 OMPPredefinedAllocators[AllocatorKind] = Allocator;
286 }
287 /// Returns the specified default allocator.
288 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
289 return OMPPredefinedAllocators[AllocatorKind];
290 }
291
Alexey Bataevaac108a2015-06-23 04:51:00 +0000292 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000293 OpenMPClauseKind getClauseParsingMode() const {
294 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
295 return ClauseKindMode;
296 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000297 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000298
Richard Smith0621a8f2019-05-31 00:45:10 +0000299 bool isBodyComplete() const {
300 const SharingMapTy *Top = getTopOfStackOrNull();
301 return Top && Top->BodyComplete;
302 }
303 void setBodyComplete() {
304 getTopOfStack().BodyComplete = true;
305 }
306
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000307 bool isForceVarCapturing() const { return ForceCapturing; }
308 void setForceVarCapturing(bool V) { ForceCapturing = V; }
309
Alexey Bataev60705422018-10-30 15:50:12 +0000310 void setForceCaptureByReferenceInTargetExecutable(bool V) {
311 ForceCaptureByReferenceInTargetExecutable = V;
312 }
313 bool isForceCaptureByReferenceInTargetExecutable() const {
314 return ForceCaptureByReferenceInTargetExecutable;
315 }
316
Alexey Bataev758e55e2013-09-06 18:03:48 +0000317 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000318 Scope *CurScope, SourceLocation Loc) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000319 assert(!IgnoredStackElements &&
320 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000321 if (Stack.empty() ||
322 Stack.back().second != CurrentNonCapturingFunctionScope)
323 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
324 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
325 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000326 }
327
328 void pop() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000329 assert(!IgnoredStackElements &&
330 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000331 assert(!Stack.back().first.empty() &&
332 "Data-sharing attributes stack is empty!");
333 Stack.back().first.pop_back();
334 }
335
Richard Smith0621a8f2019-05-31 00:45:10 +0000336 /// RAII object to temporarily leave the scope of a directive when we want to
337 /// logically operate in its parent.
338 class ParentDirectiveScope {
339 DSAStackTy &Self;
340 bool Active;
341 public:
342 ParentDirectiveScope(DSAStackTy &Self, bool Activate)
343 : Self(Self), Active(false) {
344 if (Activate)
345 enable();
346 }
347 ~ParentDirectiveScope() { disable(); }
348 void disable() {
349 if (Active) {
350 --Self.IgnoredStackElements;
351 Active = false;
352 }
353 }
354 void enable() {
355 if (!Active) {
356 ++Self.IgnoredStackElements;
357 Active = true;
358 }
359 }
360 };
361
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000362 /// Marks that we're started loop parsing.
363 void loopInit() {
364 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
365 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000366 getTopOfStack().LoopStart = true;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000367 }
368 /// Start capturing of the variables in the loop context.
369 void loopStart() {
370 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
371 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000372 getTopOfStack().LoopStart = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000373 }
374 /// true, if variables are captured, false otherwise.
375 bool isLoopStarted() const {
376 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
377 "Expected loop-based directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000378 return !getTopOfStack().LoopStart;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000379 }
380 /// Marks (or clears) declaration as possibly loop counter.
381 void resetPossibleLoopCounter(const Decl *D = nullptr) {
Richard Smith375dec52019-05-30 23:21:14 +0000382 getTopOfStack().PossiblyLoopCounter =
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000383 D ? D->getCanonicalDecl() : D;
384 }
385 /// Gets the possible loop counter decl.
386 const Decl *getPossiblyLoopCunter() const {
Richard Smith375dec52019-05-30 23:21:14 +0000387 return getTopOfStack().PossiblyLoopCounter;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000388 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000389 /// Start new OpenMP region stack in new non-capturing function.
390 void pushFunction() {
Richard Smith0621a8f2019-05-31 00:45:10 +0000391 assert(!IgnoredStackElements &&
392 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000393 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
394 assert(!isa<CapturingScopeInfo>(CurFnScope));
395 CurrentNonCapturingFunctionScope = CurFnScope;
396 }
397 /// Pop region stack for non-capturing function.
398 void popFunction(const FunctionScopeInfo *OldFSI) {
Richard Smith0621a8f2019-05-31 00:45:10 +0000399 assert(!IgnoredStackElements &&
400 "cannot change stack while ignoring elements");
Alexey Bataev4b465392017-04-26 15:06:24 +0000401 if (!Stack.empty() && Stack.back().second == OldFSI) {
402 assert(Stack.back().first.empty());
403 Stack.pop_back();
404 }
405 CurrentNonCapturingFunctionScope = nullptr;
406 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
407 if (!isa<CapturingScopeInfo>(FSI)) {
408 CurrentNonCapturingFunctionScope = FSI;
409 break;
410 }
411 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000412 }
413
Alexey Bataeve3727102018-04-18 15:57:46 +0000414 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000415 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000416 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000417 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000418 getCriticalWithHint(const DeclarationNameInfo &Name) const {
419 auto I = Criticals.find(Name.getAsString());
420 if (I != Criticals.end())
421 return I->second;
422 return std::make_pair(nullptr, llvm::APSInt());
423 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000424 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000425 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000426 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000427 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexey Bataevb6e70842019-12-16 15:54:17 -0500428 /// If 'nontemporal' declaration for given variable \a D was not seen yet,
429 /// add it and return NULL; otherwise return previous occurrence's expression
430 /// for diagnostics.
431 const Expr *addUniqueNontemporal(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000432
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000433 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000434 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000435 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000436 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000437 /// \return The index of the loop control variable in the list of associated
438 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000439 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000440 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000441 /// parent region.
442 /// \return The index of the loop control variable in the list of associated
443 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000444 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000445 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000446 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000447 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000448
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000449 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000450 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000451 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000452
Alexey Bataevfa312f32017-07-21 18:48:21 +0000453 /// Adds additional information for the reduction items with the reduction id
454 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000455 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000456 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000457 /// Adds additional information for the reduction items with the reduction id
458 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000459 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000460 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000461 /// Returns the location and reduction operation from the innermost parent
462 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000463 const DSAVarData
464 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
465 BinaryOperatorKind &BOK,
466 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000467 /// Returns the location and reduction operation from the innermost parent
468 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000469 const DSAVarData
470 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
471 const Expr *&ReductionRef,
472 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000473 /// Return reduction reference expression for the current taskgroup.
474 Expr *getTaskgroupReductionRef() const {
Richard Smith375dec52019-05-30 23:21:14 +0000475 assert(getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000476 "taskgroup reference expression requested for non taskgroup "
477 "directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000478 return getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000479 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000480 /// Checks if the given \p VD declaration is actually a taskgroup reduction
481 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000482 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +0000483 return getStackElemAtLevel(Level).TaskgroupReductionRef &&
484 cast<DeclRefExpr>(getStackElemAtLevel(Level).TaskgroupReductionRef)
Alexey Bataev88202be2017-07-27 13:20:36 +0000485 ->getDecl() == VD;
486 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000487
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000488 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000489 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000490 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000491 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000492 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000493 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000494 /// match specified \a CPred predicate in any directive which matches \a DPred
495 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000496 const DSAVarData
497 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
498 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
499 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000500 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000501 /// match specified \a CPred predicate in any innermost directive which
502 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000503 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000504 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000505 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
506 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000507 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000508 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000509 /// attributes which match specified \a CPred predicate at the specified
510 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000511 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000512 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000513 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000514
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000515 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000516 /// specified \a DPred predicate.
517 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000518 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000519 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000520
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000521 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000522 bool hasDirective(
523 const llvm::function_ref<bool(
524 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
525 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000526 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000527
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000528 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000529 OpenMPDirectiveKind getCurrentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000530 const SharingMapTy *Top = getTopOfStackOrNull();
531 return Top ? Top->Directive : OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000532 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000533 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000534 OpenMPDirectiveKind getDirective(unsigned Level) const {
535 assert(!isStackEmpty() && "No directive at specified level.");
Richard Smith375dec52019-05-30 23:21:14 +0000536 return getStackElemAtLevel(Level).Directive;
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000537 }
Joel E. Denny7d5bc552019-08-22 03:34:30 +0000538 /// Returns the capture region at the specified level.
539 OpenMPDirectiveKind getCaptureRegion(unsigned Level,
540 unsigned OpenMPCaptureLevel) const {
541 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
542 getOpenMPCaptureRegions(CaptureRegions, getDirective(Level));
543 return CaptureRegions[OpenMPCaptureLevel];
544 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000545 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000546 OpenMPDirectiveKind getParentDirective() const {
Richard Smith375dec52019-05-30 23:21:14 +0000547 const SharingMapTy *Parent = getSecondOnStackOrNull();
548 return Parent ? Parent->Directive : OMPD_unknown;
Alexey Bataev549210e2014-06-24 04:39:47 +0000549 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000550
Kelvin Li1408f912018-09-26 04:28:39 +0000551 /// Add requires decl to internal vector
552 void addRequiresDecl(OMPRequiresDecl *RD) {
553 RequiresDecls.push_back(RD);
554 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000555
Alexey Bataev318f431b2019-03-22 15:25:12 +0000556 /// Checks if the defined 'requires' directive has specified type of clause.
557 template <typename ClauseType>
558 bool hasRequiresDeclWithClause() {
559 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
560 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
561 return isa<ClauseType>(C);
562 });
563 });
564 }
565
Kelvin Li1408f912018-09-26 04:28:39 +0000566 /// Checks for a duplicate clause amongst previously declared requires
567 /// directives
568 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
569 bool IsDuplicate = false;
570 for (OMPClause *CNew : ClauseList) {
571 for (const OMPRequiresDecl *D : RequiresDecls) {
572 for (const OMPClause *CPrev : D->clauselists()) {
573 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
574 SemaRef.Diag(CNew->getBeginLoc(),
575 diag::err_omp_requires_clause_redeclaration)
576 << getOpenMPClauseName(CNew->getClauseKind());
577 SemaRef.Diag(CPrev->getBeginLoc(),
578 diag::note_omp_requires_previous_clause)
579 << getOpenMPClauseName(CPrev->getClauseKind());
580 IsDuplicate = true;
581 }
582 }
583 }
584 }
585 return IsDuplicate;
586 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000587
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000588 /// Add location of previously encountered target to internal vector
589 void addTargetDirLocation(SourceLocation LocStart) {
590 TargetLocations.push_back(LocStart);
591 }
592
593 // Return previously encountered target region locations.
594 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
595 return TargetLocations;
596 }
597
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000598 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000599 void setDefaultDSANone(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000600 getTopOfStack().DefaultAttr = DSA_none;
601 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000602 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000603 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000604 void setDefaultDSAShared(SourceLocation Loc) {
Richard Smith375dec52019-05-30 23:21:14 +0000605 getTopOfStack().DefaultAttr = DSA_shared;
606 getTopOfStack().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000607 }
cchene06f3e02019-11-15 13:02:06 -0500608 /// Set default data mapping attribute to Modifier:Kind
609 void setDefaultDMAAttr(OpenMPDefaultmapClauseModifier M,
610 OpenMPDefaultmapClauseKind Kind,
611 SourceLocation Loc) {
612 DefaultmapInfo &DMI = getTopOfStack().DefaultmapMap[Kind];
613 DMI.ImplicitBehavior = M;
614 DMI.SLoc = Loc;
615 }
616 /// Check whether the implicit-behavior has been set in defaultmap
617 bool checkDefaultmapCategory(OpenMPDefaultmapClauseKind VariableCategory) {
618 return getTopOfStack().DefaultmapMap[VariableCategory].ImplicitBehavior !=
619 OMPC_DEFAULTMAP_MODIFIER_unknown;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000620 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000621
622 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000623 return isStackEmpty() ? DSA_unspecified
Richard Smith375dec52019-05-30 23:21:14 +0000624 : getTopOfStack().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000625 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000626 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000627 return isStackEmpty() ? SourceLocation()
Richard Smith375dec52019-05-30 23:21:14 +0000628 : getTopOfStack().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000629 }
cchene06f3e02019-11-15 13:02:06 -0500630 OpenMPDefaultmapClauseModifier
631 getDefaultmapModifier(OpenMPDefaultmapClauseKind Kind) const {
632 return isStackEmpty()
633 ? OMPC_DEFAULTMAP_MODIFIER_unknown
634 : getTopOfStack().DefaultmapMap[Kind].ImplicitBehavior;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000635 }
cchene06f3e02019-11-15 13:02:06 -0500636 OpenMPDefaultmapClauseModifier
637 getDefaultmapModifierAtLevel(unsigned Level,
638 OpenMPDefaultmapClauseKind Kind) const {
639 return getStackElemAtLevel(Level).DefaultmapMap[Kind].ImplicitBehavior;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000640 }
cchene06f3e02019-11-15 13:02:06 -0500641 bool isDefaultmapCapturedByRef(unsigned Level,
642 OpenMPDefaultmapClauseKind Kind) const {
643 OpenMPDefaultmapClauseModifier M =
644 getDefaultmapModifierAtLevel(Level, Kind);
645 if (Kind == OMPC_DEFAULTMAP_scalar || Kind == OMPC_DEFAULTMAP_pointer) {
646 return (M == OMPC_DEFAULTMAP_MODIFIER_alloc) ||
647 (M == OMPC_DEFAULTMAP_MODIFIER_to) ||
648 (M == OMPC_DEFAULTMAP_MODIFIER_from) ||
649 (M == OMPC_DEFAULTMAP_MODIFIER_tofrom);
650 }
651 return true;
652 }
653 static bool mustBeFirstprivateBase(OpenMPDefaultmapClauseModifier M,
654 OpenMPDefaultmapClauseKind Kind) {
655 switch (Kind) {
656 case OMPC_DEFAULTMAP_scalar:
657 case OMPC_DEFAULTMAP_pointer:
658 return (M == OMPC_DEFAULTMAP_MODIFIER_unknown) ||
659 (M == OMPC_DEFAULTMAP_MODIFIER_firstprivate) ||
660 (M == OMPC_DEFAULTMAP_MODIFIER_default);
661 case OMPC_DEFAULTMAP_aggregate:
662 return M == OMPC_DEFAULTMAP_MODIFIER_firstprivate;
Simon Pilgrim1e3cc062019-11-18 11:42:14 +0000663 default:
664 break;
cchene06f3e02019-11-15 13:02:06 -0500665 }
Simon Pilgrim1e3cc062019-11-18 11:42:14 +0000666 llvm_unreachable("Unexpected OpenMPDefaultmapClauseKind enum");
cchene06f3e02019-11-15 13:02:06 -0500667 }
668 bool mustBeFirstprivateAtLevel(unsigned Level,
669 OpenMPDefaultmapClauseKind Kind) const {
670 OpenMPDefaultmapClauseModifier M =
671 getDefaultmapModifierAtLevel(Level, Kind);
672 return mustBeFirstprivateBase(M, Kind);
673 }
674 bool mustBeFirstprivate(OpenMPDefaultmapClauseKind Kind) const {
675 OpenMPDefaultmapClauseModifier M = getDefaultmapModifier(Kind);
676 return mustBeFirstprivateBase(M, Kind);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000677 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000678
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000679 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000680 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000681 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000682 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000683 }
684
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000685 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000686 void setOrderedRegion(bool IsOrdered, const Expr *Param,
687 OMPOrderedClause *Clause) {
Alexey Bataevf138fda2018-08-13 19:04:24 +0000688 if (IsOrdered)
Richard Smith375dec52019-05-30 23:21:14 +0000689 getTopOfStack().OrderedRegion.emplace(Param, Clause);
Alexey Bataevf138fda2018-08-13 19:04:24 +0000690 else
Richard Smith375dec52019-05-30 23:21:14 +0000691 getTopOfStack().OrderedRegion.reset();
Alexey Bataevf138fda2018-08-13 19:04:24 +0000692 }
693 /// Returns true, if region is ordered (has associated 'ordered' clause),
694 /// false - otherwise.
695 bool isOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000696 if (const SharingMapTy *Top = getTopOfStackOrNull())
697 return Top->OrderedRegion.hasValue();
698 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000699 }
700 /// Returns optional parameter for the ordered region.
701 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000702 if (const SharingMapTy *Top = getTopOfStackOrNull())
703 if (Top->OrderedRegion.hasValue())
704 return Top->OrderedRegion.getValue();
705 return std::make_pair(nullptr, nullptr);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000706 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000707 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000708 /// 'ordered' clause), false - otherwise.
709 bool isParentOrderedRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000710 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
711 return Parent->OrderedRegion.hasValue();
712 return false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000713 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000714 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000715 std::pair<const Expr *, OMPOrderedClause *>
716 getParentOrderedRegionParam() const {
Richard Smith375dec52019-05-30 23:21:14 +0000717 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
718 if (Parent->OrderedRegion.hasValue())
719 return Parent->OrderedRegion.getValue();
720 return std::make_pair(nullptr, nullptr);
Alexey Bataev346265e2015-09-25 10:37:12 +0000721 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000722 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000723 void setNowaitRegion(bool IsNowait = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000724 getTopOfStack().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000725 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000726 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000727 /// 'nowait' clause), false - otherwise.
728 bool isParentNowaitRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000729 if (const SharingMapTy *Parent = getSecondOnStackOrNull())
730 return Parent->NowaitRegion;
731 return false;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000732 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000733 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000734 void setParentCancelRegion(bool Cancel = true) {
Richard Smith375dec52019-05-30 23:21:14 +0000735 if (SharingMapTy *Parent = getSecondOnStackOrNull())
736 Parent->CancelRegion |= Cancel;
Alexey Bataev25e5b442015-09-15 12:52:43 +0000737 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000738 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000739 bool isCancelRegion() const {
Richard Smith375dec52019-05-30 23:21:14 +0000740 const SharingMapTy *Top = getTopOfStackOrNull();
741 return Top ? Top->CancelRegion : false;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000742 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000743
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000744 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000745 void setAssociatedLoops(unsigned Val) {
Richard Smith375dec52019-05-30 23:21:14 +0000746 getTopOfStack().AssociatedLoops = Val;
Alexey Bataev05be1da2019-07-18 17:49:13 +0000747 if (Val > 1)
748 getTopOfStack().HasMutipleLoops = true;
Alexey Bataev4b465392017-04-26 15:06:24 +0000749 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000750 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000751 unsigned getAssociatedLoops() const {
Richard Smith375dec52019-05-30 23:21:14 +0000752 const SharingMapTy *Top = getTopOfStackOrNull();
753 return Top ? Top->AssociatedLoops : 0;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000754 }
Alexey Bataev05be1da2019-07-18 17:49:13 +0000755 /// Returns true if the construct is associated with multiple loops.
756 bool hasMutipleLoops() const {
757 const SharingMapTy *Top = getTopOfStackOrNull();
758 return Top ? Top->HasMutipleLoops : false;
759 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000760
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000761 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000762 /// region.
763 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Richard Smith375dec52019-05-30 23:21:14 +0000764 if (SharingMapTy *Parent = getSecondOnStackOrNull())
765 Parent->InnerTeamsRegionLoc = TeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000766 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000767 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000768 bool hasInnerTeamsRegion() const {
769 return getInnerTeamsRegionLoc().isValid();
770 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000771 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000772 SourceLocation getInnerTeamsRegionLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000773 const SharingMapTy *Top = getTopOfStackOrNull();
774 return Top ? Top->InnerTeamsRegionLoc : SourceLocation();
Alexey Bataev13314bf2014-10-09 04:18:56 +0000775 }
776
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000777 Scope *getCurScope() const {
Richard Smith375dec52019-05-30 23:21:14 +0000778 const SharingMapTy *Top = getTopOfStackOrNull();
779 return Top ? Top->CurScope : nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000780 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000781 SourceLocation getConstructLoc() const {
Richard Smith375dec52019-05-30 23:21:14 +0000782 const SharingMapTy *Top = getTopOfStackOrNull();
783 return Top ? Top->ConstructLoc : SourceLocation();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000784 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000785
Samuel Antao4c8035b2016-12-12 18:00:20 +0000786 /// Do the check specified in \a Check to all component lists and return true
787 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000788 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000789 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000790 const llvm::function_ref<
791 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000792 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000793 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000794 if (isStackEmpty())
795 return false;
Richard Smith375dec52019-05-30 23:21:14 +0000796 auto SI = begin();
797 auto SE = end();
Samuel Antao5de996e2016-01-22 20:21:36 +0000798
799 if (SI == SE)
800 return false;
801
Alexey Bataeve3727102018-04-18 15:57:46 +0000802 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000803 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000804 else
805 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000806
807 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000808 auto MI = SI->MappedExprComponents.find(VD);
809 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000810 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
811 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000812 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000813 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000814 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000815 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000816 }
817
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000818 /// Do the check specified in \a Check to all component lists at a given level
819 /// and return true if any issue is found.
820 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000821 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000822 const llvm::function_ref<
823 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000824 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000825 Check) const {
Richard Smith375dec52019-05-30 23:21:14 +0000826 if (getStackSize() <= Level)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000827 return false;
828
Richard Smith375dec52019-05-30 23:21:14 +0000829 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
830 auto MI = StackElem.MappedExprComponents.find(VD);
831 if (MI != StackElem.MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000832 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
833 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000834 if (Check(L, MI->second.Kind))
835 return true;
836 return false;
837 }
838
Samuel Antao4c8035b2016-12-12 18:00:20 +0000839 /// Create a new mappable expression component list associated with a given
840 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000841 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000842 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000843 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
844 OpenMPClauseKind WhereFoundClauseKind) {
Richard Smith375dec52019-05-30 23:21:14 +0000845 MappedExprComponentTy &MEC = getTopOfStack().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000846 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000847 MEC.Components.resize(MEC.Components.size() + 1);
848 MEC.Components.back().append(Components.begin(), Components.end());
849 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000850 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000851
852 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000853 assert(!isStackEmpty());
Richard Smith375dec52019-05-30 23:21:14 +0000854 return getStackSize() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000855 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000856 void addDoacrossDependClause(OMPDependClause *C,
857 const OperatorOffsetTy &OpsOffs) {
Richard Smith375dec52019-05-30 23:21:14 +0000858 SharingMapTy *Parent = getSecondOnStackOrNull();
859 assert(Parent && isOpenMPWorksharingDirective(Parent->Directive));
860 Parent->DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000861 }
862 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
863 getDoacrossDependClauses() const {
Richard Smith375dec52019-05-30 23:21:14 +0000864 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +0000865 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000866 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000867 return llvm::make_range(Ref.begin(), Ref.end());
868 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000869 return llvm::make_range(StackElem.DoacrossDepends.end(),
870 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000871 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000872
873 // Store types of classes which have been explicitly mapped
874 void addMappedClassesQualTypes(QualType QT) {
Richard Smith375dec52019-05-30 23:21:14 +0000875 SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000876 StackElem.MappedClassesQualTypes.insert(QT);
877 }
878
879 // Return set of mapped classes types
880 bool isClassPreviouslyMapped(QualType QT) const {
Richard Smith375dec52019-05-30 23:21:14 +0000881 const SharingMapTy &StackElem = getTopOfStack();
Patrick Lystere13b1e32019-01-02 19:28:48 +0000882 return StackElem.MappedClassesQualTypes.count(QT) != 0;
883 }
884
Alexey Bataeva495c642019-03-11 19:51:42 +0000885 /// Adds global declare target to the parent target region.
886 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
887 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
888 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
889 "Expected declare target link global.");
Richard Smith375dec52019-05-30 23:21:14 +0000890 for (auto &Elem : *this) {
891 if (isOpenMPTargetExecutionDirective(Elem.Directive)) {
892 Elem.DeclareTargetLinkVarDecls.push_back(E);
893 return;
894 }
Alexey Bataeva495c642019-03-11 19:51:42 +0000895 }
896 }
897
898 /// Returns the list of globals with declare target link if current directive
899 /// is target.
900 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
901 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
902 "Expected target executable directive.");
Richard Smith375dec52019-05-30 23:21:14 +0000903 return getTopOfStack().DeclareTargetLinkVarDecls;
Alexey Bataeva495c642019-03-11 19:51:42 +0000904 }
Alexey Bataevf3c508f2020-01-23 10:47:16 -0500905
906 /// Adds list of allocators expressions.
907 void addInnerAllocatorExpr(Expr *E) {
908 getTopOfStack().InnerUsedAllocators.push_back(E);
909 }
910 /// Return list of used allocators.
911 ArrayRef<Expr *> getInnerAllocators() const {
912 return getTopOfStack().InnerUsedAllocators;
913 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000914};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000915
916bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
917 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
918}
919
920bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev412254a2019-05-09 18:44:53 +0000921 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) ||
922 DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000923}
Alexey Bataeve3727102018-04-18 15:57:46 +0000924
Alexey Bataeved09d242014-05-28 05:53:51 +0000925} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000926
Alexey Bataeve3727102018-04-18 15:57:46 +0000927static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000928 if (const auto *FE = dyn_cast<FullExpr>(E))
929 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000930
Alexey Bataeve3727102018-04-18 15:57:46 +0000931 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Tykerb0561b32019-11-17 11:41:55 +0100932 E = MTE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000933
Alexey Bataeve3727102018-04-18 15:57:46 +0000934 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000935 E = Binder->getSubExpr();
936
Alexey Bataeve3727102018-04-18 15:57:46 +0000937 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000938 E = ICE->getSubExprAsWritten();
939 return E->IgnoreParens();
940}
941
Alexey Bataeve3727102018-04-18 15:57:46 +0000942static Expr *getExprAsWritten(Expr *E) {
943 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
944}
945
946static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
947 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
948 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000949 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000950 const auto *VD = dyn_cast<VarDecl>(D);
951 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000952 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000953 VD = VD->getCanonicalDecl();
954 D = VD;
955 } else {
956 assert(FD);
957 FD = FD->getCanonicalDecl();
958 D = FD;
959 }
960 return D;
961}
962
Alexey Bataeve3727102018-04-18 15:57:46 +0000963static ValueDecl *getCanonicalDecl(ValueDecl *D) {
964 return const_cast<ValueDecl *>(
965 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
966}
967
Richard Smith375dec52019-05-30 23:21:14 +0000968DSAStackTy::DSAVarData DSAStackTy::getDSA(const_iterator &Iter,
Alexey Bataeve3727102018-04-18 15:57:46 +0000969 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000970 D = getCanonicalDecl(D);
971 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000972 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000973 DSAVarData DVar;
Richard Smith375dec52019-05-30 23:21:14 +0000974 if (Iter == end()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000975 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
976 // in a region but not in construct]
977 // File-scope or namespace-scope variables referenced in called routines
978 // in the region are shared unless they appear in a threadprivate
979 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000980 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000981 DVar.CKind = OMPC_shared;
982
983 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
984 // in a region but not in construct]
985 // Variables with static storage duration that are declared in called
986 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000987 if (VD && VD->hasGlobalStorage())
988 DVar.CKind = OMPC_shared;
989
990 // Non-static data members are shared by default.
991 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000992 DVar.CKind = OMPC_shared;
993
Alexey Bataev758e55e2013-09-06 18:03:48 +0000994 return DVar;
995 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000996
Alexey Bataevec3da872014-01-31 05:15:34 +0000997 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
998 // in a Construct, C/C++, predetermined, p.1]
999 // Variables with automatic storage duration that are declared in a scope
1000 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001001 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
1002 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001003 DVar.CKind = OMPC_private;
1004 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +00001005 }
1006
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001007 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001008 // Explicitly specified attributes and local variables with predetermined
1009 // attributes.
1010 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001011 const DSAInfo &Data = Iter->SharingMap.lookup(D);
1012 DVar.RefExpr = Data.RefExpr.getPointer();
1013 DVar.PrivateCopy = Data.PrivateCopy;
1014 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001015 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001016 return DVar;
1017 }
1018
1019 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1020 // in a Construct, C/C++, implicitly determined, p.1]
1021 // In a parallel or task construct, the data-sharing attributes of these
1022 // variables are determined by the default clause, if present.
1023 switch (Iter->DefaultAttr) {
1024 case DSA_shared:
1025 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +00001026 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001027 return DVar;
1028 case DSA_none:
1029 return DVar;
1030 case DSA_unspecified:
1031 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1032 // in a Construct, implicitly determined, p.2]
1033 // In a parallel construct, if no default clause is present, these
1034 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +00001035 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00001036 if ((isOpenMPParallelDirective(DVar.DKind) &&
1037 !isOpenMPTaskLoopDirective(DVar.DKind)) ||
Alexey Bataev13314bf2014-10-09 04:18:56 +00001038 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001039 DVar.CKind = OMPC_shared;
1040 return DVar;
1041 }
1042
1043 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1044 // in a Construct, implicitly determined, p.4]
1045 // In a task construct, if no default clause is present, a variable that in
1046 // the enclosing context is determined to be shared by all implicit tasks
1047 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +00001048 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001049 DSAVarData DVarTemp;
Richard Smith375dec52019-05-30 23:21:14 +00001050 const_iterator I = Iter, E = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001051 do {
1052 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +00001053 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +00001054 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +00001055 // In a task construct, if no default clause is present, a variable
1056 // whose data-sharing attribute is not determined by the rules above is
1057 // firstprivate.
1058 DVarTemp = getDSA(I, D);
1059 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001060 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001061 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001062 return DVar;
1063 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001064 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +00001065 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +00001066 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001067 return DVar;
1068 }
1069 }
1070 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1071 // in a Construct, implicitly determined, p.3]
1072 // For constructs other than task, if no default clause is present, these
1073 // variables inherit their data-sharing attributes from the enclosing
1074 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +00001075 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001076}
1077
Alexey Bataeve3727102018-04-18 15:57:46 +00001078const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
1079 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001080 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001081 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001082 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001083 auto It = StackElem.AlignedMap.find(D);
1084 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001085 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +00001086 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001087 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001088 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001089 assert(It->second && "Unexpected nullptr expr in the aligned map");
1090 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00001091}
1092
Alexey Bataevb6e70842019-12-16 15:54:17 -05001093const Expr *DSAStackTy::addUniqueNontemporal(const ValueDecl *D,
1094 const Expr *NewDE) {
1095 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
1096 D = getCanonicalDecl(D);
1097 SharingMapTy &StackElem = getTopOfStack();
1098 auto It = StackElem.NontemporalMap.find(D);
1099 if (It == StackElem.NontemporalMap.end()) {
1100 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
1101 StackElem.NontemporalMap[D] = NewDE;
1102 return nullptr;
1103 }
1104 assert(It->second && "Unexpected nullptr expr in the aligned map");
1105 return It->second;
1106}
1107
Alexey Bataeve3727102018-04-18 15:57:46 +00001108void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001109 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001110 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001111 SharingMapTy &StackElem = getTopOfStack();
Alexey Bataeve3727102018-04-18 15:57:46 +00001112 StackElem.LCVMap.try_emplace(
1113 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +00001114}
1115
Alexey Bataeve3727102018-04-18 15:57:46 +00001116const DSAStackTy::LCDeclInfo
1117DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001118 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001119 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001120 const SharingMapTy &StackElem = getTopOfStack();
Alexey Bataev4b465392017-04-26 15:06:24 +00001121 auto It = StackElem.LCVMap.find(D);
1122 if (It != StackElem.LCVMap.end())
1123 return It->second;
1124 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001125}
1126
Alexey Bataeve3727102018-04-18 15:57:46 +00001127const DSAStackTy::LCDeclInfo
1128DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Richard Smith375dec52019-05-30 23:21:14 +00001129 const SharingMapTy *Parent = getSecondOnStackOrNull();
1130 assert(Parent && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001131 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001132 auto It = Parent->LCVMap.find(D);
1133 if (It != Parent->LCVMap.end())
Alexey Bataev4b465392017-04-26 15:06:24 +00001134 return It->second;
1135 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001136}
1137
Alexey Bataeve3727102018-04-18 15:57:46 +00001138const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Richard Smith375dec52019-05-30 23:21:14 +00001139 const SharingMapTy *Parent = getSecondOnStackOrNull();
1140 assert(Parent && "Data-sharing attributes stack is empty");
1141 if (Parent->LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001142 return nullptr;
Richard Smith375dec52019-05-30 23:21:14 +00001143 for (const auto &Pair : Parent->LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001144 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001145 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00001146 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +00001147}
1148
Alexey Bataeve3727102018-04-18 15:57:46 +00001149void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +00001150 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001151 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001152 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001153 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001154 Data.Attributes = A;
1155 Data.RefExpr.setPointer(E);
1156 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001157 } else {
Richard Smith375dec52019-05-30 23:21:14 +00001158 DSAInfo &Data = getTopOfStack().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001159 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
1160 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
1161 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
1162 (isLoopControlVariable(D).first && A == OMPC_private));
1163 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
1164 Data.RefExpr.setInt(/*IntVal=*/true);
1165 return;
1166 }
1167 const bool IsLastprivate =
1168 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
1169 Data.Attributes = A;
1170 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
1171 Data.PrivateCopy = PrivateCopy;
1172 if (PrivateCopy) {
Richard Smith375dec52019-05-30 23:21:14 +00001173 DSAInfo &Data = getTopOfStack().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001174 Data.Attributes = A;
1175 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
1176 Data.PrivateCopy = nullptr;
1177 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001178 }
1179}
1180
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001181/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001182static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001183 StringRef Name, const AttrVec *Attrs = nullptr,
1184 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001185 DeclContext *DC = SemaRef.CurContext;
1186 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1187 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +00001188 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001189 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1190 if (Attrs) {
1191 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1192 I != E; ++I)
1193 Decl->addAttr(*I);
1194 }
1195 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001196 if (OrigRef) {
1197 Decl->addAttr(
1198 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1199 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001200 return Decl;
1201}
1202
1203static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1204 SourceLocation Loc,
1205 bool RefersToCapture = false) {
1206 D->setReferenced();
1207 D->markUsed(S.Context);
1208 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1209 SourceLocation(), D, RefersToCapture, Loc, Ty,
1210 VK_LValue);
1211}
1212
Alexey Bataeve3727102018-04-18 15:57:46 +00001213void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001214 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001215 D = getCanonicalDecl(D);
1216 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001217 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001218 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001219 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001220 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001221 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001222 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001223 "Additional reduction info may be specified only once for reduction "
1224 "items.");
1225 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001226 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001227 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001228 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001229 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1230 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001231 TaskgroupReductionRef =
1232 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001233 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001234}
1235
Alexey Bataeve3727102018-04-18 15:57:46 +00001236void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001237 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001238 D = getCanonicalDecl(D);
1239 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001240 assert(
Richard Smith375dec52019-05-30 23:21:14 +00001241 getTopOfStack().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001242 "Additional reduction info may be specified only for reduction items.");
Richard Smith375dec52019-05-30 23:21:14 +00001243 ReductionData &ReductionData = getTopOfStack().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001244 assert(ReductionData.ReductionRange.isInvalid() &&
Richard Smith375dec52019-05-30 23:21:14 +00001245 getTopOfStack().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001246 "Additional reduction info may be specified only once for reduction "
1247 "items.");
1248 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001249 Expr *&TaskgroupReductionRef =
Richard Smith375dec52019-05-30 23:21:14 +00001250 getTopOfStack().TaskgroupReductionRef;
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001251 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001252 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1253 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001254 TaskgroupReductionRef =
1255 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001256 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001257}
1258
Alexey Bataeve3727102018-04-18 15:57:46 +00001259const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1260 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1261 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001262 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001263 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001264 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001265 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001266 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001267 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001268 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001269 if (!ReductionData.ReductionOp ||
1270 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001271 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001272 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001273 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001274 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1275 "expression for the descriptor is not "
1276 "set.");
1277 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001278 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1279 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001280 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001281 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001282}
1283
Alexey Bataeve3727102018-04-18 15:57:46 +00001284const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1285 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1286 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001287 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001288 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
Richard Smith375dec52019-05-30 23:21:14 +00001289 for (const_iterator I = begin() + 1, E = end(); I != E; ++I) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001290 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001291 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001292 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001293 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001294 if (!ReductionData.ReductionOp ||
1295 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001296 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001297 SR = ReductionData.ReductionRange;
1298 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001299 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1300 "expression for the descriptor is not "
1301 "set.");
1302 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001303 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1304 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001305 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001306 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001307}
1308
Richard Smith375dec52019-05-30 23:21:14 +00001309bool DSAStackTy::isOpenMPLocal(VarDecl *D, const_iterator I) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001310 D = D->getCanonicalDecl();
Richard Smith375dec52019-05-30 23:21:14 +00001311 for (const_iterator E = end(); I != E; ++I) {
1312 if (isImplicitOrExplicitTaskingRegion(I->Directive) ||
1313 isOpenMPTargetExecutionDirective(I->Directive)) {
1314 Scope *TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
1315 Scope *CurScope = getCurScope();
1316 while (CurScope && CurScope != TopScope && !CurScope->isDeclScope(D))
1317 CurScope = CurScope->getParent();
1318 return CurScope != TopScope;
1319 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001320 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001321 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001322}
1323
Joel E. Dennyd2649292019-01-04 22:11:56 +00001324static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1325 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001326 bool *IsClassType = nullptr) {
1327 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001328 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001329 bool IsConstant = Type.isConstant(Context);
1330 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001331 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1332 ? Type->getAsCXXRecordDecl()
1333 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001334 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1335 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1336 RD = CTD->getTemplatedDecl();
1337 if (IsClassType)
1338 *IsClassType = RD;
1339 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1340 RD->hasDefinition() && RD->hasMutableFields());
1341}
1342
Joel E. Dennyd2649292019-01-04 22:11:56 +00001343static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1344 QualType Type, OpenMPClauseKind CKind,
1345 SourceLocation ELoc,
1346 bool AcceptIfMutable = true,
1347 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001348 ASTContext &Context = SemaRef.getASTContext();
1349 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001350 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1351 unsigned Diag = ListItemNotVar
1352 ? diag::err_omp_const_list_item
1353 : IsClassType ? diag::err_omp_const_not_mutable_variable
1354 : diag::err_omp_const_variable;
1355 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1356 if (!ListItemNotVar && D) {
1357 const VarDecl *VD = dyn_cast<VarDecl>(D);
1358 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1359 VarDecl::DeclarationOnly;
1360 SemaRef.Diag(D->getLocation(),
1361 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1362 << D;
1363 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001364 return true;
1365 }
1366 return false;
1367}
1368
Alexey Bataeve3727102018-04-18 15:57:46 +00001369const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1370 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001371 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001372 DSAVarData DVar;
1373
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001374 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001375 auto TI = Threadprivates.find(D);
1376 if (TI != Threadprivates.end()) {
1377 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001378 DVar.CKind = OMPC_threadprivate;
1379 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001380 }
1381 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001382 DVar.RefExpr = buildDeclRefExpr(
1383 SemaRef, VD, D->getType().getNonReferenceType(),
1384 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1385 DVar.CKind = OMPC_threadprivate;
1386 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001387 return DVar;
1388 }
1389 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1390 // in a Construct, C/C++, predetermined, p.1]
1391 // Variables appearing in threadprivate directives are threadprivate.
1392 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1393 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1394 SemaRef.getLangOpts().OpenMPUseTLS &&
1395 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1396 (VD && VD->getStorageClass() == SC_Register &&
1397 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1398 DVar.RefExpr = buildDeclRefExpr(
1399 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1400 DVar.CKind = OMPC_threadprivate;
1401 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1402 return DVar;
1403 }
1404 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1405 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1406 !isLoopControlVariable(D).first) {
Richard Smith375dec52019-05-30 23:21:14 +00001407 const_iterator IterTarget =
1408 std::find_if(begin(), end(), [](const SharingMapTy &Data) {
1409 return isOpenMPTargetExecutionDirective(Data.Directive);
1410 });
1411 if (IterTarget != end()) {
1412 const_iterator ParentIterTarget = IterTarget + 1;
1413 for (const_iterator Iter = begin();
1414 Iter != ParentIterTarget; ++Iter) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001415 if (isOpenMPLocal(VD, Iter)) {
1416 DVar.RefExpr =
1417 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1418 D->getLocation());
1419 DVar.CKind = OMPC_threadprivate;
1420 return DVar;
1421 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001422 }
Richard Smith375dec52019-05-30 23:21:14 +00001423 if (!isClauseParsingMode() || IterTarget != begin()) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001424 auto DSAIter = IterTarget->SharingMap.find(D);
1425 if (DSAIter != IterTarget->SharingMap.end() &&
1426 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1427 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1428 DVar.CKind = OMPC_threadprivate;
1429 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001430 }
Richard Smith375dec52019-05-30 23:21:14 +00001431 const_iterator End = end();
Alexey Bataeve3727102018-04-18 15:57:46 +00001432 if (!SemaRef.isOpenMPCapturedByRef(
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001433 D, std::distance(ParentIterTarget, End),
1434 /*OpenMPCaptureLevel=*/0)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001435 DVar.RefExpr =
1436 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1437 IterTarget->ConstructLoc);
1438 DVar.CKind = OMPC_threadprivate;
1439 return DVar;
1440 }
1441 }
1442 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001443 }
1444
Alexey Bataev4b465392017-04-26 15:06:24 +00001445 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001446 // Not in OpenMP execution region and top scope was already checked.
1447 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001448
Alexey Bataev758e55e2013-09-06 18:03:48 +00001449 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001450 // in a Construct, C/C++, predetermined, p.4]
1451 // Static data members are shared.
1452 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1453 // in a Construct, C/C++, predetermined, p.7]
1454 // Variables with static storage duration that are declared in a scope
1455 // inside the construct are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001456 if (VD && VD->isStaticDataMember()) {
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001457 // Check for explicitly specified attributes.
1458 const_iterator I = begin();
1459 const_iterator EndI = end();
1460 if (FromParent && I != EndI)
1461 ++I;
1462 auto It = I->SharingMap.find(D);
1463 if (It != I->SharingMap.end()) {
1464 const DSAInfo &Data = It->getSecond();
1465 DVar.RefExpr = Data.RefExpr.getPointer();
1466 DVar.PrivateCopy = Data.PrivateCopy;
1467 DVar.CKind = Data.Attributes;
1468 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
1469 DVar.DKind = I->Directive;
Alexey Bataevec3da872014-01-31 05:15:34 +00001470 return DVar;
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001471 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001472
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001473 DVar.CKind = OMPC_shared;
1474 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001475 }
1476
Alexey Bataev73f9d9aa2019-06-28 16:16:00 +00001477 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001478 // The predetermined shared attribute for const-qualified types having no
1479 // mutable members was removed after OpenMP 3.1.
1480 if (SemaRef.LangOpts.OpenMP <= 31) {
1481 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1482 // in a Construct, C/C++, predetermined, p.6]
1483 // Variables with const qualified type having no mutable member are
1484 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001485 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001486 // Variables with const-qualified type having no mutable member may be
1487 // listed in a firstprivate clause, even if they are static data members.
1488 DSAVarData DVarTemp = hasInnermostDSA(
1489 D,
1490 [](OpenMPClauseKind C) {
1491 return C == OMPC_firstprivate || C == OMPC_shared;
1492 },
1493 MatchesAlways, FromParent);
1494 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1495 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001496
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001497 DVar.CKind = OMPC_shared;
1498 return DVar;
1499 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001500 }
1501
Alexey Bataev758e55e2013-09-06 18:03:48 +00001502 // Explicitly specified attributes and local variables with predetermined
1503 // attributes.
Richard Smith375dec52019-05-30 23:21:14 +00001504 const_iterator I = begin();
1505 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001506 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001507 ++I;
Alexey Bataeve3727102018-04-18 15:57:46 +00001508 auto It = I->SharingMap.find(D);
1509 if (It != I->SharingMap.end()) {
1510 const DSAInfo &Data = It->getSecond();
1511 DVar.RefExpr = Data.RefExpr.getPointer();
1512 DVar.PrivateCopy = Data.PrivateCopy;
1513 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001514 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001515 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001516 }
1517
1518 return DVar;
1519}
1520
Alexey Bataeve3727102018-04-18 15:57:46 +00001521const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1522 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001523 if (isStackEmpty()) {
Richard Smith375dec52019-05-30 23:21:14 +00001524 const_iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001525 return getDSA(I, D);
1526 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001527 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001528 const_iterator StartI = begin();
1529 const_iterator EndI = end();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001530 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001531 ++StartI;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001532 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001533}
1534
Alexey Bataeve3727102018-04-18 15:57:46 +00001535const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001536DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001537 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1538 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001539 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001540 if (isStackEmpty())
1541 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001542 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001543 const_iterator I = begin();
1544 const_iterator EndI = end();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001545 if (FromParent && I != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001546 ++I;
1547 for (; I != EndI; ++I) {
1548 if (!DPred(I->Directive) &&
1549 !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001550 continue;
Richard Smith375dec52019-05-30 23:21:14 +00001551 const_iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001552 DSAVarData DVar = getDSA(NewI, D);
1553 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001554 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001555 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001556 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001557}
1558
Alexey Bataeve3727102018-04-18 15:57:46 +00001559const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001560 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1561 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001562 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001563 if (isStackEmpty())
1564 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001565 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001566 const_iterator StartI = begin();
1567 const_iterator EndI = end();
Alexey Bataeve3978122016-07-19 05:06:39 +00001568 if (FromParent && StartI != EndI)
Richard Smith375dec52019-05-30 23:21:14 +00001569 ++StartI;
Alexey Bataeve3978122016-07-19 05:06:39 +00001570 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001571 return {};
Richard Smith375dec52019-05-30 23:21:14 +00001572 const_iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001573 DSAVarData DVar = getDSA(NewI, D);
1574 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001575}
1576
Alexey Bataevaac108a2015-06-23 04:51:00 +00001577bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001578 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1579 unsigned Level, bool NotLastprivate) const {
Richard Smith375dec52019-05-30 23:21:14 +00001580 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001581 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001582 D = getCanonicalDecl(D);
Richard Smith375dec52019-05-30 23:21:14 +00001583 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1584 auto I = StackElem.SharingMap.find(D);
1585 if (I != StackElem.SharingMap.end() &&
1586 I->getSecond().RefExpr.getPointer() &&
1587 CPred(I->getSecond().Attributes) &&
1588 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
Alexey Bataev92b33652018-11-21 19:41:10 +00001589 return true;
1590 // Check predetermined rules for the loop control variables.
Richard Smith375dec52019-05-30 23:21:14 +00001591 auto LI = StackElem.LCVMap.find(D);
1592 if (LI != StackElem.LCVMap.end())
Alexey Bataev92b33652018-11-21 19:41:10 +00001593 return CPred(OMPC_private);
1594 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001595}
1596
Samuel Antao4be30e92015-10-02 17:14:03 +00001597bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001598 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1599 unsigned Level) const {
Richard Smith375dec52019-05-30 23:21:14 +00001600 if (getStackSize() <= Level)
Alexey Bataev4b465392017-04-26 15:06:24 +00001601 return false;
Richard Smith375dec52019-05-30 23:21:14 +00001602 const SharingMapTy &StackElem = getStackElemAtLevel(Level);
1603 return DPred(StackElem.Directive);
Samuel Antao4be30e92015-10-02 17:14:03 +00001604}
1605
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001606bool DSAStackTy::hasDirective(
1607 const llvm::function_ref<bool(OpenMPDirectiveKind,
1608 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001609 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001610 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001611 // We look only in the enclosing region.
Richard Smith375dec52019-05-30 23:21:14 +00001612 size_t Skip = FromParent ? 2 : 1;
1613 for (const_iterator I = begin() + std::min(Skip, getStackSize()), E = end();
1614 I != E; ++I) {
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001615 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1616 return true;
1617 }
1618 return false;
1619}
1620
Alexey Bataev758e55e2013-09-06 18:03:48 +00001621void Sema::InitDataSharingAttributesStack() {
1622 VarDataSharingAttributesStack = new DSAStackTy(*this);
1623}
1624
1625#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1626
Alexey Bataev4b465392017-04-26 15:06:24 +00001627void Sema::pushOpenMPFunctionRegion() {
1628 DSAStack->pushFunction();
1629}
1630
1631void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1632 DSAStack->popFunction(OldFSI);
1633}
1634
Alexey Bataevc416e642019-02-08 18:02:25 +00001635static bool isOpenMPDeviceDelayedContext(Sema &S) {
1636 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1637 "Expected OpenMP device compilation.");
1638 return !S.isInOpenMPTargetExecutionDirective() &&
1639 !S.isInOpenMPDeclareTargetContext();
1640}
1641
Alexey Bataev729e2422019-08-23 16:11:14 +00001642namespace {
1643/// Status of the function emission on the host/device.
1644enum class FunctionEmissionStatus {
1645 Emitted,
1646 Discarded,
1647 Unknown,
1648};
1649} // anonymous namespace
1650
Alexey Bataevc416e642019-02-08 18:02:25 +00001651Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1652 unsigned DiagID) {
1653 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1654 "Expected OpenMP device compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001655 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001656 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1657 switch (FES) {
1658 case FunctionEmissionStatus::Emitted:
1659 Kind = DeviceDiagBuilder::K_Immediate;
1660 break;
1661 case FunctionEmissionStatus::Unknown:
1662 Kind = isOpenMPDeviceDelayedContext(*this) ? DeviceDiagBuilder::K_Deferred
1663 : DeviceDiagBuilder::K_Immediate;
1664 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001665 case FunctionEmissionStatus::TemplateDiscarded:
1666 case FunctionEmissionStatus::OMPDiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001667 Kind = DeviceDiagBuilder::K_Nop;
1668 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001669 case FunctionEmissionStatus::CUDADiscarded:
1670 llvm_unreachable("CUDADiscarded unexpected in OpenMP device compilation");
1671 break;
Alexey Bataev729e2422019-08-23 16:11:14 +00001672 }
1673
1674 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
1675}
1676
Alexey Bataev729e2422019-08-23 16:11:14 +00001677Sema::DeviceDiagBuilder Sema::diagIfOpenMPHostCode(SourceLocation Loc,
1678 unsigned DiagID) {
1679 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1680 "Expected OpenMP host compilation.");
Yaxun Liu229c78d2019-10-09 23:54:10 +00001681 FunctionEmissionStatus FES = getEmissionStatus(getCurFunctionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +00001682 DeviceDiagBuilder::Kind Kind = DeviceDiagBuilder::K_Nop;
1683 switch (FES) {
1684 case FunctionEmissionStatus::Emitted:
1685 Kind = DeviceDiagBuilder::K_Immediate;
1686 break;
1687 case FunctionEmissionStatus::Unknown:
1688 Kind = DeviceDiagBuilder::K_Deferred;
1689 break;
Yaxun Liu229c78d2019-10-09 23:54:10 +00001690 case FunctionEmissionStatus::TemplateDiscarded:
1691 case FunctionEmissionStatus::OMPDiscarded:
1692 case FunctionEmissionStatus::CUDADiscarded:
Alexey Bataev729e2422019-08-23 16:11:14 +00001693 Kind = DeviceDiagBuilder::K_Nop;
1694 break;
1695 }
1696
1697 return DeviceDiagBuilder(Kind, Loc, DiagID, getCurFunctionDecl(), *this);
Alexey Bataevc416e642019-02-08 18:02:25 +00001698}
1699
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001700void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee,
1701 bool CheckForDelayedContext) {
Alexey Bataevc416e642019-02-08 18:02:25 +00001702 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1703 "Expected OpenMP device compilation.");
1704 assert(Callee && "Callee may not be null.");
Alexey Bataev729e2422019-08-23 16:11:14 +00001705 Callee = Callee->getMostRecentDecl();
Alexey Bataevc416e642019-02-08 18:02:25 +00001706 FunctionDecl *Caller = getCurFunctionDecl();
1707
Alexey Bataev729e2422019-08-23 16:11:14 +00001708 // host only function are not available on the device.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001709 if (Caller) {
1710 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1711 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1712 assert(CallerS != FunctionEmissionStatus::CUDADiscarded &&
1713 CalleeS != FunctionEmissionStatus::CUDADiscarded &&
1714 "CUDADiscarded unexpected in OpenMP device function check");
1715 if ((CallerS == FunctionEmissionStatus::Emitted ||
1716 (!isOpenMPDeviceDelayedContext(*this) &&
1717 CallerS == FunctionEmissionStatus::Unknown)) &&
1718 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1719 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
1720 OMPC_device_type, OMPC_DEVICE_TYPE_host);
1721 Diag(Loc, diag::err_omp_wrong_device_function_call) << HostDevTy << 0;
1722 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1723 diag::note_omp_marked_device_type_here)
1724 << HostDevTy;
1725 return;
1726 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001727 }
Alexey Bataevc416e642019-02-08 18:02:25 +00001728 // If the caller is known-emitted, mark the callee as known-emitted.
1729 // Otherwise, mark the call in our call graph so we can traverse it later.
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001730 if ((CheckForDelayedContext && !isOpenMPDeviceDelayedContext(*this)) ||
1731 (!Caller && !CheckForDelayedContext) ||
Yaxun Liu229c78d2019-10-09 23:54:10 +00001732 (Caller && getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001733 markKnownEmitted(*this, Caller, Callee, Loc,
1734 [CheckForDelayedContext](Sema &S, FunctionDecl *FD) {
Alexey Bataev729e2422019-08-23 16:11:14 +00001735 return CheckForDelayedContext &&
Yaxun Liu229c78d2019-10-09 23:54:10 +00001736 S.getEmissionStatus(FD) ==
Alexey Bataev729e2422019-08-23 16:11:14 +00001737 FunctionEmissionStatus::Emitted;
Alexey Bataev9fd495b2019-08-20 19:50:13 +00001738 });
Alexey Bataevc416e642019-02-08 18:02:25 +00001739 else if (Caller)
1740 DeviceCallGraph[Caller].insert({Callee, Loc});
1741}
1742
Alexey Bataev729e2422019-08-23 16:11:14 +00001743void Sema::checkOpenMPHostFunction(SourceLocation Loc, FunctionDecl *Callee,
1744 bool CheckCaller) {
1745 assert(LangOpts.OpenMP && !LangOpts.OpenMPIsDevice &&
1746 "Expected OpenMP host compilation.");
1747 assert(Callee && "Callee may not be null.");
1748 Callee = Callee->getMostRecentDecl();
1749 FunctionDecl *Caller = getCurFunctionDecl();
1750
1751 // device only function are not available on the host.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001752 if (Caller) {
1753 FunctionEmissionStatus CallerS = getEmissionStatus(Caller);
1754 FunctionEmissionStatus CalleeS = getEmissionStatus(Callee);
1755 assert(
1756 (LangOpts.CUDA || (CallerS != FunctionEmissionStatus::CUDADiscarded &&
1757 CalleeS != FunctionEmissionStatus::CUDADiscarded)) &&
1758 "CUDADiscarded unexpected in OpenMP host function check");
1759 if (CallerS == FunctionEmissionStatus::Emitted &&
1760 CalleeS == FunctionEmissionStatus::OMPDiscarded) {
1761 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
1762 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
1763 Diag(Loc, diag::err_omp_wrong_device_function_call) << NoHostDevTy << 1;
1764 Diag(Callee->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
1765 diag::note_omp_marked_device_type_here)
1766 << NoHostDevTy;
1767 return;
1768 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001769 }
1770 // If the caller is known-emitted, mark the callee as known-emitted.
1771 // Otherwise, mark the call in our call graph so we can traverse it later.
Yaxun Liu229c78d2019-10-09 23:54:10 +00001772 if (!shouldIgnoreInHostDeviceCheck(Callee)) {
1773 if ((!CheckCaller && !Caller) ||
1774 (Caller &&
1775 getEmissionStatus(Caller) == FunctionEmissionStatus::Emitted))
1776 markKnownEmitted(
1777 *this, Caller, Callee, Loc, [CheckCaller](Sema &S, FunctionDecl *FD) {
1778 return CheckCaller &&
1779 S.getEmissionStatus(FD) == FunctionEmissionStatus::Emitted;
1780 });
1781 else if (Caller)
1782 DeviceCallGraph[Caller].insert({Callee, Loc});
1783 }
Alexey Bataev729e2422019-08-23 16:11:14 +00001784}
1785
Alexey Bataev123ad192019-02-27 20:29:45 +00001786void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1787 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1788 "OpenMP device compilation mode is expected.");
1789 QualType Ty = E->getType();
1790 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
Alexey Bataev8557d1a2019-06-18 18:39:26 +00001791 ((Ty->isFloat128Type() ||
1792 (Ty->isRealFloatingType() && Context.getTypeSize(Ty) == 128)) &&
1793 !Context.getTargetInfo().hasFloat128Type()) ||
Alexey Bataev123ad192019-02-27 20:29:45 +00001794 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1795 !Context.getTargetInfo().hasInt128Type()))
Alexey Bataev62892592019-07-08 19:21:54 +00001796 targetDiag(E->getExprLoc(), diag::err_omp_unsupported_type)
1797 << static_cast<unsigned>(Context.getTypeSize(Ty)) << Ty
1798 << Context.getTargetInfo().getTriple().str() << E->getSourceRange();
Alexey Bataev123ad192019-02-27 20:29:45 +00001799}
1800
cchene06f3e02019-11-15 13:02:06 -05001801static OpenMPDefaultmapClauseKind
Alexey Bataev6f7c8762019-11-22 11:09:33 -05001802getVariableCategoryFromDecl(const LangOptions &LO, const ValueDecl *VD) {
1803 if (LO.OpenMP <= 45) {
1804 if (VD->getType().getNonReferenceType()->isScalarType())
1805 return OMPC_DEFAULTMAP_scalar;
1806 return OMPC_DEFAULTMAP_aggregate;
1807 }
cchene06f3e02019-11-15 13:02:06 -05001808 if (VD->getType().getNonReferenceType()->isAnyPointerType())
1809 return OMPC_DEFAULTMAP_pointer;
1810 if (VD->getType().getNonReferenceType()->isScalarType())
1811 return OMPC_DEFAULTMAP_scalar;
1812 return OMPC_DEFAULTMAP_aggregate;
1813}
1814
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001815bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level,
1816 unsigned OpenMPCaptureLevel) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001817 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1818
Alexey Bataeve3727102018-04-18 15:57:46 +00001819 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001820 bool IsByRef = true;
1821
1822 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001823 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001824 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001825
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001826 bool IsVariableUsedInMapClause = false;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001827 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001828 // This table summarizes how a given variable should be passed to the device
1829 // given its type and the clauses where it appears. This table is based on
1830 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1831 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1832 //
1833 // =========================================================================
1834 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1835 // | |(tofrom:scalar)| | pvt | | | |
1836 // =========================================================================
1837 // | scl | | | | - | | bycopy|
1838 // | scl | | - | x | - | - | bycopy|
1839 // | scl | | x | - | - | - | null |
1840 // | scl | x | | | - | | byref |
1841 // | scl | x | - | x | - | - | bycopy|
1842 // | scl | x | x | - | - | - | null |
1843 // | scl | | - | - | - | x | byref |
1844 // | scl | x | - | - | - | x | byref |
1845 //
1846 // | agg | n.a. | | | - | | byref |
1847 // | agg | n.a. | - | x | - | - | byref |
1848 // | agg | n.a. | x | - | - | - | null |
1849 // | agg | n.a. | - | - | - | x | byref |
1850 // | agg | n.a. | - | - | - | x[] | byref |
1851 //
1852 // | ptr | n.a. | | | - | | bycopy|
1853 // | ptr | n.a. | - | x | - | - | bycopy|
1854 // | ptr | n.a. | x | - | - | - | null |
1855 // | ptr | n.a. | - | - | - | x | byref |
1856 // | ptr | n.a. | - | - | - | x[] | bycopy|
1857 // | ptr | n.a. | - | - | x | | bycopy|
1858 // | ptr | n.a. | - | - | x | x | bycopy|
1859 // | ptr | n.a. | - | - | x | x[] | bycopy|
1860 // =========================================================================
1861 // Legend:
1862 // scl - scalar
1863 // ptr - pointer
1864 // agg - aggregate
1865 // x - applies
1866 // - - invalid in this combination
1867 // [] - mapped with an array section
1868 // byref - should be mapped by reference
1869 // byval - should be mapped by value
1870 // null - initialize a local variable to null on the device
1871 //
1872 // Observations:
1873 // - All scalar declarations that show up in a map clause have to be passed
1874 // by reference, because they may have been mapped in the enclosing data
1875 // environment.
1876 // - If the scalar value does not fit the size of uintptr, it has to be
1877 // passed by reference, regardless the result in the table above.
1878 // - For pointers mapped by value that have either an implicit map or an
1879 // array section, the runtime library may pass the NULL value to the
1880 // device instead of the value passed to it by the compiler.
1881
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001882 if (Ty->isReferenceType())
1883 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001884
1885 // Locate map clauses and see if the variable being captured is referred to
1886 // in any of those clauses. Here we only care about variables, not fields,
1887 // because fields are part of aggregates.
Samuel Antao86ace552016-04-27 22:40:57 +00001888 bool IsVariableAssociatedWithSection = false;
1889
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001890 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001891 D, Level,
1892 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1893 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001894 MapExprComponents,
1895 OpenMPClauseKind WhereFoundClauseKind) {
1896 // Only the map clause information influences how a variable is
1897 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001898 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001899 if (WhereFoundClauseKind != OMPC_map)
1900 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001901
1902 auto EI = MapExprComponents.rbegin();
1903 auto EE = MapExprComponents.rend();
1904
1905 assert(EI != EE && "Invalid map expression!");
1906
1907 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1908 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1909
1910 ++EI;
1911 if (EI == EE)
1912 return false;
1913
1914 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1915 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1916 isa<MemberExpr>(EI->getAssociatedExpression())) {
1917 IsVariableAssociatedWithSection = true;
1918 // There is nothing more we need to know about this variable.
1919 return true;
1920 }
1921
1922 // Keep looking for more map info.
1923 return false;
1924 });
1925
1926 if (IsVariableUsedInMapClause) {
1927 // If variable is identified in a map clause it is always captured by
1928 // reference except if it is a pointer that is dereferenced somehow.
1929 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1930 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001931 // By default, all the data that has a scalar type is mapped by copy
1932 // (except for reduction variables).
cchene06f3e02019-11-15 13:02:06 -05001933 // Defaultmap scalar is mutual exclusive to defaultmap pointer
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001934 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001935 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1936 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001937 !Ty->isScalarType() ||
Alexey Bataev6f7c8762019-11-22 11:09:33 -05001938 DSAStack->isDefaultmapCapturedByRef(
1939 Level, getVariableCategoryFromDecl(LangOpts, D)) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001940 DSAStack->hasExplicitDSA(
1941 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001942 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001943 }
1944
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001945 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001946 IsByRef =
Joel E. Denny7d5bc552019-08-22 03:34:30 +00001947 ((IsVariableUsedInMapClause &&
1948 DSAStack->getCaptureRegion(Level, OpenMPCaptureLevel) ==
1949 OMPD_target) ||
1950 !DSAStack->hasExplicitDSA(
1951 D,
1952 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1953 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001954 // If the variable is artificial and must be captured by value - try to
1955 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001956 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1957 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001958 }
1959
Samuel Antao86ace552016-04-27 22:40:57 +00001960 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001961 // and alignment, because the runtime library only deals with uintptr types.
1962 // If it does not fit the uintptr size, we need to pass the data by reference
1963 // instead.
1964 if (!IsByRef &&
1965 (Ctx.getTypeSizeInChars(Ty) >
1966 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001967 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001968 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001969 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001970
1971 return IsByRef;
1972}
1973
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001974unsigned Sema::getOpenMPNestingLevel() const {
1975 assert(getLangOpts().OpenMP);
1976 return DSAStack->getNestingLevel();
1977}
1978
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001979bool Sema::isInOpenMPTargetExecutionDirective() const {
1980 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1981 !DSAStack->isClauseParsingMode()) ||
1982 DSAStack->hasDirective(
1983 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1984 SourceLocation) -> bool {
1985 return isOpenMPTargetExecutionDirective(K);
1986 },
1987 false);
1988}
1989
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00001990VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D, bool CheckScopeInfo,
1991 unsigned StopAt) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001992 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001993 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001994
Alexey Bataev7c860692019-10-25 16:35:32 -04001995 auto *VD = dyn_cast<VarDecl>(D);
1996 // Do not capture constexpr variables.
1997 if (VD && VD->isConstexpr())
1998 return nullptr;
1999
Richard Smith0621a8f2019-05-31 00:45:10 +00002000 // If we want to determine whether the variable should be captured from the
2001 // perspective of the current capturing scope, and we've already left all the
2002 // capturing scopes of the top directive on the stack, check from the
2003 // perspective of its parent directive (if any) instead.
2004 DSAStackTy::ParentDirectiveScope InParentDirectiveRAII(
2005 *DSAStack, CheckScopeInfo && DSAStack->isBodyComplete());
2006
Samuel Antao4be30e92015-10-02 17:14:03 +00002007 // If we are attempting to capture a global variable in a directive with
2008 // 'target' we return true so that this global is also mapped to the device.
2009 //
Richard Smith0621a8f2019-05-31 00:45:10 +00002010 if (VD && !VD->hasLocalStorage() &&
2011 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
2012 if (isInOpenMPDeclareTargetContext()) {
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002013 // Try to mark variable as declare target if it is used in capturing
2014 // regions.
Alexey Bataev217ff1e2019-08-16 20:15:02 +00002015 if (LangOpts.OpenMP <= 45 &&
2016 !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002017 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002018 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002019 } else if (isInOpenMPTargetExecutionDirective()) {
2020 // If the declaration is enclosed in a 'declare target' directive,
2021 // then it should not be captured.
2022 //
Alexey Bataev97b72212018-08-14 18:31:20 +00002023 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002024 return nullptr;
Alexey Bataev36635632020-01-17 20:39:04 -05002025 CapturedRegionScopeInfo *CSI = nullptr;
2026 for (FunctionScopeInfo *FSI : llvm::drop_begin(
2027 llvm::reverse(FunctionScopes),
2028 CheckScopeInfo ? (FunctionScopes.size() - (StopAt + 1)) : 0)) {
2029 if (!isa<CapturingScopeInfo>(FSI))
2030 return nullptr;
2031 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2032 if (RSI->CapRegionKind == CR_OpenMP) {
2033 CSI = RSI;
2034 break;
2035 }
2036 }
2037 SmallVector<OpenMPDirectiveKind, 4> Regions;
2038 getOpenMPCaptureRegions(Regions,
2039 DSAStack->getDirective(CSI->OpenMPLevel));
2040 if (Regions[CSI->OpenMPCaptureLevel] != OMPD_task)
2041 return VD;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00002042 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00002043 }
Samuel Antao4be30e92015-10-02 17:14:03 +00002044
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00002045 if (CheckScopeInfo) {
2046 bool OpenMPFound = false;
2047 for (unsigned I = StopAt + 1; I > 0; --I) {
2048 FunctionScopeInfo *FSI = FunctionScopes[I - 1];
2049 if(!isa<CapturingScopeInfo>(FSI))
2050 return nullptr;
2051 if (auto *RSI = dyn_cast<CapturedRegionScopeInfo>(FSI))
2052 if (RSI->CapRegionKind == CR_OpenMP) {
2053 OpenMPFound = true;
2054 break;
2055 }
2056 }
2057 if (!OpenMPFound)
2058 return nullptr;
2059 }
2060
Alexey Bataev48977c32015-08-04 08:10:48 +00002061 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
2062 (!DSAStack->isClauseParsingMode() ||
2063 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002064 auto &&Info = DSAStack->isLoopControlVariable(D);
2065 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002066 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002067 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002068 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00002069 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00002070 DSAStackTy::DSAVarData DVarPrivate =
2071 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00002072 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00002073 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve0eb66b2019-06-21 15:08:30 +00002074 // Threadprivate variables must not be captured.
2075 if (isOpenMPThreadPrivate(DVarPrivate.CKind))
2076 return nullptr;
2077 // The variable is not private or it is the variable in the directive with
2078 // default(none) clause and not used in any clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002079 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
2080 [](OpenMPDirectiveKind) { return true; },
2081 DSAStack->isClauseParsingMode());
Alexey Bataev41ebe0c2019-05-09 18:14:57 +00002082 if (DVarPrivate.CKind != OMPC_unknown ||
2083 (VD && DSAStack->getDefaultDSA() == DSA_none))
Alexey Bataev90c228f2016-02-08 09:29:13 +00002084 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00002085 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00002086 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00002087}
2088
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002089void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
2090 unsigned Level) const {
2091 SmallVector<OpenMPDirectiveKind, 4> Regions;
2092 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
2093 FunctionScopesIndex -= Regions.size();
2094}
2095
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002096void Sema::startOpenMPLoop() {
2097 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2098 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
2099 DSAStack->loopInit();
2100}
2101
Alexey Bataevbef93a92019-10-07 18:54:57 +00002102void Sema::startOpenMPCXXRangeFor() {
2103 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
2104 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2105 DSAStack->resetPossibleLoopCounter();
2106 DSAStack->loopStart();
2107 }
2108}
2109
Alexey Bataeve3727102018-04-18 15:57:46 +00002110bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00002111 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002112 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
2113 if (DSAStack->getAssociatedLoops() > 0 &&
2114 !DSAStack->isLoopStarted()) {
2115 DSAStack->resetPossibleLoopCounter(D);
2116 DSAStack->loopStart();
2117 return true;
2118 }
2119 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
2120 DSAStack->isLoopControlVariable(D).first) &&
2121 !DSAStack->hasExplicitDSA(
2122 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
2123 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
2124 return true;
2125 }
Alexey Bataev0c99d192019-07-18 19:40:24 +00002126 if (const auto *VD = dyn_cast<VarDecl>(D)) {
2127 if (DSAStack->isThreadPrivate(const_cast<VarDecl *>(VD)) &&
2128 DSAStack->isForceVarCapturing() &&
2129 !DSAStack->hasExplicitDSA(
2130 D, [](OpenMPClauseKind K) { return K == OMPC_copyin; }, Level))
2131 return true;
2132 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00002133 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002134 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00002135 (DSAStack->isClauseParsingMode() &&
2136 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00002137 // Consider taskgroup reduction descriptor variable a private to avoid
2138 // possible capture in the region.
2139 (DSAStack->hasExplicitDirective(
2140 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
2141 Level) &&
2142 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00002143}
2144
Alexey Bataeve3727102018-04-18 15:57:46 +00002145void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
2146 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002147 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2148 D = getCanonicalDecl(D);
2149 OpenMPClauseKind OMPC = OMPC_unknown;
2150 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
2151 const unsigned NewLevel = I - 1;
2152 if (DSAStack->hasExplicitDSA(D,
2153 [&OMPC](const OpenMPClauseKind K) {
2154 if (isOpenMPPrivate(K)) {
2155 OMPC = K;
2156 return true;
2157 }
2158 return false;
2159 },
2160 NewLevel))
2161 break;
2162 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
2163 D, NewLevel,
2164 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2165 OpenMPClauseKind) { return true; })) {
2166 OMPC = OMPC_map;
2167 break;
2168 }
2169 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
2170 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002171 OMPC = OMPC_map;
Alexey Bataev6f7c8762019-11-22 11:09:33 -05002172 if (DSAStack->mustBeFirstprivateAtLevel(
2173 NewLevel, getVariableCategoryFromDecl(LangOpts, D)))
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002174 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00002175 break;
2176 }
2177 }
2178 if (OMPC != OMPC_unknown)
2179 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
2180}
2181
Alexey Bataev36635632020-01-17 20:39:04 -05002182bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D, unsigned Level,
2183 unsigned CaptureLevel) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00002184 assert(LangOpts.OpenMP && "OpenMP is not allowed");
2185 // Return true if the current level is no longer enclosed in a target region.
2186
Alexey Bataev36635632020-01-17 20:39:04 -05002187 SmallVector<OpenMPDirectiveKind, 4> Regions;
2188 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
Alexey Bataeve3727102018-04-18 15:57:46 +00002189 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002190 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002191 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
Alexey Bataev36635632020-01-17 20:39:04 -05002192 Level) &&
2193 Regions[CaptureLevel] != OMPD_task;
Samuel Antao4be30e92015-10-02 17:14:03 +00002194}
2195
Alexey Bataeved09d242014-05-28 05:53:51 +00002196void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002197
Alexey Bataev729e2422019-08-23 16:11:14 +00002198void Sema::finalizeOpenMPDelayedAnalysis() {
2199 assert(LangOpts.OpenMP && "Expected OpenMP compilation mode.");
2200 // Diagnose implicit declare target functions and their callees.
2201 for (const auto &CallerCallees : DeviceCallGraph) {
2202 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2203 OMPDeclareTargetDeclAttr::getDeviceType(
2204 CallerCallees.getFirst()->getMostRecentDecl());
2205 // Ignore host functions during device analyzis.
2206 if (LangOpts.OpenMPIsDevice && DevTy &&
2207 *DevTy == OMPDeclareTargetDeclAttr::DT_Host)
2208 continue;
2209 // Ignore nohost functions during host analyzis.
2210 if (!LangOpts.OpenMPIsDevice && DevTy &&
2211 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost)
2212 continue;
2213 for (const std::pair<CanonicalDeclPtr<FunctionDecl>, SourceLocation>
2214 &Callee : CallerCallees.getSecond()) {
2215 const FunctionDecl *FD = Callee.first->getMostRecentDecl();
2216 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
2217 OMPDeclareTargetDeclAttr::getDeviceType(FD);
2218 if (LangOpts.OpenMPIsDevice && DevTy &&
2219 *DevTy == OMPDeclareTargetDeclAttr::DT_Host) {
2220 // Diagnose host function called during device codegen.
2221 StringRef HostDevTy = getOpenMPSimpleClauseTypeName(
2222 OMPC_device_type, OMPC_DEVICE_TYPE_host);
2223 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2224 << HostDevTy << 0;
2225 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2226 diag::note_omp_marked_device_type_here)
2227 << HostDevTy;
2228 continue;
2229 }
2230 if (!LangOpts.OpenMPIsDevice && DevTy &&
2231 *DevTy == OMPDeclareTargetDeclAttr::DT_NoHost) {
2232 // Diagnose nohost function called during host codegen.
2233 StringRef NoHostDevTy = getOpenMPSimpleClauseTypeName(
2234 OMPC_device_type, OMPC_DEVICE_TYPE_nohost);
2235 Diag(Callee.second, diag::err_omp_wrong_device_function_call)
2236 << NoHostDevTy << 1;
2237 Diag(FD->getAttr<OMPDeclareTargetDeclAttr>()->getLocation(),
2238 diag::note_omp_marked_device_type_here)
2239 << NoHostDevTy;
2240 continue;
2241 }
2242 }
2243 }
2244}
2245
Alexey Bataev758e55e2013-09-06 18:03:48 +00002246void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
2247 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002248 Scope *CurScope, SourceLocation Loc) {
2249 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00002250 PushExpressionEvaluationContext(
2251 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002252}
2253
Alexey Bataevaac108a2015-06-23 04:51:00 +00002254void Sema::StartOpenMPClause(OpenMPClauseKind K) {
2255 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002256}
2257
Alexey Bataevaac108a2015-06-23 04:51:00 +00002258void Sema::EndOpenMPClause() {
2259 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00002260}
2261
Alexey Bataeve106f252019-04-01 14:25:31 +00002262static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
2263 ArrayRef<OMPClause *> Clauses);
Alexey Bataev0860db92019-12-19 10:01:10 -05002264static std::pair<ValueDecl *, bool>
2265getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
2266 SourceRange &ERange, bool AllowArraySection = false);
2267static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2268 bool WithInit);
Alexey Bataeve106f252019-04-01 14:25:31 +00002269
Alexey Bataev758e55e2013-09-06 18:03:48 +00002270void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002271 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
2272 // A variable of class type (or array thereof) that appears in a lastprivate
2273 // clause requires an accessible, unambiguous default constructor for the
2274 // class type, unless the list item is also specified in a firstprivate
2275 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00002276 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
2277 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002278 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
2279 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00002280 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002281 if (DE->isValueDependent() || DE->isTypeDependent()) {
2282 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002283 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00002284 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00002285 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00002286 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00002287 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00002288 const DSAStackTy::DSAVarData DVar =
2289 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002290 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00002291 // Generate helper private variable and initialize it with the
2292 // default value. The address of the original variable is replaced
2293 // by the address of the new private variable in CodeGen. This new
2294 // variable is not added to IdResolver, so the code in the OpenMP
2295 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00002296 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00002297 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00002298 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00002299 ActOnUninitializedDecl(VDPrivate);
Alexey Bataeve106f252019-04-01 14:25:31 +00002300 if (VDPrivate->isInvalidDecl()) {
2301 PrivateCopies.push_back(nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00002302 continue;
Alexey Bataeve106f252019-04-01 14:25:31 +00002303 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00002304 PrivateCopies.push_back(buildDeclRefExpr(
2305 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00002306 } else {
2307 // The variable is also a firstprivate, so initialization sequence
2308 // for private copy is generated already.
2309 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002310 }
2311 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002312 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataev0860db92019-12-19 10:01:10 -05002313 continue;
2314 }
2315 // Finalize nontemporal clause by handling private copies, if any.
2316 if (auto *Clause = dyn_cast<OMPNontemporalClause>(C)) {
2317 SmallVector<Expr *, 8> PrivateRefs;
2318 for (Expr *RefExpr : Clause->varlists()) {
2319 assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
2320 SourceLocation ELoc;
2321 SourceRange ERange;
2322 Expr *SimpleRefExpr = RefExpr;
2323 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
2324 if (Res.second)
2325 // It will be analyzed later.
2326 PrivateRefs.push_back(RefExpr);
2327 ValueDecl *D = Res.first;
2328 if (!D)
2329 continue;
2330
2331 const DSAStackTy::DSAVarData DVar =
2332 DSAStack->getTopDSA(D, /*FromParent=*/false);
2333 PrivateRefs.push_back(DVar.PrivateCopy ? DVar.PrivateCopy
2334 : SimpleRefExpr);
2335 }
2336 Clause->setPrivateRefs(PrivateRefs);
2337 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +00002338 }
2339 }
Alexey Bataeve106f252019-04-01 14:25:31 +00002340 // Check allocate clauses.
2341 if (!CurContext->isDependentContext())
2342 checkAllocateClauses(*this, DSAStack, D->clauses());
Alexey Bataevf29276e2014-06-18 04:14:57 +00002343 }
2344
Alexey Bataev758e55e2013-09-06 18:03:48 +00002345 DSAStack->pop();
2346 DiscardCleanupsInEvaluationContext();
2347 PopExpressionEvaluationContext();
2348}
2349
Alexey Bataev5dff95c2016-04-22 03:56:56 +00002350static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
2351 Expr *NumIterations, Sema &SemaRef,
2352 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00002353
Alexey Bataeva769e072013-03-22 06:34:35 +00002354namespace {
2355
Alexey Bataeve3727102018-04-18 15:57:46 +00002356class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002357private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002358 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00002359
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002360public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00002361 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00002362 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002363 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00002364 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002365 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00002366 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2367 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00002368 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002369 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00002370 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002371
2372 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002373 return std::make_unique<VarDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002374 }
2375
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002376};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002377
Alexey Bataeve3727102018-04-18 15:57:46 +00002378class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002379private:
2380 Sema &SemaRef;
2381
2382public:
2383 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
2384 bool ValidateCandidate(const TypoCorrection &Candidate) override {
2385 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002386 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
2387 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002388 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
2389 SemaRef.getCurScope());
2390 }
2391 return false;
2392 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00002393
2394 std::unique_ptr<CorrectionCandidateCallback> clone() override {
Jonas Devlieghere2b3d49b2019-08-14 23:04:18 +00002395 return std::make_unique<VarOrFuncDeclFilterCCC>(*this);
Bruno Ricci70ad3962019-03-25 17:08:51 +00002396 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002397};
2398
Alexey Bataeved09d242014-05-28 05:53:51 +00002399} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002400
2401ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2402 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002403 const DeclarationNameInfo &Id,
2404 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002405 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2406 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2407
2408 if (Lookup.isAmbiguous())
2409 return ExprError();
2410
2411 VarDecl *VD;
2412 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00002413 VarDeclFilterCCC CCC(*this);
2414 if (TypoCorrection Corrected =
2415 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2416 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00002417 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002418 PDiag(Lookup.empty()
2419 ? diag::err_undeclared_var_use_suggest
2420 : diag::err_omp_expected_var_arg_suggest)
2421 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00002422 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002423 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002424 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2425 : diag::err_omp_expected_var_arg)
2426 << Id.getName();
2427 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002428 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002429 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2430 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2431 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2432 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002433 }
2434 Lookup.suppressDiagnostics();
2435
2436 // OpenMP [2.9.2, Syntax, C/C++]
2437 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002438 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002439 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002440 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002441 bool IsDecl =
2442 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002443 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002444 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2445 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002446 return ExprError();
2447 }
2448
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002449 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002450 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002451 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2452 // A threadprivate directive for file-scope variables must appear outside
2453 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002454 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2455 !getCurLexicalContext()->isTranslationUnit()) {
2456 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002457 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002458 bool IsDecl =
2459 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2460 Diag(VD->getLocation(),
2461 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2462 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002463 return ExprError();
2464 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002465 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2466 // A threadprivate directive for static class member variables must appear
2467 // in the class definition, in the same scope in which the member
2468 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002469 if (CanonicalVD->isStaticDataMember() &&
2470 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2471 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002472 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002473 bool IsDecl =
2474 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2475 Diag(VD->getLocation(),
2476 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2477 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002478 return ExprError();
2479 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002480 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2481 // A threadprivate directive for namespace-scope variables must appear
2482 // outside any definition or declaration other than the namespace
2483 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002484 if (CanonicalVD->getDeclContext()->isNamespace() &&
2485 (!getCurLexicalContext()->isFileContext() ||
2486 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2487 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002488 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002489 bool IsDecl =
2490 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2491 Diag(VD->getLocation(),
2492 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2493 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002494 return ExprError();
2495 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002496 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2497 // A threadprivate directive for static block-scope variables must appear
2498 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002499 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002500 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002501 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002502 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002503 bool IsDecl =
2504 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2505 Diag(VD->getLocation(),
2506 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2507 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002508 return ExprError();
2509 }
2510
2511 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2512 // A threadprivate directive must lexically precede all references to any
2513 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002514 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2515 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002516 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002517 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002518 return ExprError();
2519 }
2520
2521 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002522 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2523 SourceLocation(), VD,
2524 /*RefersToEnclosingVariableOrCapture=*/false,
2525 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002526}
2527
Alexey Bataeved09d242014-05-28 05:53:51 +00002528Sema::DeclGroupPtrTy
2529Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2530 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002531 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002532 CurContext->addDecl(D);
2533 return DeclGroupPtrTy::make(DeclGroupRef(D));
2534 }
David Blaikie0403cb12016-01-15 23:43:25 +00002535 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002536}
2537
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002538namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002539class LocalVarRefChecker final
2540 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002541 Sema &SemaRef;
2542
2543public:
2544 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002545 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002546 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002547 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002548 diag::err_omp_local_var_in_threadprivate_init)
2549 << E->getSourceRange();
2550 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2551 << VD << VD->getSourceRange();
2552 return true;
2553 }
2554 }
2555 return false;
2556 }
2557 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002558 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002559 if (Child && Visit(Child))
2560 return true;
2561 }
2562 return false;
2563 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002564 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002565};
2566} // namespace
2567
Alexey Bataeved09d242014-05-28 05:53:51 +00002568OMPThreadPrivateDecl *
2569Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002570 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002571 for (Expr *RefExpr : VarList) {
2572 auto *DE = cast<DeclRefExpr>(RefExpr);
2573 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002574 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002575
Alexey Bataev376b4a42016-02-09 09:41:09 +00002576 // Mark variable as used.
2577 VD->setReferenced();
2578 VD->markUsed(Context);
2579
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002580 QualType QType = VD->getType();
2581 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2582 // It will be analyzed later.
2583 Vars.push_back(DE);
2584 continue;
2585 }
2586
Alexey Bataeva769e072013-03-22 06:34:35 +00002587 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2588 // A threadprivate variable must not have an incomplete type.
2589 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002590 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002591 continue;
2592 }
2593
2594 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2595 // A threadprivate variable must not have a reference type.
2596 if (VD->getType()->isReferenceType()) {
2597 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002598 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2599 bool IsDecl =
2600 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2601 Diag(VD->getLocation(),
2602 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2603 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002604 continue;
2605 }
2606
Samuel Antaof8b50122015-07-13 22:54:53 +00002607 // Check if this is a TLS variable. If TLS is not being supported, produce
2608 // the corresponding diagnostic.
2609 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2610 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2611 getLangOpts().OpenMPUseTLS &&
2612 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002613 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2614 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002615 Diag(ILoc, diag::err_omp_var_thread_local)
2616 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002617 bool IsDecl =
2618 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2619 Diag(VD->getLocation(),
2620 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2621 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002622 continue;
2623 }
2624
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002625 // Check if initial value of threadprivate variable reference variable with
2626 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002627 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002628 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002629 if (Checker.Visit(Init))
2630 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002631 }
2632
Alexey Bataeved09d242014-05-28 05:53:51 +00002633 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002634 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002635 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2636 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002637 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002638 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002639 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002640 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002641 if (!Vars.empty()) {
2642 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2643 Vars);
2644 D->setAccess(AS_public);
2645 }
2646 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002647}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002648
Alexey Bataev27ef9512019-03-20 20:14:22 +00002649static OMPAllocateDeclAttr::AllocatorTypeTy
2650getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2651 if (!Allocator)
2652 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2653 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2654 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002655 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002656 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002657 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataeve106f252019-04-01 14:25:31 +00002658 const Expr *AE = Allocator->IgnoreParenImpCasts();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002659 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2660 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2661 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
Alexey Bataeve106f252019-04-01 14:25:31 +00002662 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002663 llvm::FoldingSetNodeID AEId, DAEId;
2664 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2665 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2666 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002667 AllocatorKindRes = AllocatorKind;
2668 break;
2669 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002670 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002671 return AllocatorKindRes;
2672}
2673
Alexey Bataeve106f252019-04-01 14:25:31 +00002674static bool checkPreviousOMPAllocateAttribute(
2675 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2676 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2677 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2678 return false;
2679 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2680 Expr *PrevAllocator = A->getAllocator();
2681 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2682 getAllocatorKind(S, Stack, PrevAllocator);
2683 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2684 if (AllocatorsMatch &&
2685 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2686 Allocator && PrevAllocator) {
2687 const Expr *AE = Allocator->IgnoreParenImpCasts();
2688 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2689 llvm::FoldingSetNodeID AEId, PAEId;
2690 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2691 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2692 AllocatorsMatch = AEId == PAEId;
2693 }
2694 if (!AllocatorsMatch) {
2695 SmallString<256> AllocatorBuffer;
2696 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2697 if (Allocator)
2698 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2699 SmallString<256> PrevAllocatorBuffer;
2700 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2701 if (PrevAllocator)
2702 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2703 S.getPrintingPolicy());
2704
2705 SourceLocation AllocatorLoc =
2706 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2707 SourceRange AllocatorRange =
2708 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2709 SourceLocation PrevAllocatorLoc =
2710 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2711 SourceRange PrevAllocatorRange =
2712 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2713 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2714 << (Allocator ? 1 : 0) << AllocatorStream.str()
2715 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2716 << AllocatorRange;
2717 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2718 << PrevAllocatorRange;
2719 return true;
2720 }
2721 return false;
2722}
2723
2724static void
2725applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2726 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2727 Expr *Allocator, SourceRange SR) {
2728 if (VD->hasAttr<OMPAllocateDeclAttr>())
2729 return;
2730 if (Allocator &&
2731 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2732 Allocator->isInstantiationDependent() ||
2733 Allocator->containsUnexpandedParameterPack()))
2734 return;
2735 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2736 Allocator, SR);
2737 VD->addAttr(A);
2738 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2739 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2740}
2741
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002742Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2743 SourceLocation Loc, ArrayRef<Expr *> VarList,
2744 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2745 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2746 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002747 if (Clauses.empty()) {
Alexey Bataevf4936072019-03-22 15:32:02 +00002748 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2749 // allocate directives that appear in a target region must specify an
2750 // allocator clause unless a requires directive with the dynamic_allocators
2751 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002752 if (LangOpts.OpenMPIsDevice &&
2753 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002754 targetDiag(Loc, diag::err_expected_allocator_clause);
2755 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002756 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002757 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002758 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2759 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002760 SmallVector<Expr *, 8> Vars;
2761 for (Expr *RefExpr : VarList) {
2762 auto *DE = cast<DeclRefExpr>(RefExpr);
2763 auto *VD = cast<VarDecl>(DE->getDecl());
2764
2765 // Check if this is a TLS variable or global register.
2766 if (VD->getTLSKind() != VarDecl::TLS_None ||
2767 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2768 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2769 !VD->isLocalVarDecl()))
2770 continue;
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002771
Alexey Bataev282555a2019-03-19 20:33:44 +00002772 // If the used several times in the allocate directive, the same allocator
2773 // must be used.
Alexey Bataeve106f252019-04-01 14:25:31 +00002774 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2775 AllocatorKind, Allocator))
2776 continue;
Alexey Bataev282555a2019-03-19 20:33:44 +00002777
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002778 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2779 // If a list item has a static storage type, the allocator expression in the
2780 // allocator clause must be a constant expression that evaluates to one of
2781 // the predefined memory allocator values.
2782 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002783 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002784 Diag(Allocator->getExprLoc(),
2785 diag::err_omp_expected_predefined_allocator)
2786 << Allocator->getSourceRange();
2787 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2788 VarDecl::DeclarationOnly;
2789 Diag(VD->getLocation(),
2790 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2791 << VD;
2792 continue;
2793 }
2794 }
2795
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002796 Vars.push_back(RefExpr);
Alexey Bataeve106f252019-04-01 14:25:31 +00002797 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2798 DE->getSourceRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002799 }
2800 if (Vars.empty())
2801 return nullptr;
2802 if (!Owner)
2803 Owner = getCurLexicalContext();
Alexey Bataeve106f252019-04-01 14:25:31 +00002804 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002805 D->setAccess(AS_public);
2806 Owner->addDecl(D);
2807 return DeclGroupPtrTy::make(DeclGroupRef(D));
2808}
2809
2810Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002811Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2812 ArrayRef<OMPClause *> ClauseList) {
2813 OMPRequiresDecl *D = nullptr;
2814 if (!CurContext->isFileContext()) {
2815 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2816 } else {
2817 D = CheckOMPRequiresDecl(Loc, ClauseList);
2818 if (D) {
2819 CurContext->addDecl(D);
2820 DSAStack->addRequiresDecl(D);
2821 }
2822 }
2823 return DeclGroupPtrTy::make(DeclGroupRef(D));
2824}
2825
2826OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2827 ArrayRef<OMPClause *> ClauseList) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002828 /// For target specific clauses, the requires directive cannot be
2829 /// specified after the handling of any of the target regions in the
2830 /// current compilation unit.
2831 ArrayRef<SourceLocation> TargetLocations =
2832 DSAStack->getEncounteredTargetLocs();
2833 if (!TargetLocations.empty()) {
2834 for (const OMPClause *CNew : ClauseList) {
2835 // Check if any of the requires clauses affect target regions.
2836 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2837 isa<OMPUnifiedAddressClause>(CNew) ||
2838 isa<OMPReverseOffloadClause>(CNew) ||
2839 isa<OMPDynamicAllocatorsClause>(CNew)) {
2840 Diag(Loc, diag::err_omp_target_before_requires)
2841 << getOpenMPClauseName(CNew->getClauseKind());
2842 for (SourceLocation TargetLoc : TargetLocations) {
2843 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2844 }
2845 }
2846 }
2847 }
2848
Kelvin Li1408f912018-09-26 04:28:39 +00002849 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2850 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2851 ClauseList);
2852 return nullptr;
2853}
2854
Alexey Bataeve3727102018-04-18 15:57:46 +00002855static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2856 const ValueDecl *D,
2857 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002858 bool IsLoopIterVar = false) {
2859 if (DVar.RefExpr) {
2860 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2861 << getOpenMPClauseName(DVar.CKind);
2862 return;
2863 }
2864 enum {
2865 PDSA_StaticMemberShared,
2866 PDSA_StaticLocalVarShared,
2867 PDSA_LoopIterVarPrivate,
2868 PDSA_LoopIterVarLinear,
2869 PDSA_LoopIterVarLastprivate,
2870 PDSA_ConstVarShared,
2871 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002872 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002873 PDSA_LocalVarPrivate,
2874 PDSA_Implicit
2875 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002876 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002877 auto ReportLoc = D->getLocation();
2878 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002879 if (IsLoopIterVar) {
2880 if (DVar.CKind == OMPC_private)
2881 Reason = PDSA_LoopIterVarPrivate;
2882 else if (DVar.CKind == OMPC_lastprivate)
2883 Reason = PDSA_LoopIterVarLastprivate;
2884 else
2885 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002886 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2887 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002888 Reason = PDSA_TaskVarFirstprivate;
2889 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002890 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002891 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002892 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002893 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002894 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002895 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002896 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002897 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002898 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002899 ReportHint = true;
2900 Reason = PDSA_LocalVarPrivate;
2901 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002902 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002903 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002904 << Reason << ReportHint
2905 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2906 } else if (DVar.ImplicitDSALoc.isValid()) {
2907 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2908 << getOpenMPClauseName(DVar.CKind);
2909 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002910}
2911
cchene06f3e02019-11-15 13:02:06 -05002912static OpenMPMapClauseKind
2913getMapClauseKindFromModifier(OpenMPDefaultmapClauseModifier M,
2914 bool IsAggregateOrDeclareTarget) {
2915 OpenMPMapClauseKind Kind = OMPC_MAP_unknown;
2916 switch (M) {
2917 case OMPC_DEFAULTMAP_MODIFIER_alloc:
2918 Kind = OMPC_MAP_alloc;
2919 break;
2920 case OMPC_DEFAULTMAP_MODIFIER_to:
2921 Kind = OMPC_MAP_to;
2922 break;
2923 case OMPC_DEFAULTMAP_MODIFIER_from:
2924 Kind = OMPC_MAP_from;
2925 break;
2926 case OMPC_DEFAULTMAP_MODIFIER_tofrom:
2927 Kind = OMPC_MAP_tofrom;
2928 break;
2929 case OMPC_DEFAULTMAP_MODIFIER_firstprivate:
2930 case OMPC_DEFAULTMAP_MODIFIER_last:
2931 llvm_unreachable("Unexpected defaultmap implicit behavior");
2932 case OMPC_DEFAULTMAP_MODIFIER_none:
2933 case OMPC_DEFAULTMAP_MODIFIER_default:
2934 case OMPC_DEFAULTMAP_MODIFIER_unknown:
2935 // IsAggregateOrDeclareTarget could be true if:
2936 // 1. the implicit behavior for aggregate is tofrom
2937 // 2. it's a declare target link
2938 if (IsAggregateOrDeclareTarget) {
2939 Kind = OMPC_MAP_tofrom;
2940 break;
2941 }
2942 llvm_unreachable("Unexpected defaultmap implicit behavior");
2943 }
2944 assert(Kind != OMPC_MAP_unknown && "Expect map kind to be known");
2945 return Kind;
2946}
2947
Alexey Bataev758e55e2013-09-06 18:03:48 +00002948namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002949class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002950 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002951 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002952 bool ErrorFound = false;
Alexey Bataevc09c0652019-10-29 10:06:11 -04002953 bool TryCaptureCXXThisMembers = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00002954 CapturedStmt *CS = nullptr;
2955 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
cchene06f3e02019-11-15 13:02:06 -05002956 llvm::SmallVector<Expr *, 4> ImplicitMap[OMPC_MAP_delete];
Alexey Bataeve3727102018-04-18 15:57:46 +00002957 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2958 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002959
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002960 void VisitSubCaptures(OMPExecutableDirective *S) {
2961 // Check implicitly captured variables.
2962 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2963 return;
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002964 visitSubCaptures(S->getInnermostCapturedStmt());
Alexey Bataevc09c0652019-10-29 10:06:11 -04002965 // Try to capture inner this->member references to generate correct mappings
2966 // and diagnostics.
2967 if (TryCaptureCXXThisMembers ||
2968 (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2969 llvm::any_of(S->getInnermostCapturedStmt()->captures(),
2970 [](const CapturedStmt::Capture &C) {
2971 return C.capturesThis();
2972 }))) {
2973 bool SavedTryCaptureCXXThisMembers = TryCaptureCXXThisMembers;
2974 TryCaptureCXXThisMembers = true;
2975 Visit(S->getInnermostCapturedStmt()->getCapturedStmt());
2976 TryCaptureCXXThisMembers = SavedTryCaptureCXXThisMembers;
2977 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002978 }
2979
Alexey Bataev758e55e2013-09-06 18:03:48 +00002980public:
2981 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataevc09c0652019-10-29 10:06:11 -04002982 if (TryCaptureCXXThisMembers || E->isTypeDependent() ||
2983 E->isValueDependent() || E->containsUnexpandedParameterPack() ||
2984 E->isInstantiationDependent())
Alexey Bataev07b79c22016-04-29 09:56:11 +00002985 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002986 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev412254a2019-05-09 18:44:53 +00002987 // Check the datasharing rules for the expressions in the clauses.
2988 if (!CS) {
2989 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(VD))
2990 if (!CED->hasAttr<OMPCaptureNoInitAttr>()) {
2991 Visit(CED->getInit());
2992 return;
2993 }
Alexey Bataev1242d8f2019-06-28 20:45:14 +00002994 } else if (VD->isImplicit() || isa<OMPCapturedExprDecl>(VD))
2995 // Do not analyze internal variables and do not enclose them into
2996 // implicit clauses.
2997 return;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002998 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002999 // Skip internally declared variables.
Alexey Bataev412254a2019-05-09 18:44:53 +00003000 if (VD->hasLocalStorage() && CS && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00003001 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00003002
Alexey Bataeve3727102018-04-18 15:57:46 +00003003 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003004 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003005 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00003006 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00003007
Alexey Bataevafe50572017-10-06 17:00:28 +00003008 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00003009 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00003010 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev412254a2019-05-09 18:44:53 +00003011 if (VD->hasGlobalStorage() && CS && !CS->capturesVariable(VD) &&
Gheorghe-Teodor Bercea5254f0a2019-06-14 17:58:26 +00003012 (Stack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
3013 !Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00003014 return;
3015
Alexey Bataeve3727102018-04-18 15:57:46 +00003016 SourceLocation ELoc = E->getExprLoc();
3017 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003018 // The default(none) clause requires that each variable that is referenced
3019 // in the construct, and does not have a predetermined data-sharing
3020 // attribute, must have its data-sharing attribute explicitly determined
3021 // by being listed in a data-sharing attribute clause.
3022 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00003023 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00003024 VarsWithInheritedDSA.count(VD) == 0) {
3025 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00003026 return;
3027 }
3028
cchene06f3e02019-11-15 13:02:06 -05003029 // OpenMP 5.0 [2.19.7.2, defaultmap clause, Description]
3030 // If implicit-behavior is none, each variable referenced in the
3031 // construct that does not have a predetermined data-sharing attribute
3032 // and does not appear in a to or link clause on a declare target
3033 // directive must be listed in a data-mapping attribute clause, a
3034 // data-haring attribute clause (including a data-sharing attribute
3035 // clause on a combined construct where target. is one of the
3036 // constituent constructs), or an is_device_ptr clause.
Alexey Bataev6f7c8762019-11-22 11:09:33 -05003037 OpenMPDefaultmapClauseKind ClauseKind =
3038 getVariableCategoryFromDecl(SemaRef.getLangOpts(), VD);
cchene06f3e02019-11-15 13:02:06 -05003039 if (SemaRef.getLangOpts().OpenMP >= 50) {
3040 bool IsModifierNone = Stack->getDefaultmapModifier(ClauseKind) ==
3041 OMPC_DEFAULTMAP_MODIFIER_none;
3042 if (DVar.CKind == OMPC_unknown && IsModifierNone &&
3043 VarsWithInheritedDSA.count(VD) == 0 && !Res) {
3044 // Only check for data-mapping attribute and is_device_ptr here
3045 // since we have already make sure that the declaration does not
3046 // have a data-sharing attribute above
3047 if (!Stack->checkMappableExprComponentListsForDecl(
3048 VD, /*CurrentRegionOnly=*/true,
3049 [VD](OMPClauseMappableExprCommon::MappableExprComponentListRef
3050 MapExprComponents,
3051 OpenMPClauseKind) {
3052 auto MI = MapExprComponents.rbegin();
3053 auto ME = MapExprComponents.rend();
3054 return MI != ME && MI->getAssociatedDeclaration() == VD;
3055 })) {
3056 VarsWithInheritedDSA[VD] = E;
3057 return;
3058 }
3059 }
3060 }
3061
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003062 if (isOpenMPTargetExecutionDirective(DKind) &&
3063 !Stack->isLoopControlVariable(VD).first) {
3064 if (!Stack->checkMappableExprComponentListsForDecl(
3065 VD, /*CurrentRegionOnly=*/true,
3066 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3067 StackComponents,
3068 OpenMPClauseKind) {
3069 // Variable is used if it has been marked as an array, array
3070 // section or the variable iself.
3071 return StackComponents.size() == 1 ||
3072 std::all_of(
3073 std::next(StackComponents.rbegin()),
3074 StackComponents.rend(),
3075 [](const OMPClauseMappableExprCommon::
3076 MappableComponent &MC) {
3077 return MC.getAssociatedDeclaration() ==
3078 nullptr &&
3079 (isa<OMPArraySectionExpr>(
3080 MC.getAssociatedExpression()) ||
3081 isa<ArraySubscriptExpr>(
3082 MC.getAssociatedExpression()));
3083 });
3084 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00003085 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003086 // By default lambdas are captured as firstprivates.
3087 if (const auto *RD =
3088 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00003089 IsFirstprivate = RD->isLambda();
3090 IsFirstprivate =
cchene06f3e02019-11-15 13:02:06 -05003091 IsFirstprivate || (Stack->mustBeFirstprivate(ClauseKind) && !Res);
3092 if (IsFirstprivate) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003093 ImplicitFirstprivate.emplace_back(E);
cchene06f3e02019-11-15 13:02:06 -05003094 } else {
3095 OpenMPDefaultmapClauseModifier M =
3096 Stack->getDefaultmapModifier(ClauseKind);
3097 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3098 M, ClauseKind == OMPC_DEFAULTMAP_aggregate || Res);
3099 ImplicitMap[Kind].emplace_back(E);
3100 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003101 return;
3102 }
3103 }
3104
Alexey Bataev758e55e2013-09-06 18:03:48 +00003105 // OpenMP [2.9.3.6, Restrictions, p.2]
3106 // A list item that appears in a reduction clause of the innermost
3107 // enclosing worksharing or parallel construct may not be accessed in an
3108 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003109 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00003110 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3111 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003112 return isOpenMPParallelDirective(K) ||
3113 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3114 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00003115 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00003116 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00003117 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00003118 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00003119 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00003120 return;
3121 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003122
3123 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00003124 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00003125 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00003126 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003127 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00003128 return;
3129 }
3130
3131 // Store implicitly used globals with declare target link for parent
3132 // target.
3133 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
3134 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
3135 Stack->addToParentTargetRegionLinkGlobals(E);
3136 return;
3137 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003138 }
3139 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003140 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00003141 if (E->isTypeDependent() || E->isValueDependent() ||
3142 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
3143 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003144 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003145 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00003146 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003147 if (!FD)
3148 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003149 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003150 // Check if the variable has explicit DSA set and stop analysis if it
3151 // so.
3152 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
3153 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003154
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003155 if (isOpenMPTargetExecutionDirective(DKind) &&
3156 !Stack->isLoopControlVariable(FD).first &&
3157 !Stack->checkMappableExprComponentListsForDecl(
3158 FD, /*CurrentRegionOnly=*/true,
3159 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
3160 StackComponents,
3161 OpenMPClauseKind) {
3162 return isa<CXXThisExpr>(
3163 cast<MemberExpr>(
3164 StackComponents.back().getAssociatedExpression())
3165 ->getBase()
3166 ->IgnoreParens());
3167 })) {
3168 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
3169 // A bit-field cannot appear in a map clause.
3170 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003171 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003172 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00003173
3174 // Check to see if the member expression is referencing a class that
3175 // has already been explicitly mapped
3176 if (Stack->isClassPreviouslyMapped(TE->getType()))
3177 return;
3178
cchene06f3e02019-11-15 13:02:06 -05003179 OpenMPDefaultmapClauseModifier Modifier =
3180 Stack->getDefaultmapModifier(OMPC_DEFAULTMAP_aggregate);
3181 OpenMPMapClauseKind Kind = getMapClauseKindFromModifier(
3182 Modifier, /*IsAggregateOrDeclareTarget*/ true);
3183 ImplicitMap[Kind].emplace_back(E);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003184 return;
3185 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003186
Alexey Bataeve3727102018-04-18 15:57:46 +00003187 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003188 // OpenMP [2.9.3.6, Restrictions, p.2]
3189 // A list item that appears in a reduction clause of the innermost
3190 // enclosing worksharing or parallel construct may not be accessed in
3191 // an explicit task.
3192 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00003193 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
3194 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003195 return isOpenMPParallelDirective(K) ||
3196 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
3197 },
3198 /*FromParent=*/true);
3199 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
3200 ErrorFound = true;
3201 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00003202 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003203 return;
3204 }
3205
3206 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00003207 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003208 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00003209 !Stack->isLoopControlVariable(FD).first) {
3210 // Check if there is a captured expression for the current field in the
3211 // region. Do not mark it as firstprivate unless there is no captured
3212 // expression.
3213 // TODO: try to make it firstprivate.
3214 if (DVar.CKind != OMPC_unknown)
3215 ImplicitFirstprivate.push_back(E);
3216 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003217 return;
3218 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003219 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003220 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00003221 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00003222 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00003223 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00003224 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003225 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
3226 if (!Stack->checkMappableExprComponentListsForDecl(
3227 VD, /*CurrentRegionOnly=*/true,
3228 [&CurComponents](
3229 OMPClauseMappableExprCommon::MappableExprComponentListRef
3230 StackComponents,
3231 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003232 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00003233 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003234 for (const auto &SC : llvm::reverse(StackComponents)) {
3235 // Do both expressions have the same kind?
3236 if (CCI->getAssociatedExpression()->getStmtClass() !=
3237 SC.getAssociatedExpression()->getStmtClass())
3238 if (!(isa<OMPArraySectionExpr>(
3239 SC.getAssociatedExpression()) &&
3240 isa<ArraySubscriptExpr>(
3241 CCI->getAssociatedExpression())))
3242 return false;
3243
Alexey Bataeve3727102018-04-18 15:57:46 +00003244 const Decl *CCD = CCI->getAssociatedDeclaration();
3245 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003246 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
3247 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
3248 if (SCD != CCD)
3249 return false;
3250 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00003251 if (CCI == CCE)
3252 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003253 }
3254 return true;
3255 })) {
3256 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003257 }
Alexey Bataevc09c0652019-10-29 10:06:11 -04003258 } else if (!TryCaptureCXXThisMembers) {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00003259 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00003260 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00003261 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003262 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003263 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003264 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003265 // for task|target directives.
3266 // Skip analysis of arguments of implicitly defined map clause for target
3267 // directives.
3268 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
3269 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003270 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003271 if (CC)
3272 Visit(CC);
3273 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003274 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003275 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00003276 // Check implicitly captured variables.
3277 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00003278 }
3279 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003280 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003281 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00003282 // Check implicitly captured variables in the task-based directives to
3283 // check if they must be firstprivatized.
3284 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00003285 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003286 }
Alexey Bataeved09d242014-05-28 05:53:51 +00003287 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003288
Alexey Bataev1242d8f2019-06-28 20:45:14 +00003289 void visitSubCaptures(CapturedStmt *S) {
3290 for (const CapturedStmt::Capture &Cap : S->captures()) {
3291 if (!Cap.capturesVariable() && !Cap.capturesVariableByCopy())
3292 continue;
3293 VarDecl *VD = Cap.getCapturedVar();
3294 // Do not try to map the variable if it or its sub-component was mapped
3295 // already.
3296 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
3297 Stack->checkMappableExprComponentListsForDecl(
3298 VD, /*CurrentRegionOnly=*/true,
3299 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
3300 OpenMPClauseKind) { return true; }))
3301 continue;
3302 DeclRefExpr *DRE = buildDeclRefExpr(
3303 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
3304 Cap.getLocation(), /*RefersToCapture=*/true);
3305 Visit(DRE);
3306 }
3307 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003308 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003309 ArrayRef<Expr *> getImplicitFirstprivate() const {
3310 return ImplicitFirstprivate;
3311 }
cchene06f3e02019-11-15 13:02:06 -05003312 ArrayRef<Expr *> getImplicitMap(OpenMPDefaultmapClauseKind Kind) const {
3313 return ImplicitMap[Kind];
3314 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003315 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003316 return VarsWithInheritedDSA;
3317 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003318
Alexey Bataev7ff55242014-06-19 09:13:45 +00003319 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00003320 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
3321 // Process declare target link variables for the target directives.
3322 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
3323 for (DeclRefExpr *E : Stack->getLinkGlobals())
3324 Visit(E);
3325 }
3326 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003327};
Alexey Bataeved09d242014-05-28 05:53:51 +00003328} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00003329
Alexey Bataevbae9a792014-06-27 10:37:06 +00003330void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00003331 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00003332 case OMPD_parallel:
3333 case OMPD_parallel_for:
3334 case OMPD_parallel_for_simd:
3335 case OMPD_parallel_sections:
cchen47d60942019-12-05 13:43:48 -05003336 case OMPD_parallel_master:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00003337 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00003338 case OMPD_teams_distribute:
3339 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003340 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00003341 QualType KmpInt32PtrTy =
3342 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003343 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003344 std::make_pair(".global_tid.", KmpInt32PtrTy),
3345 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3346 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00003347 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003348 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3349 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00003350 break;
3351 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003352 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00003353 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00003354 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00003355 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00003356 case OMPD_target_teams_distribute:
3357 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003358 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3359 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3360 QualType KmpInt32PtrTy =
3361 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3362 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003363 FunctionProtoType::ExtProtoInfo EPI;
3364 EPI.Variadic = true;
3365 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3366 Sema::CapturedParamNameType Params[] = {
3367 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003368 std::make_pair(".part_id.", KmpInt32PtrTy),
3369 std::make_pair(".privates.", VoidPtrTy),
3370 std::make_pair(
3371 ".copy_fn.",
3372 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003373 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3374 std::make_pair(StringRef(), QualType()) // __context with shared vars
3375 };
3376 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003377 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00003378 // Mark this captured region as inlined, because we don't use outlined
3379 // function directly.
3380 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3381 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003382 Context, {}, AttributeCommonInfo::AS_Keyword,
3383 AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003384 Sema::CapturedParamNameType ParamsTarget[] = {
3385 std::make_pair(StringRef(), QualType()) // __context with shared vars
3386 };
3387 // Start a captured region for 'target' with no implicit parameters.
3388 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003389 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003390 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003391 std::make_pair(".global_tid.", KmpInt32PtrTy),
3392 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3393 std::make_pair(StringRef(), QualType()) // __context with shared vars
3394 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00003395 // Start a captured region for 'teams' or 'parallel'. Both regions have
3396 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003397 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003398 ParamsTeamsOrParallel, /*OpenMPCaptureLevel=*/2);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003399 break;
3400 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00003401 case OMPD_target:
3402 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003403 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3404 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3405 QualType KmpInt32PtrTy =
3406 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3407 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003408 FunctionProtoType::ExtProtoInfo EPI;
3409 EPI.Variadic = true;
3410 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3411 Sema::CapturedParamNameType Params[] = {
3412 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003413 std::make_pair(".part_id.", KmpInt32PtrTy),
3414 std::make_pair(".privates.", VoidPtrTy),
3415 std::make_pair(
3416 ".copy_fn.",
3417 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003418 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3419 std::make_pair(StringRef(), QualType()) // __context with shared vars
3420 };
3421 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003422 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003423 // Mark this captured region as inlined, because we don't use outlined
3424 // function directly.
3425 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3426 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003427 Context, {}, AttributeCommonInfo::AS_Keyword,
3428 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00003429 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003430 std::make_pair(StringRef(), QualType()),
3431 /*OpenMPCaptureLevel=*/1);
Alexey Bataev8451efa2018-01-15 19:06:12 +00003432 break;
3433 }
Kelvin Li70a12c52016-07-13 21:51:49 +00003434 case OMPD_simd:
3435 case OMPD_for:
3436 case OMPD_for_simd:
3437 case OMPD_sections:
3438 case OMPD_section:
3439 case OMPD_single:
3440 case OMPD_master:
3441 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00003442 case OMPD_taskgroup:
3443 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00003444 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00003445 case OMPD_ordered:
3446 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00003447 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00003448 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00003449 std::make_pair(StringRef(), QualType()) // __context with shared vars
3450 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00003451 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3452 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003453 break;
3454 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003455 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003456 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3457 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3458 QualType KmpInt32PtrTy =
3459 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3460 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00003461 FunctionProtoType::ExtProtoInfo EPI;
3462 EPI.Variadic = true;
3463 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003464 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00003465 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003466 std::make_pair(".part_id.", KmpInt32PtrTy),
3467 std::make_pair(".privates.", VoidPtrTy),
3468 std::make_pair(
3469 ".copy_fn.",
3470 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00003471 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003472 std::make_pair(StringRef(), QualType()) // __context with shared vars
3473 };
3474 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3475 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00003476 // Mark this captured region as inlined, because we don't use outlined
3477 // function directly.
3478 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3479 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003480 Context, {}, AttributeCommonInfo::AS_Keyword,
3481 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003482 break;
3483 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00003484 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +00003485 case OMPD_taskloop_simd:
Alexey Bataevb8552ab2019-10-18 16:47:35 +00003486 case OMPD_master_taskloop:
3487 case OMPD_master_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00003488 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003489 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3490 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003491 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003492 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3493 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00003494 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003495 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3496 .withConst();
3497 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3498 QualType KmpInt32PtrTy =
3499 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3500 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00003501 FunctionProtoType::ExtProtoInfo EPI;
3502 EPI.Variadic = true;
3503 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00003504 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00003505 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003506 std::make_pair(".part_id.", KmpInt32PtrTy),
3507 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00003508 std::make_pair(
3509 ".copy_fn.",
3510 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3511 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3512 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003513 std::make_pair(".ub.", KmpUInt64Ty),
3514 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00003515 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003516 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00003517 std::make_pair(StringRef(), QualType()) // __context with shared vars
3518 };
3519 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3520 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00003521 // Mark this captured region as inlined, because we don't use outlined
3522 // function directly.
3523 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3524 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003525 Context, {}, AttributeCommonInfo::AS_Keyword,
3526 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00003527 break;
3528 }
Alexey Bataev14a388f2019-10-25 10:27:13 -04003529 case OMPD_parallel_master_taskloop:
3530 case OMPD_parallel_master_taskloop_simd: {
Alexey Bataev5bbcead2019-10-14 17:17:41 +00003531 QualType KmpInt32Ty =
3532 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
3533 .withConst();
3534 QualType KmpUInt64Ty =
3535 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
3536 .withConst();
3537 QualType KmpInt64Ty =
3538 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
3539 .withConst();
3540 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3541 QualType KmpInt32PtrTy =
3542 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3543 Sema::CapturedParamNameType ParamsParallel[] = {
3544 std::make_pair(".global_tid.", KmpInt32PtrTy),
3545 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3546 std::make_pair(StringRef(), QualType()) // __context with shared vars
3547 };
3548 // Start a captured region for 'parallel'.
3549 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3550 ParamsParallel, /*OpenMPCaptureLevel=*/1);
3551 QualType Args[] = {VoidPtrTy};
3552 FunctionProtoType::ExtProtoInfo EPI;
3553 EPI.Variadic = true;
3554 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3555 Sema::CapturedParamNameType Params[] = {
3556 std::make_pair(".global_tid.", KmpInt32Ty),
3557 std::make_pair(".part_id.", KmpInt32PtrTy),
3558 std::make_pair(".privates.", VoidPtrTy),
3559 std::make_pair(
3560 ".copy_fn.",
3561 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3562 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3563 std::make_pair(".lb.", KmpUInt64Ty),
3564 std::make_pair(".ub.", KmpUInt64Ty),
3565 std::make_pair(".st.", KmpInt64Ty),
3566 std::make_pair(".liter.", KmpInt32Ty),
3567 std::make_pair(".reductions.", VoidPtrTy),
3568 std::make_pair(StringRef(), QualType()) // __context with shared vars
3569 };
3570 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3571 Params, /*OpenMPCaptureLevel=*/2);
3572 // Mark this captured region as inlined, because we don't use outlined
3573 // function directly.
3574 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3575 AlwaysInlineAttr::CreateImplicit(
3576 Context, {}, AttributeCommonInfo::AS_Keyword,
3577 AlwaysInlineAttr::Keyword_forceinline));
3578 break;
3579 }
Kelvin Li4a39add2016-07-05 05:00:15 +00003580 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00003581 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003582 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00003583 QualType KmpInt32PtrTy =
3584 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3585 Sema::CapturedParamNameType Params[] = {
3586 std::make_pair(".global_tid.", KmpInt32PtrTy),
3587 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003588 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3589 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00003590 std::make_pair(StringRef(), QualType()) // __context with shared vars
3591 };
3592 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3593 Params);
3594 break;
3595 }
Alexey Bataev647dd842018-01-15 20:59:40 +00003596 case OMPD_target_teams_distribute_parallel_for:
3597 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003598 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003599 QualType KmpInt32PtrTy =
3600 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003601 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003602
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003603 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003604 FunctionProtoType::ExtProtoInfo EPI;
3605 EPI.Variadic = true;
3606 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3607 Sema::CapturedParamNameType Params[] = {
3608 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003609 std::make_pair(".part_id.", KmpInt32PtrTy),
3610 std::make_pair(".privates.", VoidPtrTy),
3611 std::make_pair(
3612 ".copy_fn.",
3613 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003614 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3615 std::make_pair(StringRef(), QualType()) // __context with shared vars
3616 };
3617 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003618 Params, /*OpenMPCaptureLevel=*/0);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003619 // Mark this captured region as inlined, because we don't use outlined
3620 // function directly.
3621 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3622 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003623 Context, {}, AttributeCommonInfo::AS_Keyword,
3624 AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003625 Sema::CapturedParamNameType ParamsTarget[] = {
3626 std::make_pair(StringRef(), QualType()) // __context with shared vars
3627 };
3628 // Start a captured region for 'target' with no implicit parameters.
3629 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003630 ParamsTarget, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003631
3632 Sema::CapturedParamNameType ParamsTeams[] = {
3633 std::make_pair(".global_tid.", KmpInt32PtrTy),
3634 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3635 std::make_pair(StringRef(), QualType()) // __context with shared vars
3636 };
3637 // Start a captured region for 'target' with no implicit parameters.
3638 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003639 ParamsTeams, /*OpenMPCaptureLevel=*/2);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003640
3641 Sema::CapturedParamNameType ParamsParallel[] = {
3642 std::make_pair(".global_tid.", KmpInt32PtrTy),
3643 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003644 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3645 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003646 std::make_pair(StringRef(), QualType()) // __context with shared vars
3647 };
3648 // Start a captured region for 'teams' or 'parallel'. Both regions have
3649 // the same implicit parameters.
3650 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003651 ParamsParallel, /*OpenMPCaptureLevel=*/3);
Carlo Bertolli52978c32018-01-03 21:12:44 +00003652 break;
3653 }
3654
Alexey Bataev46506272017-12-05 17:41:34 +00003655 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003656 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003657 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003658 QualType KmpInt32PtrTy =
3659 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3660
3661 Sema::CapturedParamNameType ParamsTeams[] = {
3662 std::make_pair(".global_tid.", KmpInt32PtrTy),
3663 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3664 std::make_pair(StringRef(), QualType()) // __context with shared vars
3665 };
3666 // Start a captured region for 'target' with no implicit parameters.
3667 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003668 ParamsTeams, /*OpenMPCaptureLevel=*/0);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003669
3670 Sema::CapturedParamNameType ParamsParallel[] = {
3671 std::make_pair(".global_tid.", KmpInt32PtrTy),
3672 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003673 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3674 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003675 std::make_pair(StringRef(), QualType()) // __context with shared vars
3676 };
3677 // Start a captured region for 'teams' or 'parallel'. Both regions have
3678 // the same implicit parameters.
3679 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Joel E. Denny7d5bc552019-08-22 03:34:30 +00003680 ParamsParallel, /*OpenMPCaptureLevel=*/1);
Carlo Bertolli62fae152017-11-20 20:46:39 +00003681 break;
3682 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003683 case OMPD_target_update:
3684 case OMPD_target_enter_data:
3685 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003686 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3687 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3688 QualType KmpInt32PtrTy =
3689 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3690 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003691 FunctionProtoType::ExtProtoInfo EPI;
3692 EPI.Variadic = true;
3693 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3694 Sema::CapturedParamNameType Params[] = {
3695 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003696 std::make_pair(".part_id.", KmpInt32PtrTy),
3697 std::make_pair(".privates.", VoidPtrTy),
3698 std::make_pair(
3699 ".copy_fn.",
3700 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003701 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3702 std::make_pair(StringRef(), QualType()) // __context with shared vars
3703 };
3704 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3705 Params);
3706 // Mark this captured region as inlined, because we don't use outlined
3707 // function directly.
3708 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3709 AlwaysInlineAttr::CreateImplicit(
Erich Keane6a24e802019-09-13 17:39:31 +00003710 Context, {}, AttributeCommonInfo::AS_Keyword,
3711 AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003712 break;
3713 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003714 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003715 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003716 case OMPD_taskyield:
3717 case OMPD_barrier:
3718 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003719 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003720 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003721 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003722 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003723 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003724 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003725 case OMPD_declare_target:
3726 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003727 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00003728 case OMPD_declare_variant:
Alexey Bataev9959db52014-05-06 10:08:46 +00003729 llvm_unreachable("OpenMP Directive is not allowed");
3730 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003731 llvm_unreachable("Unknown OpenMP directive");
3732 }
3733}
3734
Alexey Bataev0e100032019-10-14 16:44:01 +00003735int Sema::getNumberOfConstructScopes(unsigned Level) const {
3736 return getOpenMPCaptureLevels(DSAStack->getDirective(Level));
3737}
3738
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003739int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3740 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3741 getOpenMPCaptureRegions(CaptureRegions, DKind);
3742 return CaptureRegions.size();
3743}
3744
Alexey Bataev3392d762016-02-16 11:18:12 +00003745static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003746 Expr *CaptureExpr, bool WithInit,
3747 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003748 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003749 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003750 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003751 QualType Ty = Init->getType();
3752 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003753 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003754 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003755 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003756 Ty = C.getPointerType(Ty);
3757 ExprResult Res =
3758 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3759 if (!Res.isUsable())
3760 return nullptr;
3761 Init = Res.get();
3762 }
Alexey Bataev61205072016-03-02 04:57:40 +00003763 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003764 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003765 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003766 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003767 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003768 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003769 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003770 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003771 return CED;
3772}
3773
Alexey Bataev61205072016-03-02 04:57:40 +00003774static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3775 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003776 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003777 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003778 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003779 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003780 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3781 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003782 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003783 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003784}
3785
Alexey Bataev5a3af132016-03-29 08:58:54 +00003786static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003787 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003788 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003789 OMPCapturedExprDecl *CD = buildCaptureDecl(
3790 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3791 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003792 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3793 CaptureExpr->getExprLoc());
3794 }
3795 ExprResult Res = Ref;
3796 if (!S.getLangOpts().CPlusPlus &&
3797 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003798 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003799 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003800 if (!Res.isUsable())
3801 return ExprError();
3802 }
3803 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003804}
3805
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003806namespace {
3807// OpenMP directives parsed in this section are represented as a
3808// CapturedStatement with an associated statement. If a syntax error
3809// is detected during the parsing of the associated statement, the
3810// compiler must abort processing and close the CapturedStatement.
3811//
3812// Combined directives such as 'target parallel' have more than one
3813// nested CapturedStatements. This RAII ensures that we unwind out
3814// of all the nested CapturedStatements when an error is found.
3815class CaptureRegionUnwinderRAII {
3816private:
3817 Sema &S;
3818 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003819 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003820
3821public:
3822 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3823 OpenMPDirectiveKind DKind)
3824 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3825 ~CaptureRegionUnwinderRAII() {
3826 if (ErrorFound) {
3827 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3828 while (--ThisCaptureLevel >= 0)
3829 S.ActOnCapturedRegionError();
3830 }
3831 }
3832};
3833} // namespace
3834
Alexey Bataevb600ae32019-07-01 17:46:52 +00003835void Sema::tryCaptureOpenMPLambdas(ValueDecl *V) {
3836 // Capture variables captured by reference in lambdas for target-based
3837 // directives.
3838 if (!CurContext->isDependentContext() &&
3839 (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) ||
3840 isOpenMPTargetDataManagementDirective(
3841 DSAStack->getCurrentDirective()))) {
3842 QualType Type = V->getType();
3843 if (const auto *RD = Type.getCanonicalType()
3844 .getNonReferenceType()
3845 ->getAsCXXRecordDecl()) {
3846 bool SavedForceCaptureByReferenceInTargetExecutable =
3847 DSAStack->isForceCaptureByReferenceInTargetExecutable();
3848 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3849 /*V=*/true);
3850 if (RD->isLambda()) {
3851 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
3852 FieldDecl *ThisCapture;
3853 RD->getCaptureFields(Captures, ThisCapture);
3854 for (const LambdaCapture &LC : RD->captures()) {
3855 if (LC.getCaptureKind() == LCK_ByRef) {
3856 VarDecl *VD = LC.getCapturedVar();
3857 DeclContext *VDC = VD->getDeclContext();
3858 if (!VDC->Encloses(CurContext))
3859 continue;
3860 MarkVariableReferenced(LC.getLocation(), VD);
3861 } else if (LC.getCaptureKind() == LCK_This) {
3862 QualType ThisTy = getCurrentThisType();
3863 if (!ThisTy.isNull() &&
3864 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
3865 CheckCXXThisCapture(LC.getLocation());
3866 }
3867 }
3868 }
3869 DSAStack->setForceCaptureByReferenceInTargetExecutable(
3870 SavedForceCaptureByReferenceInTargetExecutable);
3871 }
3872 }
3873}
3874
Alexey Bataevcb8e6912020-01-31 16:09:26 -05003875static bool checkOrderedOrderSpecified(Sema &S,
3876 const ArrayRef<OMPClause *> Clauses) {
3877 const OMPOrderedClause *Ordered = nullptr;
3878 const OMPOrderClause *Order = nullptr;
3879
3880 for (const OMPClause *Clause : Clauses) {
3881 if (Clause->getClauseKind() == OMPC_ordered)
3882 Ordered = cast<OMPOrderedClause>(Clause);
3883 else if (Clause->getClauseKind() == OMPC_order) {
3884 Order = cast<OMPOrderClause>(Clause);
3885 if (Order->getKind() != OMPC_ORDER_concurrent)
3886 Order = nullptr;
3887 }
3888 if (Ordered && Order)
3889 break;
3890 }
3891
3892 if (Ordered && Order) {
3893 S.Diag(Order->getKindKwLoc(),
3894 diag::err_omp_simple_clause_incompatible_with_ordered)
3895 << getOpenMPClauseName(OMPC_order)
3896 << getOpenMPSimpleClauseTypeName(OMPC_order, OMPC_ORDER_concurrent)
3897 << SourceRange(Order->getBeginLoc(), Order->getEndLoc());
3898 S.Diag(Ordered->getBeginLoc(), diag::note_omp_ordered_param)
3899 << 0 << SourceRange(Ordered->getBeginLoc(), Ordered->getEndLoc());
3900 return true;
3901 }
3902 return false;
3903}
3904
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003905StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3906 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003907 bool ErrorFound = false;
3908 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3909 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003910 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003911 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003912 return StmtError();
3913 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003914
Alexey Bataev2ba67042017-11-28 21:11:44 +00003915 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3916 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003917 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003918 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003919 SmallVector<const OMPLinearClause *, 4> LCs;
3920 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003921 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003922 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003923 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3924 Clause->getClauseKind() == OMPC_in_reduction) {
3925 // Capture taskgroup task_reduction descriptors inside the tasking regions
3926 // with the corresponding in_reduction items.
3927 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003928 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003929 if (E)
3930 MarkDeclarationsReferencedInExpr(E);
3931 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003932 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003933 Clause->getClauseKind() == OMPC_copyprivate ||
3934 (getLangOpts().OpenMPUseTLS &&
3935 getASTContext().getTargetInfo().isTLSSupported() &&
3936 Clause->getClauseKind() == OMPC_copyin)) {
3937 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003938 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003939 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003940 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003941 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003942 }
3943 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003944 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003945 } else if (CaptureRegions.size() > 1 ||
3946 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003947 if (auto *C = OMPClauseWithPreInit::get(Clause))
3948 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003949 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003950 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003951 MarkDeclarationsReferencedInExpr(E);
3952 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003953 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003954 if (Clause->getClauseKind() == OMPC_schedule)
3955 SC = cast<OMPScheduleClause>(Clause);
3956 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003957 OC = cast<OMPOrderedClause>(Clause);
3958 else if (Clause->getClauseKind() == OMPC_linear)
3959 LCs.push_back(cast<OMPLinearClause>(Clause));
3960 }
Alexey Bataevf3c508f2020-01-23 10:47:16 -05003961 // Capture allocator expressions if used.
3962 for (Expr *E : DSAStack->getInnerAllocators())
3963 MarkDeclarationsReferencedInExpr(E);
Alexey Bataev6402bca2015-12-28 07:25:51 +00003964 // OpenMP, 2.7.1 Loop Construct, Restrictions
3965 // The nonmonotonic modifier cannot be specified if an ordered clause is
3966 // specified.
3967 if (SC &&
3968 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3969 SC->getSecondScheduleModifier() ==
3970 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3971 OC) {
3972 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3973 ? SC->getFirstScheduleModifierLoc()
3974 : SC->getSecondScheduleModifierLoc(),
Alexey Bataevcb8e6912020-01-31 16:09:26 -05003975 diag::err_omp_simple_clause_incompatible_with_ordered)
3976 << getOpenMPClauseName(OMPC_schedule)
3977 << getOpenMPSimpleClauseTypeName(OMPC_schedule,
3978 OMPC_SCHEDULE_MODIFIER_nonmonotonic)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003979 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003980 ErrorFound = true;
3981 }
Alexey Bataevcb8e6912020-01-31 16:09:26 -05003982 // OpenMP 5.0, 2.9.2 Worksharing-Loop Construct, Restrictions.
3983 // If an order(concurrent) clause is present, an ordered clause may not appear
3984 // on the same directive.
3985 if (checkOrderedOrderSpecified(*this, Clauses))
3986 ErrorFound = true;
Alexey Bataev993d2802015-12-28 06:23:08 +00003987 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003988 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003989 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003990 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003991 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003992 ErrorFound = true;
3993 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003994 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3995 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3996 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003997 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003998 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3999 ErrorFound = true;
4000 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00004001 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00004002 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00004003 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004004 StmtResult SR = S;
Richard Smith0621a8f2019-05-31 00:45:10 +00004005 unsigned CompletedRegions = 0;
Alexey Bataev2ba67042017-11-28 21:11:44 +00004006 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00004007 // Mark all variables in private list clauses as used in inner region.
4008 // Required for proper codegen of combined directives.
4009 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00004010 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004011 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00004012 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
4013 // Find the particular capture region for the clause if the
4014 // directive is a combined one with multiple capture regions.
4015 // If the directive is not a combined one, the capture region
4016 // associated with the clause is OMPD_unknown and is generated
4017 // only once.
4018 if (CaptureRegion == ThisCaptureRegion ||
4019 CaptureRegion == OMPD_unknown) {
4020 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004021 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00004022 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
4023 }
4024 }
4025 }
4026 }
Richard Smith0621a8f2019-05-31 00:45:10 +00004027 if (++CompletedRegions == CaptureRegions.size())
4028 DSAStack->setBodyComplete();
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004029 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00004030 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00004031 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00004032}
4033
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00004034static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
4035 OpenMPDirectiveKind CancelRegion,
4036 SourceLocation StartLoc) {
4037 // CancelRegion is only needed for cancel and cancellation_point.
4038 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
4039 return false;
4040
4041 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
4042 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
4043 return false;
4044
4045 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
4046 << getOpenMPDirectiveName(CancelRegion);
4047 return true;
4048}
4049
Alexey Bataeve3727102018-04-18 15:57:46 +00004050static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004051 OpenMPDirectiveKind CurrentRegion,
4052 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004053 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004054 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004055 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004056 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
4057 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00004058 bool NestingProhibited = false;
4059 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00004060 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004061 enum {
4062 NoRecommend,
4063 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00004064 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004065 ShouldBeInTargetRegion,
4066 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004067 } Recommend = NoRecommend;
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05004068 if (isOpenMPSimdDirective(ParentRegion) &&
4069 ((SemaRef.LangOpts.OpenMP <= 45 && CurrentRegion != OMPD_ordered) ||
4070 (SemaRef.LangOpts.OpenMP >= 50 && CurrentRegion != OMPD_ordered &&
4071 CurrentRegion != OMPD_simd && CurrentRegion != OMPD_atomic))) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004072 // OpenMP [2.16, Nesting of Regions]
4073 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004074 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00004075 // An ordered construct with the simd clause is the only OpenMP
4076 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00004077 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00004078 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
4079 // message.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05004080 // OpenMP 5.0 [2.9.3.1, simd Construct, Restrictions]
4081 // The only OpenMP constructs that can be encountered during execution of
4082 // a simd region are the atomic construct, the loop construct, the simd
4083 // construct and the ordered construct with the simd clause.
Kelvin Lifd8b5742016-07-01 14:30:25 +00004084 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
4085 ? diag::err_omp_prohibited_region_simd
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05004086 : diag::warn_omp_nesting_simd)
4087 << (SemaRef.LangOpts.OpenMP >= 50 ? 1 : 0);
Kelvin Lifd8b5742016-07-01 14:30:25 +00004088 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00004089 }
Alexey Bataev0162e452014-07-22 10:10:35 +00004090 if (ParentRegion == OMPD_atomic) {
4091 // OpenMP [2.16, Nesting of Regions]
4092 // OpenMP constructs may not be nested inside an atomic region.
4093 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
4094 return true;
4095 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004096 if (CurrentRegion == OMPD_section) {
4097 // OpenMP [2.7.2, sections Construct, Restrictions]
4098 // Orphaned section directives are prohibited. That is, the section
4099 // directives must appear within the sections construct and must not be
4100 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004101 if (ParentRegion != OMPD_sections &&
4102 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004103 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
4104 << (ParentRegion != OMPD_unknown)
4105 << getOpenMPDirectiveName(ParentRegion);
4106 return true;
4107 }
4108 return false;
4109 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00004110 // Allow some constructs (except teams and cancellation constructs) to be
4111 // orphaned (they could be used in functions, called from OpenMP regions
4112 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00004113 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00004114 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
4115 CurrentRegion != OMPD_cancellation_point &&
4116 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004117 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00004118 if (CurrentRegion == OMPD_cancellation_point ||
4119 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004120 // OpenMP [2.16, Nesting of Regions]
4121 // A cancellation point construct for which construct-type-clause is
4122 // taskgroup must be nested inside a task construct. A cancellation
4123 // point construct for which construct-type-clause is not taskgroup must
4124 // be closely nested inside an OpenMP construct that matches the type
4125 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00004126 // A cancel construct for which construct-type-clause is taskgroup must be
4127 // nested inside a task construct. A cancel construct for which
4128 // construct-type-clause is not taskgroup must be closely nested inside an
4129 // OpenMP construct that matches the type specified in
4130 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004131 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004132 !((CancelRegion == OMPD_parallel &&
4133 (ParentRegion == OMPD_parallel ||
4134 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00004135 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004136 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00004137 ParentRegion == OMPD_target_parallel_for ||
4138 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00004139 ParentRegion == OMPD_teams_distribute_parallel_for ||
4140 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004141 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
4142 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00004143 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
4144 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00004145 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004146 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00004147 // OpenMP [2.16, Nesting of Regions]
4148 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004149 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00004150 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004151 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004152 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
4153 // OpenMP [2.16, Nesting of Regions]
4154 // A critical region may not be nested (closely or otherwise) inside a
4155 // critical region with the same name. Note that this restriction is not
4156 // sufficient to prevent deadlock.
4157 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00004158 bool DeadLock = Stack->hasDirective(
4159 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
4160 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00004161 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00004162 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
4163 PreviousCriticalLoc = Loc;
4164 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004165 }
4166 return false;
David Majnemer9d168222016-08-05 17:44:54 +00004167 },
4168 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004169 if (DeadLock) {
4170 SemaRef.Diag(StartLoc,
4171 diag::err_omp_prohibited_region_critical_same_name)
4172 << CurrentName.getName();
4173 if (PreviousCriticalLoc.isValid())
4174 SemaRef.Diag(PreviousCriticalLoc,
4175 diag::note_omp_previous_critical_region);
4176 return true;
4177 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004178 } else if (CurrentRegion == OMPD_barrier) {
4179 // OpenMP [2.16, Nesting of Regions]
4180 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00004181 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004182 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4183 isOpenMPTaskingDirective(ParentRegion) ||
4184 ParentRegion == OMPD_master ||
cchen47d60942019-12-05 13:43:48 -05004185 ParentRegion == OMPD_parallel_master ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004186 ParentRegion == OMPD_critical ||
4187 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00004188 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00004189 !isOpenMPParallelDirective(CurrentRegion) &&
4190 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00004191 // OpenMP [2.16, Nesting of Regions]
4192 // A worksharing region may not be closely nested inside a worksharing,
4193 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00004194 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
4195 isOpenMPTaskingDirective(ParentRegion) ||
4196 ParentRegion == OMPD_master ||
cchen47d60942019-12-05 13:43:48 -05004197 ParentRegion == OMPD_parallel_master ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004198 ParentRegion == OMPD_critical ||
4199 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004200 Recommend = ShouldBeInParallelRegion;
4201 } else if (CurrentRegion == OMPD_ordered) {
4202 // OpenMP [2.16, Nesting of Regions]
4203 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00004204 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004205 // An ordered region must be closely nested inside a loop region (or
4206 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004207 // OpenMP [2.8.1,simd Construct, Restrictions]
4208 // An ordered construct with the simd clause is the only OpenMP construct
4209 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004210 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00004211 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00004212 !(isOpenMPSimdDirective(ParentRegion) ||
4213 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004214 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00004215 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004216 // OpenMP [2.16, Nesting of Regions]
4217 // If specified, a teams construct must be contained within a target
4218 // construct.
Alexey Bataev7a54d762019-09-10 20:19:58 +00004219 NestingProhibited =
4220 (SemaRef.LangOpts.OpenMP <= 45 && ParentRegion != OMPD_target) ||
4221 (SemaRef.LangOpts.OpenMP >= 50 && ParentRegion != OMPD_unknown &&
4222 ParentRegion != OMPD_target);
Kelvin Li2b51f722016-07-26 04:32:50 +00004223 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004224 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004225 }
Kelvin Libf594a52016-12-17 05:48:59 +00004226 if (!NestingProhibited &&
4227 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
4228 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
4229 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00004230 // OpenMP [2.16, Nesting of Regions]
4231 // distribute, parallel, parallel sections, parallel workshare, and the
4232 // parallel loop and parallel loop SIMD constructs are the only OpenMP
4233 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004234 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
4235 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00004236 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00004237 }
David Majnemer9d168222016-08-05 17:44:54 +00004238 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00004239 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004240 // OpenMP 4.5 [2.17 Nesting of Regions]
4241 // The region associated with the distribute construct must be strictly
4242 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00004243 NestingProhibited =
4244 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004245 Recommend = ShouldBeInTeamsRegion;
4246 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004247 if (!NestingProhibited &&
4248 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
4249 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
4250 // OpenMP 4.5 [2.17 Nesting of Regions]
4251 // If a target, target update, target data, target enter data, or
4252 // target exit data construct is encountered during execution of a
4253 // target region, the behavior is unspecified.
4254 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004255 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00004256 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004257 if (isOpenMPTargetExecutionDirective(K)) {
4258 OffendingRegion = K;
4259 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004260 }
4261 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00004262 },
4263 false /* don't skip top directive */);
4264 CloseNesting = false;
4265 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004266 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00004267 if (OrphanSeen) {
4268 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
4269 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
4270 } else {
4271 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
4272 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
4273 << Recommend << getOpenMPDirectiveName(CurrentRegion);
4274 }
Alexey Bataev549210e2014-06-24 04:39:47 +00004275 return true;
4276 }
4277 }
4278 return false;
4279}
4280
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06004281struct Kind2Unsigned {
4282 using argument_type = OpenMPDirectiveKind;
4283 unsigned operator()(argument_type DK) { return unsigned(DK); }
4284};
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004285static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
4286 ArrayRef<OMPClause *> Clauses,
4287 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
4288 bool ErrorFound = false;
4289 unsigned NamedModifiersNumber = 0;
Johannes Doerferteb3e81f2019-11-04 22:00:49 -06004290 llvm::IndexedMap<const OMPIfClause *, Kind2Unsigned> FoundNameModifiers;
4291 FoundNameModifiers.resize(unsigned(OMPD_unknown) + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00004292 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00004293 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004294 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
4295 // At most one if clause without a directive-name-modifier can appear on
4296 // the directive.
4297 OpenMPDirectiveKind CurNM = IC->getNameModifier();
4298 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004299 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004300 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
4301 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
4302 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004303 } else if (CurNM != OMPD_unknown) {
4304 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004305 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00004306 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004307 FoundNameModifiers[CurNM] = IC;
4308 if (CurNM == OMPD_unknown)
4309 continue;
4310 // Check if the specified name modifier is allowed for the current
4311 // directive.
4312 // At most one if clause with the particular directive-name-modifier can
4313 // appear on the directive.
4314 bool MatchFound = false;
4315 for (auto NM : AllowedNameModifiers) {
4316 if (CurNM == NM) {
4317 MatchFound = true;
4318 break;
4319 }
4320 }
4321 if (!MatchFound) {
4322 S.Diag(IC->getNameModifierLoc(),
4323 diag::err_omp_wrong_if_directive_name_modifier)
4324 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
4325 ErrorFound = true;
4326 }
4327 }
4328 }
4329 // If any if clause on the directive includes a directive-name-modifier then
4330 // all if clauses on the directive must include a directive-name-modifier.
4331 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
4332 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004333 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004334 diag::err_omp_no_more_if_clause);
4335 } else {
4336 std::string Values;
4337 std::string Sep(", ");
4338 unsigned AllowedCnt = 0;
4339 unsigned TotalAllowedNum =
4340 AllowedNameModifiers.size() - NamedModifiersNumber;
4341 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
4342 ++Cnt) {
4343 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
4344 if (!FoundNameModifiers[NM]) {
4345 Values += "'";
4346 Values += getOpenMPDirectiveName(NM);
4347 Values += "'";
4348 if (AllowedCnt + 2 == TotalAllowedNum)
4349 Values += " or ";
4350 else if (AllowedCnt + 1 != TotalAllowedNum)
4351 Values += Sep;
4352 ++AllowedCnt;
4353 }
4354 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004355 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004356 diag::err_omp_unnamed_if_clause)
4357 << (TotalAllowedNum > 1) << Values;
4358 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004359 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00004360 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
4361 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004362 ErrorFound = true;
4363 }
4364 return ErrorFound;
4365}
4366
Alexey Bataev0860db92019-12-19 10:01:10 -05004367static std::pair<ValueDecl *, bool> getPrivateItem(Sema &S, Expr *&RefExpr,
4368 SourceLocation &ELoc,
4369 SourceRange &ERange,
4370 bool AllowArraySection) {
Alexey Bataeve106f252019-04-01 14:25:31 +00004371 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
4372 RefExpr->containsUnexpandedParameterPack())
4373 return std::make_pair(nullptr, true);
4374
4375 // OpenMP [3.1, C/C++]
4376 // A list item is a variable name.
4377 // OpenMP [2.9.3.3, Restrictions, p.1]
4378 // A variable that is part of another variable (as an array or
4379 // structure element) cannot appear in a private clause.
4380 RefExpr = RefExpr->IgnoreParens();
4381 enum {
4382 NoArrayExpr = -1,
4383 ArraySubscript = 0,
4384 OMPArraySection = 1
4385 } IsArrayExpr = NoArrayExpr;
4386 if (AllowArraySection) {
4387 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
4388 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
4389 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4390 Base = TempASE->getBase()->IgnoreParenImpCasts();
4391 RefExpr = Base;
4392 IsArrayExpr = ArraySubscript;
4393 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
4394 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
4395 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
4396 Base = TempOASE->getBase()->IgnoreParenImpCasts();
4397 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
4398 Base = TempASE->getBase()->IgnoreParenImpCasts();
4399 RefExpr = Base;
4400 IsArrayExpr = OMPArraySection;
4401 }
4402 }
4403 ELoc = RefExpr->getExprLoc();
4404 ERange = RefExpr->getSourceRange();
4405 RefExpr = RefExpr->IgnoreParenImpCasts();
4406 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
4407 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
4408 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
4409 (S.getCurrentThisType().isNull() || !ME ||
4410 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
4411 !isa<FieldDecl>(ME->getMemberDecl()))) {
4412 if (IsArrayExpr != NoArrayExpr) {
4413 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
4414 << ERange;
4415 } else {
4416 S.Diag(ELoc,
4417 AllowArraySection
4418 ? diag::err_omp_expected_var_name_member_expr_or_array_item
4419 : diag::err_omp_expected_var_name_member_expr)
4420 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
4421 }
4422 return std::make_pair(nullptr, false);
4423 }
4424 return std::make_pair(
4425 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
4426}
4427
4428static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00004429 ArrayRef<OMPClause *> Clauses) {
4430 assert(!S.CurContext->isDependentContext() &&
4431 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00004432 auto AllocateRange =
4433 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00004434 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
4435 DeclToCopy;
4436 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
4437 return isOpenMPPrivate(C->getClauseKind());
4438 });
4439 for (OMPClause *Cl : PrivateRange) {
4440 MutableArrayRef<Expr *>::iterator I, It, Et;
4441 if (Cl->getClauseKind() == OMPC_private) {
4442 auto *PC = cast<OMPPrivateClause>(Cl);
4443 I = PC->private_copies().begin();
4444 It = PC->varlist_begin();
4445 Et = PC->varlist_end();
4446 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
4447 auto *PC = cast<OMPFirstprivateClause>(Cl);
4448 I = PC->private_copies().begin();
4449 It = PC->varlist_begin();
4450 Et = PC->varlist_end();
4451 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
4452 auto *PC = cast<OMPLastprivateClause>(Cl);
4453 I = PC->private_copies().begin();
4454 It = PC->varlist_begin();
4455 Et = PC->varlist_end();
4456 } else if (Cl->getClauseKind() == OMPC_linear) {
4457 auto *PC = cast<OMPLinearClause>(Cl);
4458 I = PC->privates().begin();
4459 It = PC->varlist_begin();
4460 Et = PC->varlist_end();
4461 } else if (Cl->getClauseKind() == OMPC_reduction) {
4462 auto *PC = cast<OMPReductionClause>(Cl);
4463 I = PC->privates().begin();
4464 It = PC->varlist_begin();
4465 Et = PC->varlist_end();
4466 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
4467 auto *PC = cast<OMPTaskReductionClause>(Cl);
4468 I = PC->privates().begin();
4469 It = PC->varlist_begin();
4470 Et = PC->varlist_end();
4471 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
4472 auto *PC = cast<OMPInReductionClause>(Cl);
4473 I = PC->privates().begin();
4474 It = PC->varlist_begin();
4475 Et = PC->varlist_end();
4476 } else {
4477 llvm_unreachable("Expected private clause.");
4478 }
4479 for (Expr *E : llvm::make_range(It, Et)) {
4480 if (!*I) {
4481 ++I;
4482 continue;
4483 }
4484 SourceLocation ELoc;
4485 SourceRange ERange;
4486 Expr *SimpleRefExpr = E;
4487 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
4488 /*AllowArraySection=*/true);
4489 DeclToCopy.try_emplace(Res.first,
4490 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
4491 ++I;
4492 }
4493 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004494 for (OMPClause *C : AllocateRange) {
4495 auto *AC = cast<OMPAllocateClause>(C);
4496 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
4497 getAllocatorKind(S, Stack, AC->getAllocator());
4498 // OpenMP, 2.11.4 allocate Clause, Restrictions.
4499 // For task, taskloop or target directives, allocation requests to memory
4500 // allocators with the trait access set to thread result in unspecified
4501 // behavior.
4502 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
4503 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
4504 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
4505 S.Diag(AC->getAllocator()->getExprLoc(),
4506 diag::warn_omp_allocate_thread_on_task_target_directive)
4507 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00004508 }
4509 for (Expr *E : AC->varlists()) {
4510 SourceLocation ELoc;
4511 SourceRange ERange;
4512 Expr *SimpleRefExpr = E;
4513 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
4514 ValueDecl *VD = Res.first;
4515 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
4516 if (!isOpenMPPrivate(Data.CKind)) {
4517 S.Diag(E->getExprLoc(),
4518 diag::err_omp_expected_private_copy_for_allocate);
4519 continue;
4520 }
4521 VarDecl *PrivateVD = DeclToCopy[VD];
4522 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
4523 AllocatorKind, AC->getAllocator()))
4524 continue;
4525 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
4526 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00004527 }
4528 }
Alexey Bataev471171c2019-03-28 19:15:36 +00004529}
4530
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004531StmtResult Sema::ActOnOpenMPExecutableDirective(
4532 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
4533 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
4534 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004535 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00004536 // First check CancelRegion which is then used in checkNestingOfRegions.
4537 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
4538 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004539 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00004540 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00004541
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004542 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00004543 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004544 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00004545 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00004546 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004547 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
4548
4549 // Check default data sharing attributes for referenced variables.
4550 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00004551 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
4552 Stmt *S = AStmt;
4553 while (--ThisCaptureLevel >= 0)
4554 S = cast<CapturedStmt>(S)->getCapturedStmt();
4555 DSAChecker.Visit(S);
Alexey Bataev1242d8f2019-06-28 20:45:14 +00004556 if (!isOpenMPTargetDataManagementDirective(Kind) &&
4557 !isOpenMPTaskingDirective(Kind)) {
4558 // Visit subcaptures to generate implicit clauses for captured vars.
4559 auto *CS = cast<CapturedStmt>(AStmt);
4560 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
4561 getOpenMPCaptureRegions(CaptureRegions, Kind);
4562 // Ignore outer tasking regions for target directives.
4563 if (CaptureRegions.size() > 1 && CaptureRegions.front() == OMPD_task)
4564 CS = cast<CapturedStmt>(CS->getCapturedStmt());
4565 DSAChecker.visitSubCaptures(CS);
4566 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004567 if (DSAChecker.isErrorFound())
4568 return StmtError();
4569 // Generate list of implicitly defined firstprivate variables.
4570 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00004571
Alexey Bataev88202be2017-07-27 13:20:36 +00004572 SmallVector<Expr *, 4> ImplicitFirstprivates(
4573 DSAChecker.getImplicitFirstprivate().begin(),
4574 DSAChecker.getImplicitFirstprivate().end());
cchene06f3e02019-11-15 13:02:06 -05004575 SmallVector<Expr *, 4> ImplicitMaps[OMPC_MAP_delete];
4576 for (unsigned I = 0; I < OMPC_MAP_delete; ++I) {
4577 ArrayRef<Expr *> ImplicitMap =
4578 DSAChecker.getImplicitMap(static_cast<OpenMPDefaultmapClauseKind>(I));
4579 ImplicitMaps[I].append(ImplicitMap.begin(), ImplicitMap.end());
4580 }
Alexey Bataev88202be2017-07-27 13:20:36 +00004581 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00004582 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00004583 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004584 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00004585 if (E)
4586 ImplicitFirstprivates.emplace_back(E);
4587 }
4588 }
4589 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004590 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00004591 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
4592 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00004593 ClausesWithImplicit.push_back(Implicit);
4594 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00004595 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004596 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00004597 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004598 }
Alexey Bataev68446b72014-07-18 07:47:19 +00004599 }
cchene06f3e02019-11-15 13:02:06 -05004600 int ClauseKindCnt = -1;
4601 for (ArrayRef<Expr *> ImplicitMap : ImplicitMaps) {
4602 ++ClauseKindCnt;
4603 if (ImplicitMap.empty())
4604 continue;
Michael Kruse4304e9d2019-02-19 16:38:20 +00004605 CXXScopeSpec MapperIdScopeSpec;
4606 DeclarationNameInfo MapperId;
cchene06f3e02019-11-15 13:02:06 -05004607 auto Kind = static_cast<OpenMPMapClauseKind>(ClauseKindCnt);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004608 if (OMPClause *Implicit = ActOnOpenMPMapClause(
cchene06f3e02019-11-15 13:02:06 -05004609 llvm::None, llvm::None, MapperIdScopeSpec, MapperId, Kind,
4610 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
4611 ImplicitMap, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004612 ClausesWithImplicit.emplace_back(Implicit);
4613 ErrorFound |=
cchene06f3e02019-11-15 13:02:06 -05004614 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMap.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00004615 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004616 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00004617 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00004618 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004619 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00004620
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004621 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004622 switch (Kind) {
4623 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00004624 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
4625 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004626 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004627 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004628 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004629 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4630 VarsWithInheritedDSA);
Alexey Bataevd08c0562019-11-19 12:07:54 -05004631 if (LangOpts.OpenMP >= 50)
4632 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00004633 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00004634 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00004635 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
4636 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00004637 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00004638 case OMPD_for_simd:
4639 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4640 EndLoc, VarsWithInheritedDSA);
Alexey Bataev103f3c9e2019-11-20 15:59:03 -05004641 if (LangOpts.OpenMP >= 50)
4642 AllowedNameModifiers.push_back(OMPD_simd);
Alexander Musmanf82886e2014-09-18 05:12:34 +00004643 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00004644 case OMPD_sections:
4645 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
4646 EndLoc);
4647 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004648 case OMPD_section:
4649 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00004650 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00004651 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
4652 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00004653 case OMPD_single:
4654 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
4655 EndLoc);
4656 break;
Alexander Musman80c22892014-07-17 08:54:58 +00004657 case OMPD_master:
4658 assert(ClausesWithImplicit.empty() &&
4659 "No clauses are allowed for 'omp master' directive");
4660 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
4661 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004662 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00004663 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
4664 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00004665 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004666 case OMPD_parallel_for:
4667 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
4668 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004669 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00004670 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00004671 case OMPD_parallel_for_simd:
4672 Res = ActOnOpenMPParallelForSimdDirective(
4673 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004674 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevf59614d2019-11-21 10:00:56 -05004675 if (LangOpts.OpenMP >= 50)
4676 AllowedNameModifiers.push_back(OMPD_simd);
Alexander Musmane4e893b2014-09-23 09:33:00 +00004677 break;
cchen47d60942019-12-05 13:43:48 -05004678 case OMPD_parallel_master:
4679 Res = ActOnOpenMPParallelMasterDirective(ClausesWithImplicit, AStmt,
4680 StartLoc, EndLoc);
4681 AllowedNameModifiers.push_back(OMPD_parallel);
4682 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004683 case OMPD_parallel_sections:
4684 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
4685 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004686 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00004687 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004688 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004689 Res =
4690 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004691 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004692 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00004693 case OMPD_taskyield:
4694 assert(ClausesWithImplicit.empty() &&
4695 "No clauses are allowed for 'omp taskyield' directive");
4696 assert(AStmt == nullptr &&
4697 "No associated statement allowed for 'omp taskyield' directive");
4698 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
4699 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00004700 case OMPD_barrier:
4701 assert(ClausesWithImplicit.empty() &&
4702 "No clauses are allowed for 'omp barrier' directive");
4703 assert(AStmt == nullptr &&
4704 "No associated statement allowed for 'omp barrier' directive");
4705 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4706 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004707 case OMPD_taskwait:
4708 assert(ClausesWithImplicit.empty() &&
4709 "No clauses are allowed for 'omp taskwait' directive");
4710 assert(AStmt == nullptr &&
4711 "No associated statement allowed for 'omp taskwait' directive");
4712 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4713 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004714 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004715 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4716 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004717 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004718 case OMPD_flush:
4719 assert(AStmt == nullptr &&
4720 "No associated statement allowed for 'omp flush' directive");
4721 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4722 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004723 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004724 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4725 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004726 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004727 case OMPD_atomic:
4728 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4729 EndLoc);
4730 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004731 case OMPD_teams:
4732 Res =
4733 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4734 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004735 case OMPD_target:
4736 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4737 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004738 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004739 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004740 case OMPD_target_parallel:
4741 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4742 StartLoc, EndLoc);
4743 AllowedNameModifiers.push_back(OMPD_target);
4744 AllowedNameModifiers.push_back(OMPD_parallel);
4745 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004746 case OMPD_target_parallel_for:
4747 Res = ActOnOpenMPTargetParallelForDirective(
4748 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4749 AllowedNameModifiers.push_back(OMPD_target);
4750 AllowedNameModifiers.push_back(OMPD_parallel);
4751 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004752 case OMPD_cancellation_point:
4753 assert(ClausesWithImplicit.empty() &&
4754 "No clauses are allowed for 'omp cancellation point' directive");
4755 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4756 "cancellation point' directive");
4757 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4758 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004759 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004760 assert(AStmt == nullptr &&
4761 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004762 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4763 CancelRegion);
4764 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004765 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004766 case OMPD_target_data:
4767 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4768 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004769 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004770 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004771 case OMPD_target_enter_data:
4772 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004773 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004774 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4775 break;
Samuel Antao72590762016-01-19 20:04:50 +00004776 case OMPD_target_exit_data:
4777 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004778 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004779 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4780 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004781 case OMPD_taskloop:
4782 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4783 EndLoc, VarsWithInheritedDSA);
4784 AllowedNameModifiers.push_back(OMPD_taskloop);
4785 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004786 case OMPD_taskloop_simd:
4787 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4788 EndLoc, VarsWithInheritedDSA);
4789 AllowedNameModifiers.push_back(OMPD_taskloop);
Alexey Bataev61205822019-12-04 09:50:21 -05004790 if (LangOpts.OpenMP >= 50)
4791 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004792 break;
Alexey Bataev60e51c42019-10-10 20:13:02 +00004793 case OMPD_master_taskloop:
4794 Res = ActOnOpenMPMasterTaskLoopDirective(
4795 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4796 AllowedNameModifiers.push_back(OMPD_taskloop);
4797 break;
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004798 case OMPD_master_taskloop_simd:
4799 Res = ActOnOpenMPMasterTaskLoopSimdDirective(
4800 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4801 AllowedNameModifiers.push_back(OMPD_taskloop);
Alexey Bataev853961f2019-12-05 09:50:18 -05004802 if (LangOpts.OpenMP >= 50)
4803 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataevb8552ab2019-10-18 16:47:35 +00004804 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +00004805 case OMPD_parallel_master_taskloop:
4806 Res = ActOnOpenMPParallelMasterTaskLoopDirective(
4807 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4808 AllowedNameModifiers.push_back(OMPD_taskloop);
4809 AllowedNameModifiers.push_back(OMPD_parallel);
4810 break;
Alexey Bataev14a388f2019-10-25 10:27:13 -04004811 case OMPD_parallel_master_taskloop_simd:
4812 Res = ActOnOpenMPParallelMasterTaskLoopSimdDirective(
4813 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4814 AllowedNameModifiers.push_back(OMPD_taskloop);
4815 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5c517a62019-12-05 11:31:45 -05004816 if (LangOpts.OpenMP >= 50)
4817 AllowedNameModifiers.push_back(OMPD_simd);
Alexey Bataev14a388f2019-10-25 10:27:13 -04004818 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004819 case OMPD_distribute:
4820 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4821 EndLoc, VarsWithInheritedDSA);
4822 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004823 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004824 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4825 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004826 AllowedNameModifiers.push_back(OMPD_target_update);
4827 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004828 case OMPD_distribute_parallel_for:
4829 Res = ActOnOpenMPDistributeParallelForDirective(
4830 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4831 AllowedNameModifiers.push_back(OMPD_parallel);
4832 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004833 case OMPD_distribute_parallel_for_simd:
4834 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4835 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4836 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev52812f22019-12-05 13:22:15 -05004837 if (LangOpts.OpenMP >= 50)
4838 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li4a39add2016-07-05 05:00:15 +00004839 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004840 case OMPD_distribute_simd:
4841 Res = ActOnOpenMPDistributeSimdDirective(
4842 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev779a1802019-12-06 12:21:31 -05004843 if (LangOpts.OpenMP >= 50)
4844 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li787f3fc2016-07-06 04:45:38 +00004845 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004846 case OMPD_target_parallel_for_simd:
4847 Res = ActOnOpenMPTargetParallelForSimdDirective(
4848 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4849 AllowedNameModifiers.push_back(OMPD_target);
4850 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevda17a532019-12-10 11:37:03 -05004851 if (LangOpts.OpenMP >= 50)
4852 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Lia579b912016-07-14 02:54:56 +00004853 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004854 case OMPD_target_simd:
4855 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4856 EndLoc, VarsWithInheritedDSA);
4857 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataevef94cd12019-12-10 12:44:45 -05004858 if (LangOpts.OpenMP >= 50)
4859 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li986330c2016-07-20 22:57:10 +00004860 break;
Kelvin Li02532872016-08-05 14:37:37 +00004861 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004862 Res = ActOnOpenMPTeamsDistributeDirective(
4863 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004864 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004865 case OMPD_teams_distribute_simd:
4866 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4867 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev7b774b72019-12-11 11:20:47 -05004868 if (LangOpts.OpenMP >= 50)
4869 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li4e325f72016-10-25 12:50:55 +00004870 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004871 case OMPD_teams_distribute_parallel_for_simd:
4872 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4873 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4874 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev0b978942019-12-11 15:26:38 -05004875 if (LangOpts.OpenMP >= 50)
4876 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li579e41c2016-11-30 23:51:03 +00004877 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004878 case OMPD_teams_distribute_parallel_for:
4879 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4880 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4881 AllowedNameModifiers.push_back(OMPD_parallel);
4882 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004883 case OMPD_target_teams:
4884 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4885 EndLoc);
4886 AllowedNameModifiers.push_back(OMPD_target);
4887 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004888 case OMPD_target_teams_distribute:
4889 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4890 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4891 AllowedNameModifiers.push_back(OMPD_target);
4892 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004893 case OMPD_target_teams_distribute_parallel_for:
4894 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4895 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4896 AllowedNameModifiers.push_back(OMPD_target);
4897 AllowedNameModifiers.push_back(OMPD_parallel);
4898 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004899 case OMPD_target_teams_distribute_parallel_for_simd:
4900 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4901 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4902 AllowedNameModifiers.push_back(OMPD_target);
4903 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataevfd0c91b2019-12-16 10:27:39 -05004904 if (LangOpts.OpenMP >= 50)
4905 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Li1851df52017-01-03 05:23:48 +00004906 break;
Kelvin Lida681182017-01-10 18:08:18 +00004907 case OMPD_target_teams_distribute_simd:
4908 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4909 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4910 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev411e81a2019-12-16 11:16:46 -05004911 if (LangOpts.OpenMP >= 50)
4912 AllowedNameModifiers.push_back(OMPD_simd);
Kelvin Lida681182017-01-10 18:08:18 +00004913 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004914 case OMPD_declare_target:
4915 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004916 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004917 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004918 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004919 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004920 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004921 case OMPD_requires:
Alexey Bataevd158cf62019-09-13 20:18:17 +00004922 case OMPD_declare_variant:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004923 llvm_unreachable("OpenMP Directive is not allowed");
4924 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004925 llvm_unreachable("Unknown OpenMP directive");
4926 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004927
Roman Lebedevb5700602019-03-20 16:32:36 +00004928 ErrorFound = Res.isInvalid() || ErrorFound;
4929
Alexey Bataev412254a2019-05-09 18:44:53 +00004930 // Check variables in the clauses if default(none) was specified.
4931 if (DSAStack->getDefaultDSA() == DSA_none) {
4932 DSAAttrChecker DSAChecker(DSAStack, *this, nullptr);
4933 for (OMPClause *C : Clauses) {
4934 switch (C->getClauseKind()) {
4935 case OMPC_num_threads:
4936 case OMPC_dist_schedule:
4937 // Do not analyse if no parent teams directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004938 if (isOpenMPTeamsDirective(Kind))
Alexey Bataev412254a2019-05-09 18:44:53 +00004939 break;
4940 continue;
4941 case OMPC_if:
Alexey Bataev77d049d2019-11-21 11:03:26 -05004942 if (isOpenMPTeamsDirective(Kind) &&
Alexey Bataev412254a2019-05-09 18:44:53 +00004943 cast<OMPIfClause>(C)->getNameModifier() != OMPD_target)
4944 break;
Alexey Bataev77d049d2019-11-21 11:03:26 -05004945 if (isOpenMPParallelDirective(Kind) &&
4946 isOpenMPTaskLoopDirective(Kind) &&
4947 cast<OMPIfClause>(C)->getNameModifier() != OMPD_parallel)
4948 break;
Alexey Bataev412254a2019-05-09 18:44:53 +00004949 continue;
4950 case OMPC_schedule:
4951 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +00004952 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +00004953 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004954 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +00004955 case OMPC_priority:
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004956 // Do not analyze if no parent parallel directive.
Alexey Bataev77d049d2019-11-21 11:03:26 -05004957 if (isOpenMPParallelDirective(Kind))
Alexey Bataev3a842ec2019-10-15 19:37:05 +00004958 break;
4959 continue;
Alexey Bataev412254a2019-05-09 18:44:53 +00004960 case OMPC_ordered:
4961 case OMPC_device:
4962 case OMPC_num_teams:
4963 case OMPC_thread_limit:
Alexey Bataev412254a2019-05-09 18:44:53 +00004964 case OMPC_hint:
4965 case OMPC_collapse:
4966 case OMPC_safelen:
4967 case OMPC_simdlen:
Alexey Bataev412254a2019-05-09 18:44:53 +00004968 case OMPC_default:
4969 case OMPC_proc_bind:
4970 case OMPC_private:
4971 case OMPC_firstprivate:
4972 case OMPC_lastprivate:
4973 case OMPC_shared:
4974 case OMPC_reduction:
4975 case OMPC_task_reduction:
4976 case OMPC_in_reduction:
4977 case OMPC_linear:
4978 case OMPC_aligned:
4979 case OMPC_copyin:
4980 case OMPC_copyprivate:
4981 case OMPC_nowait:
4982 case OMPC_untied:
4983 case OMPC_mergeable:
4984 case OMPC_allocate:
4985 case OMPC_read:
4986 case OMPC_write:
4987 case OMPC_update:
4988 case OMPC_capture:
4989 case OMPC_seq_cst:
4990 case OMPC_depend:
4991 case OMPC_threads:
4992 case OMPC_simd:
4993 case OMPC_map:
4994 case OMPC_nogroup:
4995 case OMPC_defaultmap:
4996 case OMPC_to:
4997 case OMPC_from:
4998 case OMPC_use_device_ptr:
4999 case OMPC_is_device_ptr:
Alexey Bataevb6e70842019-12-16 15:54:17 -05005000 case OMPC_nontemporal:
Alexey Bataevcb8e6912020-01-31 16:09:26 -05005001 case OMPC_order:
Alexey Bataev412254a2019-05-09 18:44:53 +00005002 continue;
5003 case OMPC_allocator:
5004 case OMPC_flush:
5005 case OMPC_threadprivate:
5006 case OMPC_uniform:
5007 case OMPC_unknown:
5008 case OMPC_unified_address:
5009 case OMPC_unified_shared_memory:
5010 case OMPC_reverse_offload:
5011 case OMPC_dynamic_allocators:
5012 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +00005013 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +00005014 case OMPC_match:
Alexey Bataev412254a2019-05-09 18:44:53 +00005015 llvm_unreachable("Unexpected clause");
5016 }
5017 for (Stmt *CC : C->children()) {
5018 if (CC)
5019 DSAChecker.Visit(CC);
5020 }
5021 }
Alexey Bataevcb8e6912020-01-31 16:09:26 -05005022 for (const auto &P : DSAChecker.getVarsWithInheritedDSA())
Alexey Bataev412254a2019-05-09 18:44:53 +00005023 VarsWithInheritedDSA[P.getFirst()] = P.getSecond();
5024 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005025 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev1242d8f2019-06-28 20:45:14 +00005026 if (P.getFirst()->isImplicit() || isa<OMPCapturedExprDecl>(P.getFirst()))
5027 continue;
5028 ErrorFound = true;
cchene06f3e02019-11-15 13:02:06 -05005029 if (DSAStack->getDefaultDSA() == DSA_none) {
5030 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
5031 << P.first << P.second->getSourceRange();
5032 Diag(DSAStack->getDefaultDSALocation(), diag::note_omp_default_dsa_none);
5033 } else if (getLangOpts().OpenMP >= 50) {
5034 Diag(P.second->getExprLoc(),
5035 diag::err_omp_defaultmap_no_attr_for_variable)
5036 << P.first << P.second->getSourceRange();
5037 Diag(DSAStack->getDefaultDSALocation(),
5038 diag::note_omp_defaultmap_attr_none);
5039 }
Alexey Bataev4acb8592014-07-07 13:01:15 +00005040 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005041
5042 if (!AllowedNameModifiers.empty())
5043 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
5044 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00005045
Alexey Bataeved09d242014-05-28 05:53:51 +00005046 if (ErrorFound)
5047 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00005048
5049 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
5050 Res.getAs<OMPExecutableDirective>()
5051 ->getStructuredBlock()
5052 ->setIsOMPStructuredBlock(true);
5053 }
5054
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00005055 if (!CurContext->isDependentContext() &&
5056 isOpenMPTargetExecutionDirective(Kind) &&
5057 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
5058 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
5059 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
5060 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
5061 // Register target to DSA Stack.
5062 DSAStack->addTargetDirLocation(StartLoc);
5063 }
5064
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005065 return Res;
5066}
5067
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005068Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
5069 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00005070 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00005071 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
5072 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005073 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00005074 assert(Linears.size() == LinModifiers.size());
5075 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00005076 if (!DG || DG.get().isNull())
5077 return DeclGroupPtrTy();
5078
Alexey Bataevd158cf62019-09-13 20:18:17 +00005079 const int SimdId = 0;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005080 if (!DG.get().isSingleDecl()) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005081 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5082 << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005083 return DG;
5084 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005085 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00005086 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5087 ADecl = FTD->getTemplatedDecl();
5088
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005089 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5090 if (!FD) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005091 Diag(ADecl->getLocation(), diag::err_omp_function_expected) << SimdId;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005092 return DeclGroupPtrTy();
5093 }
5094
Alexey Bataev2af33e32016-04-07 12:45:37 +00005095 // OpenMP [2.8.2, declare simd construct, Description]
5096 // The parameter of the simdlen clause must be a constant positive integer
5097 // expression.
5098 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005099 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00005100 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005101 // OpenMP [2.8.2, declare simd construct, Description]
5102 // The special this pointer can be used as if was one of the arguments to the
5103 // function in any of the linear, aligned, or uniform clauses.
5104 // The uniform clause declares one or more arguments to have an invariant
5105 // value for all concurrent invocations of the function in the execution of a
5106 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00005107 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
5108 const Expr *UniformedLinearThis = nullptr;
5109 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005110 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005111 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5112 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005113 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5114 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00005115 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00005116 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005117 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005118 }
5119 if (isa<CXXThisExpr>(E)) {
5120 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005121 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005122 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005123 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5124 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00005125 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00005126 // OpenMP [2.8.2, declare simd construct, Description]
5127 // The aligned clause declares that the object to which each list item points
5128 // is aligned to the number of bytes expressed in the optional parameter of
5129 // the aligned clause.
5130 // The special this pointer can be used as if was one of the arguments to the
5131 // function in any of the linear, aligned, or uniform clauses.
5132 // The type of list items appearing in the aligned clause must be array,
5133 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00005134 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
5135 const Expr *AlignedThis = nullptr;
5136 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005137 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005138 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5139 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5140 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005141 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5142 FD->getParamDecl(PVD->getFunctionScopeIndex())
5143 ->getCanonicalDecl() == CanonPVD) {
5144 // OpenMP [2.8.1, simd construct, Restrictions]
5145 // A list-item cannot appear in more than one aligned clause.
5146 if (AlignedArgs.count(CanonPVD) > 0) {
Alexey Bataevb6e70842019-12-16 15:54:17 -05005147 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5148 << 1 << getOpenMPClauseName(OMPC_aligned)
5149 << E->getSourceRange();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005150 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
5151 diag::note_omp_explicit_dsa)
5152 << getOpenMPClauseName(OMPC_aligned);
5153 continue;
5154 }
5155 AlignedArgs[CanonPVD] = E;
5156 QualType QTy = PVD->getType()
5157 .getNonReferenceType()
5158 .getUnqualifiedType()
5159 .getCanonicalType();
5160 const Type *Ty = QTy.getTypePtrOrNull();
5161 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
5162 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
5163 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
5164 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
5165 }
5166 continue;
5167 }
5168 }
5169 if (isa<CXXThisExpr>(E)) {
5170 if (AlignedThis) {
Alexey Bataevb6e70842019-12-16 15:54:17 -05005171 Diag(E->getExprLoc(), diag::err_omp_used_in_clause_twice)
5172 << 2 << getOpenMPClauseName(OMPC_aligned) << E->getSourceRange();
Alexey Bataevd93d3762016-04-12 09:35:56 +00005173 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
5174 << getOpenMPClauseName(OMPC_aligned);
5175 }
5176 AlignedThis = E;
5177 continue;
5178 }
5179 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5180 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5181 }
5182 // The optional parameter of the aligned clause, alignment, must be a constant
5183 // positive integer expression. If no optional parameter is specified,
5184 // implementation-defined default alignments for SIMD instructions on the
5185 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00005186 SmallVector<const Expr *, 4> NewAligns;
5187 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00005188 ExprResult Align;
5189 if (E)
5190 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
5191 NewAligns.push_back(Align.get());
5192 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00005193 // OpenMP [2.8.2, declare simd construct, Description]
5194 // The linear clause declares one or more list items to be private to a SIMD
5195 // lane and to have a linear relationship with respect to the iteration space
5196 // of a loop.
5197 // The special this pointer can be used as if was one of the arguments to the
5198 // function in any of the linear, aligned, or uniform clauses.
5199 // When a linear-step expression is specified in a linear clause it must be
5200 // either a constant integer expression or an integer-typed parameter that is
5201 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00005202 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00005203 const bool IsUniformedThis = UniformedLinearThis != nullptr;
5204 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00005205 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005206 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
5207 ++MI;
5208 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00005209 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5210 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5211 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005212 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
5213 FD->getParamDecl(PVD->getFunctionScopeIndex())
5214 ->getCanonicalDecl() == CanonPVD) {
5215 // OpenMP [2.15.3.7, linear Clause, Restrictions]
5216 // A list-item cannot appear in more than one linear clause.
5217 if (LinearArgs.count(CanonPVD) > 0) {
5218 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5219 << getOpenMPClauseName(OMPC_linear)
5220 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
5221 Diag(LinearArgs[CanonPVD]->getExprLoc(),
5222 diag::note_omp_explicit_dsa)
5223 << getOpenMPClauseName(OMPC_linear);
5224 continue;
5225 }
5226 // Each argument can appear in at most one uniform or linear clause.
5227 if (UniformedArgs.count(CanonPVD) > 0) {
5228 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5229 << getOpenMPClauseName(OMPC_linear)
5230 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
5231 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
5232 diag::note_omp_explicit_dsa)
5233 << getOpenMPClauseName(OMPC_uniform);
5234 continue;
5235 }
5236 LinearArgs[CanonPVD] = E;
5237 if (E->isValueDependent() || E->isTypeDependent() ||
5238 E->isInstantiationDependent() ||
5239 E->containsUnexpandedParameterPack())
5240 continue;
5241 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
5242 PVD->getOriginalType());
5243 continue;
5244 }
5245 }
5246 if (isa<CXXThisExpr>(E)) {
5247 if (UniformedLinearThis) {
5248 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
5249 << getOpenMPClauseName(OMPC_linear)
5250 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
5251 << E->getSourceRange();
5252 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
5253 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
5254 : OMPC_linear);
5255 continue;
5256 }
5257 UniformedLinearThis = E;
5258 if (E->isValueDependent() || E->isTypeDependent() ||
5259 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
5260 continue;
5261 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
5262 E->getType());
5263 continue;
5264 }
5265 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
5266 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
5267 }
5268 Expr *Step = nullptr;
5269 Expr *NewStep = nullptr;
5270 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00005271 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005272 // Skip the same step expression, it was checked already.
5273 if (Step == E || !E) {
5274 NewSteps.push_back(E ? NewStep : nullptr);
5275 continue;
5276 }
5277 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00005278 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
5279 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
5280 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00005281 if (UniformedArgs.count(CanonPVD) == 0) {
5282 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
5283 << Step->getSourceRange();
5284 } else if (E->isValueDependent() || E->isTypeDependent() ||
5285 E->isInstantiationDependent() ||
5286 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00005287 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005288 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00005289 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00005290 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
5291 << Step->getSourceRange();
5292 }
5293 continue;
5294 }
5295 NewStep = Step;
5296 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
5297 !Step->isInstantiationDependent() &&
5298 !Step->containsUnexpandedParameterPack()) {
5299 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
5300 .get();
5301 if (NewStep)
5302 NewStep = VerifyIntegerConstantExpression(NewStep).get();
5303 }
5304 NewSteps.push_back(NewStep);
5305 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00005306 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
5307 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00005308 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00005309 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
5310 const_cast<Expr **>(Linears.data()), Linears.size(),
5311 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
5312 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00005313 ADecl->addAttr(NewAttr);
Alexey Bataeva0063072019-09-16 17:06:31 +00005314 return DG;
Alexey Bataev587e1de2016-03-30 10:43:55 +00005315}
5316
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005317static void setPrototype(Sema &S, FunctionDecl *FD, FunctionDecl *FDWithProto,
5318 QualType NewType) {
5319 assert(NewType->isFunctionProtoType() &&
5320 "Expected function type with prototype.");
5321 assert(FD->getType()->isFunctionNoProtoType() &&
5322 "Expected function with type with no prototype.");
5323 assert(FDWithProto->getType()->isFunctionProtoType() &&
5324 "Expected function with prototype.");
5325 // Synthesize parameters with the same types.
5326 FD->setType(NewType);
5327 SmallVector<ParmVarDecl *, 16> Params;
5328 for (const ParmVarDecl *P : FDWithProto->parameters()) {
5329 auto *Param = ParmVarDecl::Create(S.getASTContext(), FD, SourceLocation(),
5330 SourceLocation(), nullptr, P->getType(),
5331 /*TInfo=*/nullptr, SC_None, nullptr);
5332 Param->setScopeInfo(0, Params.size());
5333 Param->setImplicit();
5334 Params.push_back(Param);
5335 }
5336
5337 FD->setParams(Params);
5338}
5339
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005340Optional<std::pair<FunctionDecl *, Expr *>>
5341Sema::checkOpenMPDeclareVariantFunction(Sema::DeclGroupPtrTy DG,
5342 Expr *VariantRef, SourceRange SR) {
Alexey Bataevd158cf62019-09-13 20:18:17 +00005343 if (!DG || DG.get().isNull())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005344 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005345
5346 const int VariantId = 1;
5347 // Must be applied only to single decl.
5348 if (!DG.get().isSingleDecl()) {
5349 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd_variant)
5350 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005351 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005352 }
5353 Decl *ADecl = DG.get().getSingleDecl();
5354 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
5355 ADecl = FTD->getTemplatedDecl();
5356
5357 // Decl must be a function.
5358 auto *FD = dyn_cast<FunctionDecl>(ADecl);
5359 if (!FD) {
5360 Diag(ADecl->getLocation(), diag::err_omp_function_expected)
5361 << VariantId << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005362 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005363 }
5364
5365 auto &&HasMultiVersionAttributes = [](const FunctionDecl *FD) {
5366 return FD->hasAttrs() &&
5367 (FD->hasAttr<CPUDispatchAttr>() || FD->hasAttr<CPUSpecificAttr>() ||
5368 FD->hasAttr<TargetAttr>());
5369 };
5370 // OpenMP is not compatible with CPU-specific attributes.
5371 if (HasMultiVersionAttributes(FD)) {
5372 Diag(FD->getLocation(), diag::err_omp_declare_variant_incompat_attributes)
5373 << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005374 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005375 }
5376
5377 // Allow #pragma omp declare variant only if the function is not used.
Alexey Bataev12026142019-09-26 20:04:15 +00005378 if (FD->isUsed(false))
5379 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_used)
Alexey Bataevd158cf62019-09-13 20:18:17 +00005380 << FD->getLocation();
Alexey Bataev12026142019-09-26 20:04:15 +00005381
5382 // Check if the function was emitted already.
Alexey Bataev218bea92019-09-30 18:24:35 +00005383 const FunctionDecl *Definition;
5384 if (!FD->isThisDeclarationADefinition() && FD->isDefined(Definition) &&
5385 (LangOpts.EmitAllDecls || Context.DeclMustBeEmitted(Definition)))
Alexey Bataev12026142019-09-26 20:04:15 +00005386 Diag(SR.getBegin(), diag::warn_omp_declare_variant_after_emitted)
5387 << FD->getLocation();
Alexey Bataevd158cf62019-09-13 20:18:17 +00005388
5389 // The VariantRef must point to function.
5390 if (!VariantRef) {
5391 Diag(SR.getBegin(), diag::err_omp_function_expected) << VariantId;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005392 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005393 }
5394
5395 // Do not check templates, wait until instantiation.
5396 if (VariantRef->isTypeDependent() || VariantRef->isValueDependent() ||
5397 VariantRef->containsUnexpandedParameterPack() ||
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005398 VariantRef->isInstantiationDependent() || FD->isDependentContext())
5399 return std::make_pair(FD, VariantRef);
Alexey Bataevd158cf62019-09-13 20:18:17 +00005400
5401 // Convert VariantRef expression to the type of the original function to
5402 // resolve possible conflicts.
5403 ExprResult VariantRefCast;
5404 if (LangOpts.CPlusPlus) {
5405 QualType FnPtrType;
5406 auto *Method = dyn_cast<CXXMethodDecl>(FD);
5407 if (Method && !Method->isStatic()) {
5408 const Type *ClassType =
5409 Context.getTypeDeclType(Method->getParent()).getTypePtr();
5410 FnPtrType = Context.getMemberPointerType(FD->getType(), ClassType);
5411 ExprResult ER;
5412 {
5413 // Build adrr_of unary op to correctly handle type checks for member
5414 // functions.
5415 Sema::TentativeAnalysisScope Trap(*this);
5416 ER = CreateBuiltinUnaryOp(VariantRef->getBeginLoc(), UO_AddrOf,
5417 VariantRef);
5418 }
5419 if (!ER.isUsable()) {
5420 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5421 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005422 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005423 }
5424 VariantRef = ER.get();
5425 } else {
5426 FnPtrType = Context.getPointerType(FD->getType());
5427 }
5428 ImplicitConversionSequence ICS =
5429 TryImplicitConversion(VariantRef, FnPtrType.getUnqualifiedType(),
5430 /*SuppressUserConversions=*/false,
Richard Smithd28763c2020-01-29 12:07:14 -08005431 AllowedExplicit::None,
Alexey Bataevd158cf62019-09-13 20:18:17 +00005432 /*InOverloadResolution=*/false,
5433 /*CStyle=*/false,
5434 /*AllowObjCWritebackConversion=*/false);
5435 if (ICS.isFailure()) {
5436 Diag(VariantRef->getExprLoc(),
5437 diag::err_omp_declare_variant_incompat_types)
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005438 << VariantRef->getType()
5439 << ((Method && !Method->isStatic()) ? FnPtrType : FD->getType())
5440 << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005441 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005442 }
5443 VariantRefCast = PerformImplicitConversion(
5444 VariantRef, FnPtrType.getUnqualifiedType(), AA_Converting);
5445 if (!VariantRefCast.isUsable())
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005446 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005447 // Drop previously built artificial addr_of unary op for member functions.
5448 if (Method && !Method->isStatic()) {
5449 Expr *PossibleAddrOfVariantRef = VariantRefCast.get();
5450 if (auto *UO = dyn_cast<UnaryOperator>(
5451 PossibleAddrOfVariantRef->IgnoreImplicit()))
5452 VariantRefCast = UO->getSubExpr();
5453 }
5454 } else {
5455 VariantRefCast = VariantRef;
5456 }
5457
5458 ExprResult ER = CheckPlaceholderExpr(VariantRefCast.get());
5459 if (!ER.isUsable() ||
5460 !ER.get()->IgnoreParenImpCasts()->getType()->isFunctionType()) {
5461 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5462 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005463 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005464 }
5465
5466 // The VariantRef must point to function.
5467 auto *DRE = dyn_cast<DeclRefExpr>(ER.get()->IgnoreParenImpCasts());
5468 if (!DRE) {
5469 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5470 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005471 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005472 }
5473 auto *NewFD = dyn_cast_or_null<FunctionDecl>(DRE->getDecl());
5474 if (!NewFD) {
5475 Diag(VariantRef->getExprLoc(), diag::err_omp_function_expected)
5476 << VariantId << VariantRef->getSourceRange();
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005477 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005478 }
5479
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005480 // Check if function types are compatible in C.
5481 if (!LangOpts.CPlusPlus) {
5482 QualType NewType =
5483 Context.mergeFunctionTypes(FD->getType(), NewFD->getType());
5484 if (NewType.isNull()) {
5485 Diag(VariantRef->getExprLoc(),
5486 diag::err_omp_declare_variant_incompat_types)
5487 << NewFD->getType() << FD->getType() << VariantRef->getSourceRange();
5488 return None;
5489 }
5490 if (NewType->isFunctionProtoType()) {
5491 if (FD->getType()->isFunctionNoProtoType())
5492 setPrototype(*this, FD, NewFD, NewType);
5493 else if (NewFD->getType()->isFunctionNoProtoType())
5494 setPrototype(*this, NewFD, FD, NewType);
5495 }
5496 }
5497
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005498 // Check if variant function is not marked with declare variant directive.
5499 if (NewFD->hasAttrs() && NewFD->hasAttr<OMPDeclareVariantAttr>()) {
5500 Diag(VariantRef->getExprLoc(),
5501 diag::warn_omp_declare_variant_marked_as_declare_variant)
5502 << VariantRef->getSourceRange();
5503 SourceRange SR =
5504 NewFD->specific_attr_begin<OMPDeclareVariantAttr>()->getRange();
5505 Diag(SR.getBegin(), diag::note_omp_marked_declare_variant_here) << SR;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005506 return None;
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005507 }
5508
Alexey Bataevd158cf62019-09-13 20:18:17 +00005509 enum DoesntSupport {
5510 VirtFuncs = 1,
5511 Constructors = 3,
5512 Destructors = 4,
5513 DeletedFuncs = 5,
5514 DefaultedFuncs = 6,
5515 ConstexprFuncs = 7,
5516 ConstevalFuncs = 8,
5517 };
5518 if (const auto *CXXFD = dyn_cast<CXXMethodDecl>(FD)) {
5519 if (CXXFD->isVirtual()) {
5520 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5521 << VirtFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005522 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005523 }
5524
5525 if (isa<CXXConstructorDecl>(FD)) {
5526 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5527 << Constructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005528 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005529 }
5530
5531 if (isa<CXXDestructorDecl>(FD)) {
5532 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5533 << Destructors;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005534 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005535 }
5536 }
5537
5538 if (FD->isDeleted()) {
5539 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5540 << DeletedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005541 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005542 }
5543
5544 if (FD->isDefaulted()) {
5545 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5546 << DefaultedFuncs;
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005547 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005548 }
5549
5550 if (FD->isConstexpr()) {
5551 Diag(FD->getLocation(), diag::err_omp_declare_variant_doesnt_support)
5552 << (NewFD->isConsteval() ? ConstevalFuncs : ConstexprFuncs);
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005553 return None;
Alexey Bataevd158cf62019-09-13 20:18:17 +00005554 }
5555
5556 // Check general compatibility.
5557 if (areMultiversionVariantFunctionsCompatible(
Alexey Bataev0ee89c12019-12-12 14:13:02 -05005558 FD, NewFD, PartialDiagnostic::NullDiagnostic(),
5559 PartialDiagnosticAt(SourceLocation(),
5560 PartialDiagnostic::NullDiagnostic()),
Alexey Bataevd158cf62019-09-13 20:18:17 +00005561 PartialDiagnosticAt(
5562 VariantRef->getExprLoc(),
5563 PDiag(diag::err_omp_declare_variant_doesnt_support)),
5564 PartialDiagnosticAt(VariantRef->getExprLoc(),
5565 PDiag(diag::err_omp_declare_variant_diff)
5566 << FD->getLocation()),
Alexey Bataev6b06ead2019-10-08 14:56:20 +00005567 /*TemplatesSupported=*/true, /*ConstexprSupported=*/false,
5568 /*CLinkageMayDiffer=*/true))
Alexey Bataev0736f7f2019-09-18 16:24:31 +00005569 return None;
5570 return std::make_pair(FD, cast<Expr>(DRE));
5571}
Alexey Bataevd158cf62019-09-13 20:18:17 +00005572
Alexey Bataev9ff34742019-09-25 19:43:37 +00005573void Sema::ActOnOpenMPDeclareVariantDirective(
5574 FunctionDecl *FD, Expr *VariantRef, SourceRange SR,
Alexey Bataevfde11e92019-11-07 11:03:10 -05005575 ArrayRef<OMPCtxSelectorData> Data) {
5576 if (Data.empty())
Alexey Bataev9ff34742019-09-25 19:43:37 +00005577 return;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005578 SmallVector<Expr *, 4> CtxScores;
5579 SmallVector<unsigned, 4> CtxSets;
5580 SmallVector<unsigned, 4> Ctxs;
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005581 SmallVector<StringRef, 4> ImplVendors, DeviceKinds;
Alexey Bataevfde11e92019-11-07 11:03:10 -05005582 bool IsError = false;
5583 for (const OMPCtxSelectorData &D : Data) {
5584 OpenMPContextSelectorSetKind CtxSet = D.CtxSet;
5585 OpenMPContextSelectorKind Ctx = D.Ctx;
5586 if (CtxSet == OMP_CTX_SET_unknown || Ctx == OMP_CTX_unknown)
5587 return;
5588 Expr *Score = nullptr;
5589 if (D.Score.isUsable()) {
5590 Score = D.Score.get();
5591 if (!Score->isTypeDependent() && !Score->isValueDependent() &&
5592 !Score->isInstantiationDependent() &&
5593 !Score->containsUnexpandedParameterPack()) {
5594 Score =
5595 PerformOpenMPImplicitIntegerConversion(Score->getExprLoc(), Score)
5596 .get();
5597 if (Score)
5598 Score = VerifyIntegerConstantExpression(Score).get();
5599 }
5600 } else {
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005601 // OpenMP 5.0, 2.3.3 Matching and Scoring Context Selectors.
5602 // The kind, arch, and isa selectors are given the values 2^l, 2^(l+1) and
5603 // 2^(l+2), respectively, where l is the number of traits in the construct
5604 // set.
5605 // TODO: implement correct logic for isa and arch traits.
5606 // TODO: take the construct context set into account when it is
5607 // implemented.
5608 int L = 0; // Currently set the number of traits in construct set to 0,
5609 // since the construct trait set in not supported yet.
5610 if (CtxSet == OMP_CTX_SET_device && Ctx == OMP_CTX_kind)
5611 Score = ActOnIntegerConstant(SourceLocation(), std::pow(2, L)).get();
5612 else
5613 Score = ActOnIntegerConstant(SourceLocation(), 0).get();
Alexey Bataeva15a1412019-10-02 18:19:02 +00005614 }
Alexey Bataev5459a902019-11-22 11:42:08 -05005615 switch (Ctx) {
5616 case OMP_CTX_vendor:
5617 assert(CtxSet == OMP_CTX_SET_implementation &&
5618 "Expected implementation context selector set.");
5619 ImplVendors.append(D.Names.begin(), D.Names.end());
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005620 break;
Alexey Bataev5459a902019-11-22 11:42:08 -05005621 case OMP_CTX_kind:
5622 assert(CtxSet == OMP_CTX_SET_device &&
5623 "Expected device context selector set.");
5624 DeviceKinds.append(D.Names.begin(), D.Names.end());
Alexey Bataevfde11e92019-11-07 11:03:10 -05005625 break;
Alexey Bataev5459a902019-11-22 11:42:08 -05005626 case OMP_CTX_unknown:
5627 llvm_unreachable("Unknown context selector kind.");
Alexey Bataevfde11e92019-11-07 11:03:10 -05005628 }
5629 IsError = IsError || !Score;
5630 CtxSets.push_back(CtxSet);
5631 Ctxs.push_back(Ctx);
5632 CtxScores.push_back(Score);
Alexey Bataeva15a1412019-10-02 18:19:02 +00005633 }
Alexey Bataevfde11e92019-11-07 11:03:10 -05005634 if (!IsError) {
5635 auto *NewAttr = OMPDeclareVariantAttr::CreateImplicit(
5636 Context, VariantRef, CtxScores.begin(), CtxScores.size(),
5637 CtxSets.begin(), CtxSets.size(), Ctxs.begin(), Ctxs.size(),
Alexey Bataev4e8231b2019-11-05 15:13:30 -05005638 ImplVendors.begin(), ImplVendors.size(), DeviceKinds.begin(),
5639 DeviceKinds.size(), SR);
Alexey Bataevfde11e92019-11-07 11:03:10 -05005640 FD->addAttr(NewAttr);
5641 }
Alexey Bataevd158cf62019-09-13 20:18:17 +00005642}
5643
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005644void Sema::markOpenMPDeclareVariantFuncsReferenced(SourceLocation Loc,
5645 FunctionDecl *Func,
5646 bool MightBeOdrUse) {
5647 assert(LangOpts.OpenMP && "Expected OpenMP mode.");
5648
5649 if (!Func->isDependentContext() && Func->hasAttrs()) {
5650 for (OMPDeclareVariantAttr *A :
5651 Func->specific_attrs<OMPDeclareVariantAttr>()) {
5652 // TODO: add checks for active OpenMP context where possible.
5653 Expr *VariantRef = A->getVariantFuncRef();
Alexey Bataevf17a1d82019-12-02 14:15:38 -05005654 auto *DRE = cast<DeclRefExpr>(VariantRef->IgnoreParenImpCasts());
Alexey Bataevbf5d4292019-09-17 17:36:49 +00005655 auto *F = cast<FunctionDecl>(DRE->getDecl());
5656 if (!F->isDefined() && F->isTemplateInstantiation())
5657 InstantiateFunctionDefinition(Loc, F->getFirstDecl());
5658 MarkFunctionReferenced(Loc, F, MightBeOdrUse);
5659 }
5660 }
5661}
5662
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005663StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
5664 Stmt *AStmt,
5665 SourceLocation StartLoc,
5666 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005667 if (!AStmt)
5668 return StmtError();
5669
Alexey Bataeve3727102018-04-18 15:57:46 +00005670 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00005671 // 1.2.2 OpenMP Language Terminology
5672 // Structured block - An executable statement with a single entry at the
5673 // top and a single exit at the bottom.
5674 // The point of exit cannot be a branch out of the structured block.
5675 // longjmp() and throw() must not violate the entry/exit criteria.
5676 CS->getCapturedDecl()->setNothrow();
5677
Reid Kleckner87a31802018-03-12 21:43:02 +00005678 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005679
Alexey Bataev25e5b442015-09-15 12:52:43 +00005680 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5681 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00005682}
5683
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005684namespace {
Alexey Bataevf8be4762019-08-14 19:30:06 +00005685/// Iteration space of a single for loop.
5686struct LoopIterationSpace final {
5687 /// True if the condition operator is the strict compare operator (<, > or
5688 /// !=).
5689 bool IsStrictCompare = false;
5690 /// Condition of the loop.
5691 Expr *PreCond = nullptr;
5692 /// This expression calculates the number of iterations in the loop.
5693 /// It is always possible to calculate it before starting the loop.
5694 Expr *NumIterations = nullptr;
5695 /// The loop counter variable.
5696 Expr *CounterVar = nullptr;
5697 /// Private loop counter variable.
5698 Expr *PrivateCounterVar = nullptr;
5699 /// This is initializer for the initial value of #CounterVar.
5700 Expr *CounterInit = nullptr;
5701 /// This is step for the #CounterVar used to generate its update:
5702 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
5703 Expr *CounterStep = nullptr;
5704 /// Should step be subtracted?
5705 bool Subtract = false;
5706 /// Source range of the loop init.
5707 SourceRange InitSrcRange;
5708 /// Source range of the loop condition.
5709 SourceRange CondSrcRange;
5710 /// Source range of the loop increment.
5711 SourceRange IncSrcRange;
5712 /// Minimum value that can have the loop control variable. Used to support
5713 /// non-rectangular loops. Applied only for LCV with the non-iterator types,
5714 /// since only such variables can be used in non-loop invariant expressions.
5715 Expr *MinValue = nullptr;
5716 /// Maximum value that can have the loop control variable. Used to support
5717 /// non-rectangular loops. Applied only for LCV with the non-iterator type,
5718 /// since only such variables can be used in non-loop invariant expressions.
5719 Expr *MaxValue = nullptr;
5720 /// true, if the lower bound depends on the outer loop control var.
5721 bool IsNonRectangularLB = false;
5722 /// true, if the upper bound depends on the outer loop control var.
5723 bool IsNonRectangularUB = false;
5724 /// Index of the loop this loop depends on and forms non-rectangular loop
5725 /// nest.
5726 unsigned LoopDependentIdx = 0;
5727 /// Final condition for the non-rectangular loop nest support. It is used to
5728 /// check that the number of iterations for this particular counter must be
5729 /// finished.
5730 Expr *FinalCondition = nullptr;
5731};
5732
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005733/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005734/// extracting iteration space of each loop in the loop nest, that will be used
5735/// for IR generation.
5736class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005737 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005738 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005739 /// Data-sharing stack.
5740 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005741 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005742 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005743 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005744 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005745 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005746 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005747 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005748 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005749 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005750 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005751 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005752 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005753 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005754 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005755 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005756 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005757 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005758 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005759 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005760 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005761 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005762 /// Var < UB
5763 /// Var <= UB
5764 /// UB > Var
5765 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00005766 /// This will have no value when the condition is !=
5767 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005768 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005769 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005770 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005771 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005772 /// The outer loop counter this loop depends on (if any).
5773 const ValueDecl *DepDecl = nullptr;
5774 /// Contains number of loop (starts from 1) on which loop counter init
5775 /// expression of this loop depends on.
5776 Optional<unsigned> InitDependOnLC;
5777 /// Contains number of loop (starts from 1) on which loop counter condition
5778 /// expression of this loop depends on.
5779 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005780 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005781 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005782 /// Original condition required for checking of the exit condition for
5783 /// non-rectangular loop.
5784 Expr *Condition = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005785
5786public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00005787 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
5788 SourceLocation DefaultLoc)
5789 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
5790 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005791 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005792 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00005793 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005794 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005795 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00005796 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005797 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005798 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00005799 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005800 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005801 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005802 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00005803 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005804 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005805 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005806 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00005807 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005808 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005809 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005810 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00005811 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00005812 /// True, if the compare operator is strict (<, > or !=).
5813 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005814 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005815 Expr *buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00005816 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005817 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005818 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005819 Expr *
5820 buildPreCond(Scope *S, Expr *Cond,
5821 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005822 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005823 DeclRefExpr *
5824 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5825 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005826 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00005827 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005828 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005829 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005830 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005831 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005832 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005833 /// Build loop data with counter value for depend clauses in ordered
5834 /// directives.
5835 Expr *
5836 buildOrderedLoopData(Scope *S, Expr *Counter,
5837 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5838 SourceLocation Loc, Expr *Inc = nullptr,
5839 OverloadedOperatorKind OOK = OO_Amp);
Alexey Bataevf8be4762019-08-14 19:30:06 +00005840 /// Builds the minimum value for the loop counter.
5841 std::pair<Expr *, Expr *> buildMinMaxValues(
5842 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
5843 /// Builds final condition for the non-rectangular loops.
5844 Expr *buildFinalCondition(Scope *S) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005845 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00005846 bool dependent() const;
Alexey Bataevf8be4762019-08-14 19:30:06 +00005847 /// Returns true if the initializer forms non-rectangular loop.
5848 bool doesInitDependOnLC() const { return InitDependOnLC.hasValue(); }
5849 /// Returns true if the condition forms non-rectangular loop.
5850 bool doesCondDependOnLC() const { return CondDependOnLC.hasValue(); }
5851 /// Returns index of the loop we depend on (starting from 1), or 0 otherwise.
5852 unsigned getLoopDependentIdx() const {
5853 return InitDependOnLC.getValueOr(CondDependOnLC.getValueOr(0));
5854 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005855
5856private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005857 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005858 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00005859 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005860 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00005861 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
5862 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005863 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00005864 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
5865 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005866 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00005867 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005868};
5869
Alexey Bataeve3727102018-04-18 15:57:46 +00005870bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005871 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005872 assert(!LB && !UB && !Step);
5873 return false;
5874 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005875 return LCDecl->getType()->isDependentType() ||
5876 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
5877 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005878}
5879
Alexey Bataeve3727102018-04-18 15:57:46 +00005880bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005881 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00005882 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005883 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005884 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00005885 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005886 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005887 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005888 LCDecl = getCanonicalDecl(NewLCDecl);
5889 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005890 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
5891 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00005892 if ((Ctor->isCopyOrMoveConstructor() ||
5893 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
5894 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005895 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005896 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005897 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005898 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005899 return false;
5900}
5901
Alexey Bataev316ccf62019-01-29 18:51:58 +00005902bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
5903 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00005904 bool StrictOp, SourceRange SR,
5905 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005906 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005907 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
5908 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005909 if (!NewUB)
5910 return true;
5911 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00005912 if (LessOp)
5913 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005914 TestIsStrictOp = StrictOp;
5915 ConditionSrcRange = SR;
5916 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005917 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005918 return false;
5919}
5920
Alexey Bataeve3727102018-04-18 15:57:46 +00005921bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005922 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005923 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005924 if (!NewStep)
5925 return true;
5926 if (!NewStep->isValueDependent()) {
5927 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005928 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00005929 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
5930 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005931 if (Val.isInvalid())
5932 return true;
5933 NewStep = Val.get();
5934
5935 // OpenMP [2.6, Canonical Loop Form, Restrictions]
5936 // If test-expr is of form var relational-op b and relational-op is < or
5937 // <= then incr-expr must cause var to increase on each iteration of the
5938 // loop. If test-expr is of form var relational-op b and relational-op is
5939 // > or >= then incr-expr must cause var to decrease on each iteration of
5940 // the loop.
5941 // If test-expr is of form b relational-op var and relational-op is < or
5942 // <= then incr-expr must cause var to decrease on each iteration of the
5943 // loop. If test-expr is of form b relational-op var and relational-op is
5944 // > or >= then incr-expr must cause var to increase on each iteration of
5945 // the loop.
5946 llvm::APSInt Result;
5947 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
5948 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
5949 bool IsConstNeg =
5950 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005951 bool IsConstPos =
5952 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005953 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00005954
5955 // != with increment is treated as <; != with decrement is treated as >
5956 if (!TestIsLessOp.hasValue())
5957 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005958 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005959 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005960 (IsConstNeg || (IsUnsigned && Subtract)) :
5961 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005962 SemaRef.Diag(NewStep->getExprLoc(),
5963 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005964 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005965 SemaRef.Diag(ConditionLoc,
5966 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00005967 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005968 return true;
5969 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00005970 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00005971 NewStep =
5972 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
5973 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005974 Subtract = !Subtract;
5975 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005976 }
5977
5978 Step = NewStep;
5979 SubtractStep = Subtract;
5980 return false;
5981}
5982
Alexey Bataev622af1d2019-04-24 19:58:30 +00005983namespace {
5984/// Checker for the non-rectangular loops. Checks if the initializer or
5985/// condition expression references loop counter variable.
5986class LoopCounterRefChecker final
5987 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
5988 Sema &SemaRef;
5989 DSAStackTy &Stack;
5990 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00005991 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005992 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00005993 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00005994 unsigned BaseLoopId = 0;
5995 bool checkDecl(const Expr *E, const ValueDecl *VD) {
5996 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
5997 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
5998 << (IsInitializer ? 0 : 1);
5999 return false;
6000 }
6001 const auto &&Data = Stack.isLoopControlVariable(VD);
6002 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
6003 // The type of the loop iterator on which we depend may not have a random
6004 // access iterator type.
6005 if (Data.first && VD->getType()->isRecordType()) {
6006 SmallString<128> Name;
6007 llvm::raw_svector_ostream OS(Name);
6008 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
6009 /*Qualified=*/true);
6010 SemaRef.Diag(E->getExprLoc(),
6011 diag::err_omp_wrong_dependency_iterator_type)
6012 << OS.str();
6013 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
6014 return false;
6015 }
6016 if (Data.first &&
6017 (DepDecl || (PrevDepDecl &&
6018 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
6019 if (!DepDecl && PrevDepDecl)
6020 DepDecl = PrevDepDecl;
6021 SmallString<128> Name;
6022 llvm::raw_svector_ostream OS(Name);
6023 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
6024 /*Qualified=*/true);
6025 SemaRef.Diag(E->getExprLoc(),
6026 diag::err_omp_invariant_or_linear_dependency)
6027 << OS.str();
6028 return false;
6029 }
6030 if (Data.first) {
6031 DepDecl = VD;
6032 BaseLoopId = Data.first;
6033 }
6034 return Data.first;
6035 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00006036
6037public:
6038 bool VisitDeclRefExpr(const DeclRefExpr *E) {
6039 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006040 if (isa<VarDecl>(VD))
6041 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00006042 return false;
6043 }
6044 bool VisitMemberExpr(const MemberExpr *E) {
6045 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
6046 const ValueDecl *VD = E->getMemberDecl();
Mike Rice552c2c02019-07-17 15:18:45 +00006047 if (isa<VarDecl>(VD) || isa<FieldDecl>(VD))
6048 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00006049 }
6050 return false;
6051 }
6052 bool VisitStmt(const Stmt *S) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00006053 bool Res = false;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00006054 for (const Stmt *Child : S->children())
Alexey Bataevf8be4762019-08-14 19:30:06 +00006055 Res = (Child && Visit(Child)) || Res;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00006056 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00006057 }
6058 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006059 const ValueDecl *CurLCDecl, bool IsInitializer,
6060 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00006061 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006062 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
6063 unsigned getBaseLoopId() const {
6064 assert(CurLCDecl && "Expected loop dependency.");
6065 return BaseLoopId;
6066 }
6067 const ValueDecl *getDepDecl() const {
6068 assert(CurLCDecl && "Expected loop dependency.");
6069 return DepDecl;
6070 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00006071};
6072} // namespace
6073
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006074Optional<unsigned>
6075OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
6076 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00006077 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00006078 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
6079 DepDecl);
6080 if (LoopStmtChecker.Visit(S)) {
6081 DepDecl = LoopStmtChecker.getDepDecl();
6082 return LoopStmtChecker.getBaseLoopId();
6083 }
6084 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00006085}
6086
Alexey Bataeve3727102018-04-18 15:57:46 +00006087bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006088 // Check init-expr for canonical loop form and save loop counter
6089 // variable - #Var and its initialization value - #LB.
6090 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
6091 // var = lb
6092 // integer-type var = lb
6093 // random-access-iterator-type var = lb
6094 // pointer-type var = lb
6095 //
6096 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00006097 if (EmitDiags) {
6098 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
6099 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006100 return true;
6101 }
Tim Shen4a05bb82016-06-21 20:29:17 +00006102 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6103 if (!ExprTemp->cleanupsHaveSideEffects())
6104 S = ExprTemp->getSubExpr();
6105
Alexander Musmana5f070a2014-10-01 06:03:56 +00006106 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006107 if (Expr *E = dyn_cast<Expr>(S))
6108 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00006109 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006110 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006111 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006112 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
6113 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6114 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006115 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6116 EmitDiags);
6117 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006118 }
6119 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6120 if (ME->isArrow() &&
6121 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006122 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6123 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006124 }
6125 }
David Majnemer9d168222016-08-05 17:44:54 +00006126 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006127 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00006128 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00006129 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006130 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00006131 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006132 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006133 diag::ext_omp_loop_not_canonical_init)
6134 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00006135 return setLCDeclAndLB(
6136 Var,
6137 buildDeclRefExpr(SemaRef, Var,
6138 Var->getType().getNonReferenceType(),
6139 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00006140 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006141 }
6142 }
6143 }
David Majnemer9d168222016-08-05 17:44:54 +00006144 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006145 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006146 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00006147 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006148 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
6149 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006150 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6151 EmitDiags);
6152 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006153 }
6154 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
6155 if (ME->isArrow() &&
6156 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00006157 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
6158 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006159 }
6160 }
6161 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006162
Alexey Bataeve3727102018-04-18 15:57:46 +00006163 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006164 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00006165 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006166 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00006167 << S->getSourceRange();
6168 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006169 return true;
6170}
6171
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006172/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006173/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00006174static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006175 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00006176 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006177 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00006178 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006179 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00006180 if ((Ctor->isCopyOrMoveConstructor() ||
6181 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
6182 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006183 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00006184 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
6185 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006186 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006187 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006188 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006189 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
6190 return getCanonicalDecl(ME->getMemberDecl());
6191 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006192}
6193
Alexey Bataeve3727102018-04-18 15:57:46 +00006194bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006195 // Check test-expr for canonical form, save upper-bound UB, flags for
6196 // less/greater and for strict/non-strict comparison.
Alexey Bataev1be63402019-09-11 15:44:06 +00006197 // OpenMP [2.9] Canonical loop form. Test-expr may be one of the following:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006198 // var relational-op b
6199 // b relational-op var
6200 //
Alexey Bataev1be63402019-09-11 15:44:06 +00006201 bool IneqCondIsCanonical = SemaRef.getLangOpts().OpenMP >= 50;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006202 if (!S) {
Alexey Bataev1be63402019-09-11 15:44:06 +00006203 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond)
6204 << (IneqCondIsCanonical ? 1 : 0) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006205 return true;
6206 }
Alexey Bataevf8be4762019-08-14 19:30:06 +00006207 Condition = S;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006208 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006209 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00006210 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006211 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006212 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6213 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006214 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
6215 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6216 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006217 if (getInitLCDecl(BO->getRHS()) == LCDecl)
6218 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006219 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
6220 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
6221 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataev1be63402019-09-11 15:44:06 +00006222 } else if (IneqCondIsCanonical && BO->getOpcode() == BO_NE)
6223 return setUB(
6224 getInitLCDecl(BO->getLHS()) == LCDecl ? BO->getRHS() : BO->getLHS(),
6225 /*LessOp=*/llvm::None,
6226 /*StrictOp=*/true, BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00006227 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006228 if (CE->getNumArgs() == 2) {
6229 auto Op = CE->getOperator();
6230 switch (Op) {
6231 case OO_Greater:
6232 case OO_GreaterEqual:
6233 case OO_Less:
6234 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006235 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6236 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006237 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6238 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00006239 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
6240 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006241 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
6242 CE->getOperatorLoc());
6243 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006244 case OO_ExclaimEqual:
Alexey Bataev1be63402019-09-11 15:44:06 +00006245 if (IneqCondIsCanonical)
6246 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ? CE->getArg(1)
6247 : CE->getArg(0),
6248 /*LessOp=*/llvm::None,
6249 /*StrictOp=*/true, CE->getSourceRange(),
6250 CE->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00006251 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006252 default:
6253 break;
6254 }
6255 }
6256 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006257 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006258 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006259 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataev1be63402019-09-11 15:44:06 +00006260 << (IneqCondIsCanonical ? 1 : 0) << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006261 return true;
6262}
6263
Alexey Bataeve3727102018-04-18 15:57:46 +00006264bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006265 // RHS of canonical loop form increment can be:
6266 // var + incr
6267 // incr + var
6268 // var - incr
6269 //
6270 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00006271 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006272 if (BO->isAdditiveOp()) {
6273 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00006274 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6275 return setStep(BO->getRHS(), !IsAdd);
6276 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
6277 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006278 }
David Majnemer9d168222016-08-05 17:44:54 +00006279 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006280 bool IsAdd = CE->getOperator() == OO_Plus;
6281 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006282 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6283 return setStep(CE->getArg(1), !IsAdd);
6284 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
6285 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006286 }
6287 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006288 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006289 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006290 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006291 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006292 return true;
6293}
6294
Alexey Bataeve3727102018-04-18 15:57:46 +00006295bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006296 // Check incr-expr for canonical loop form and return true if it
6297 // does not conform.
6298 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
6299 // ++var
6300 // var++
6301 // --var
6302 // var--
6303 // var += incr
6304 // var -= incr
6305 // var = var + incr
6306 // var = incr + var
6307 // var = var - incr
6308 //
6309 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006310 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006311 return true;
6312 }
Tim Shen4a05bb82016-06-21 20:29:17 +00006313 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
6314 if (!ExprTemp->cleanupsHaveSideEffects())
6315 S = ExprTemp->getSubExpr();
6316
Alexander Musmana5f070a2014-10-01 06:03:56 +00006317 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006318 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00006319 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006320 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00006321 getInitLCDecl(UO->getSubExpr()) == LCDecl)
6322 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006323 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006324 (UO->isDecrementOp() ? -1 : 1))
6325 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006326 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00006327 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006328 switch (BO->getOpcode()) {
6329 case BO_AddAssign:
6330 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006331 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6332 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006333 break;
6334 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00006335 if (getInitLCDecl(BO->getLHS()) == LCDecl)
6336 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006337 break;
6338 default:
6339 break;
6340 }
David Majnemer9d168222016-08-05 17:44:54 +00006341 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006342 switch (CE->getOperator()) {
6343 case OO_PlusPlus:
6344 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00006345 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6346 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00006347 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006348 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00006349 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
6350 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00006351 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006352 break;
6353 case OO_PlusEqual:
6354 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00006355 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6356 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006357 break;
6358 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00006359 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
6360 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006361 break;
6362 default:
6363 break;
6364 }
6365 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006366 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006367 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006368 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006369 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006370 return true;
6371}
Alexander Musmana5f070a2014-10-01 06:03:56 +00006372
Alexey Bataev5a3af132016-03-29 08:58:54 +00006373static ExprResult
6374tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00006375 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00006376 if (SemaRef.CurContext->isDependentContext())
6377 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006378 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
6379 return SemaRef.PerformImplicitConversion(
6380 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
6381 /*AllowExplicit=*/true);
6382 auto I = Captures.find(Capture);
6383 if (I != Captures.end())
6384 return buildCapture(SemaRef, Capture, I->second);
6385 DeclRefExpr *Ref = nullptr;
6386 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
6387 Captures[Capture] = Ref;
6388 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006389}
6390
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006391/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00006392Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00006393 Scope *S, ArrayRef<LoopIterationSpace> ResultIterSpaces, bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00006394 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006395 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00006396 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006397 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00006398 SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00006399 Expr *LBVal = LB;
6400 Expr *UBVal = UB;
6401 // LB = TestIsLessOp.getValue() ? min(LB(MinVal), LB(MaxVal)) :
6402 // max(LB(MinVal), LB(MaxVal))
6403 if (InitDependOnLC) {
6404 const LoopIterationSpace &IS =
6405 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6406 InitDependOnLC.getValueOr(
6407 CondDependOnLC.getValueOr(0))];
6408 if (!IS.MinValue || !IS.MaxValue)
6409 return nullptr;
6410 // OuterVar = Min
6411 ExprResult MinValue =
6412 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6413 if (!MinValue.isUsable())
6414 return nullptr;
6415
6416 ExprResult LBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6417 IS.CounterVar, MinValue.get());
6418 if (!LBMinVal.isUsable())
6419 return nullptr;
6420 // OuterVar = Min, LBVal
6421 LBMinVal =
6422 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMinVal.get(), LBVal);
6423 if (!LBMinVal.isUsable())
6424 return nullptr;
6425 // (OuterVar = Min, LBVal)
6426 LBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMinVal.get());
6427 if (!LBMinVal.isUsable())
6428 return nullptr;
6429
6430 // OuterVar = Max
6431 ExprResult MaxValue =
6432 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6433 if (!MaxValue.isUsable())
6434 return nullptr;
6435
6436 ExprResult LBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6437 IS.CounterVar, MaxValue.get());
6438 if (!LBMaxVal.isUsable())
6439 return nullptr;
6440 // OuterVar = Max, LBVal
6441 LBMaxVal =
6442 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, LBMaxVal.get(), LBVal);
6443 if (!LBMaxVal.isUsable())
6444 return nullptr;
6445 // (OuterVar = Max, LBVal)
6446 LBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, LBMaxVal.get());
6447 if (!LBMaxVal.isUsable())
6448 return nullptr;
6449
6450 Expr *LBMin = tryBuildCapture(SemaRef, LBMinVal.get(), Captures).get();
6451 Expr *LBMax = tryBuildCapture(SemaRef, LBMaxVal.get(), Captures).get();
6452 if (!LBMin || !LBMax)
6453 return nullptr;
6454 // LB(MinVal) < LB(MaxVal)
6455 ExprResult MinLessMaxRes =
6456 SemaRef.BuildBinOp(S, DefaultLoc, BO_LT, LBMin, LBMax);
6457 if (!MinLessMaxRes.isUsable())
6458 return nullptr;
6459 Expr *MinLessMax =
6460 tryBuildCapture(SemaRef, MinLessMaxRes.get(), Captures).get();
6461 if (!MinLessMax)
6462 return nullptr;
6463 if (TestIsLessOp.getValue()) {
6464 // LB(MinVal) < LB(MaxVal) ? LB(MinVal) : LB(MaxVal) - min(LB(MinVal),
6465 // LB(MaxVal))
6466 ExprResult MinLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6467 MinLessMax, LBMin, LBMax);
6468 if (!MinLB.isUsable())
6469 return nullptr;
6470 LBVal = MinLB.get();
6471 } else {
6472 // LB(MinVal) < LB(MaxVal) ? LB(MaxVal) : LB(MinVal) - max(LB(MinVal),
6473 // LB(MaxVal))
6474 ExprResult MaxLB = SemaRef.ActOnConditionalOp(DefaultLoc, DefaultLoc,
6475 MinLessMax, LBMax, LBMin);
6476 if (!MaxLB.isUsable())
6477 return nullptr;
6478 LBVal = MaxLB.get();
6479 }
6480 }
6481 // UB = TestIsLessOp.getValue() ? max(UB(MinVal), UB(MaxVal)) :
6482 // min(UB(MinVal), UB(MaxVal))
6483 if (CondDependOnLC) {
6484 const LoopIterationSpace &IS =
6485 ResultIterSpaces[ResultIterSpaces.size() - 1 -
6486 InitDependOnLC.getValueOr(
6487 CondDependOnLC.getValueOr(0))];
6488 if (!IS.MinValue || !IS.MaxValue)
6489 return nullptr;
6490 // OuterVar = Min
6491 ExprResult MinValue =
6492 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MinValue);
6493 if (!MinValue.isUsable())
6494 return nullptr;
6495
6496 ExprResult UBMinVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6497 IS.CounterVar, MinValue.get());
6498 if (!UBMinVal.isUsable())
6499 return nullptr;
6500 // OuterVar = Min, UBVal
6501 UBMinVal =
6502 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMinVal.get(), UBVal);
6503 if (!UBMinVal.isUsable())
6504 return nullptr;
6505 // (OuterVar = Min, UBVal)
6506 UBMinVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMinVal.get());
6507 if (!UBMinVal.isUsable())
6508 return nullptr;
6509
6510 // OuterVar = Max
6511 ExprResult MaxValue =
6512 SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, IS.MaxValue);
6513 if (!MaxValue.isUsable())
6514 return nullptr;
6515
6516 ExprResult UBMaxVal = SemaRef.BuildBinOp(S, DefaultLoc, BO_Assign,
6517 IS.CounterVar, MaxValue.get());
6518 if (!UBMaxVal.isUsable())
6519 return nullptr;
6520 // OuterVar = Max, UBVal
6521 UBMaxVal =
6522 SemaRef.BuildBinOp(S, DefaultLoc, BO_Comma, UBMaxVal.get(), UBVal);
6523 if (!UBMaxVal.isUsable())
6524 return nullptr;
6525 // (OuterVar = Max, UBVal)
6526 UBMaxVal = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, UBMaxVal.get());
6527 if (!UBMaxVal.isUsable())
6528 return nullptr;
6529
6530 Expr *UBMin = tryBuildCapture(SemaRef, UBMinVal.get(), Captures).get();
6531 Expr *UBMax = tryBuildCapture(SemaRef, UBMaxVal.get(), Captures).get();
6532 if (!UBMin || !UBMax)
6533 return nullptr;
6534 // UB(MinVal) > UB(MaxVal)
6535 ExprResult MinGreaterMaxRes =
6536 SemaRef.BuildBinOp(S, DefaultLoc, BO_GT, UBMin, UBMax);
6537 if (!MinGreaterMaxRes.isUsable())
6538 return nullptr;
6539 Expr *MinGreaterMax =
6540 tryBuildCapture(SemaRef, MinGreaterMaxRes.get(), Captures).get();
6541 if (!MinGreaterMax)
6542 return nullptr;
6543 if (TestIsLessOp.getValue()) {
6544 // UB(MinVal) > UB(MaxVal) ? UB(MinVal) : UB(MaxVal) - max(UB(MinVal),
6545 // UB(MaxVal))
6546 ExprResult MaxUB = SemaRef.ActOnConditionalOp(
6547 DefaultLoc, DefaultLoc, MinGreaterMax, UBMin, UBMax);
6548 if (!MaxUB.isUsable())
6549 return nullptr;
6550 UBVal = MaxUB.get();
6551 } else {
6552 // UB(MinVal) > UB(MaxVal) ? UB(MaxVal) : UB(MinVal) - min(UB(MinVal),
6553 // UB(MaxVal))
6554 ExprResult MinUB = SemaRef.ActOnConditionalOp(
6555 DefaultLoc, DefaultLoc, MinGreaterMax, UBMax, UBMin);
6556 if (!MinUB.isUsable())
6557 return nullptr;
6558 UBVal = MinUB.get();
6559 }
6560 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006561 // Upper - Lower
Alexey Bataevf8be4762019-08-14 19:30:06 +00006562 Expr *UBExpr = TestIsLessOp.getValue() ? UBVal : LBVal;
6563 Expr *LBExpr = TestIsLessOp.getValue() ? LBVal : UBVal;
Alexey Bataev5a3af132016-03-29 08:58:54 +00006564 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
6565 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006566 if (!Upper || !Lower)
6567 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006568
6569 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6570
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006571 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006572 // BuildBinOp already emitted error, this one is to point user to upper
6573 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006574 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00006575 << Upper->getSourceRange() << Lower->getSourceRange();
6576 return nullptr;
6577 }
6578 }
6579
6580 if (!Diff.isUsable())
6581 return nullptr;
6582
6583 // Upper - Lower [- 1]
6584 if (TestIsStrictOp)
6585 Diff = SemaRef.BuildBinOp(
6586 S, DefaultLoc, BO_Sub, Diff.get(),
6587 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6588 if (!Diff.isUsable())
6589 return nullptr;
6590
6591 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006592 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006593 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006594 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006595 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006596 if (!Diff.isUsable())
6597 return nullptr;
6598
6599 // Parentheses (for dumping/debugging purposes only).
6600 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6601 if (!Diff.isUsable())
6602 return nullptr;
6603
6604 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006605 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00006606 if (!Diff.isUsable())
6607 return nullptr;
6608
Alexander Musman174b3ca2014-10-06 11:16:29 +00006609 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006610 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00006611 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006612 bool UseVarType = VarType->hasIntegerRepresentation() &&
6613 C.getTypeSize(Type) > C.getTypeSize(VarType);
6614 if (!Type->isIntegerType() || UseVarType) {
6615 unsigned NewSize =
6616 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
6617 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
6618 : Type->hasSignedIntegerRepresentation();
6619 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00006620 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
6621 Diff = SemaRef.PerformImplicitConversion(
6622 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
6623 if (!Diff.isUsable())
6624 return nullptr;
6625 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006626 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006627 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00006628 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
6629 if (NewSize != C.getTypeSize(Type)) {
6630 if (NewSize < C.getTypeSize(Type)) {
6631 assert(NewSize == 64 && "incorrect loop var size");
6632 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
6633 << InitSrcRange << ConditionSrcRange;
6634 }
6635 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006636 NewSize, Type->hasSignedIntegerRepresentation() ||
6637 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00006638 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
6639 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
6640 Sema::AA_Converting, true);
6641 if (!Diff.isUsable())
6642 return nullptr;
6643 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00006644 }
6645 }
6646
Alexander Musmana5f070a2014-10-01 06:03:56 +00006647 return Diff.get();
6648}
6649
Alexey Bataevf8be4762019-08-14 19:30:06 +00006650std::pair<Expr *, Expr *> OpenMPIterationSpaceChecker::buildMinMaxValues(
6651 Scope *S, llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
6652 // Do not build for iterators, they cannot be used in non-rectangular loop
6653 // nests.
6654 if (LCDecl->getType()->isRecordType())
6655 return std::make_pair(nullptr, nullptr);
6656 // If we subtract, the min is in the condition, otherwise the min is in the
6657 // init value.
6658 Expr *MinExpr = nullptr;
6659 Expr *MaxExpr = nullptr;
6660 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
6661 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
6662 bool LBNonRect = TestIsLessOp.getValue() ? InitDependOnLC.hasValue()
6663 : CondDependOnLC.hasValue();
6664 bool UBNonRect = TestIsLessOp.getValue() ? CondDependOnLC.hasValue()
6665 : InitDependOnLC.hasValue();
6666 Expr *Lower =
6667 LBNonRect ? LBExpr : tryBuildCapture(SemaRef, LBExpr, Captures).get();
6668 Expr *Upper =
6669 UBNonRect ? UBExpr : tryBuildCapture(SemaRef, UBExpr, Captures).get();
6670 if (!Upper || !Lower)
6671 return std::make_pair(nullptr, nullptr);
6672
6673 if (TestIsLessOp.getValue())
6674 MinExpr = Lower;
6675 else
6676 MaxExpr = Upper;
6677
6678 // Build minimum/maximum value based on number of iterations.
6679 ExprResult Diff;
6680 QualType VarType = LCDecl->getType().getNonReferenceType();
6681
6682 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6683 if (!Diff.isUsable())
6684 return std::make_pair(nullptr, nullptr);
6685
6686 // Upper - Lower [- 1]
6687 if (TestIsStrictOp)
6688 Diff = SemaRef.BuildBinOp(
6689 S, DefaultLoc, BO_Sub, Diff.get(),
6690 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
6691 if (!Diff.isUsable())
6692 return std::make_pair(nullptr, nullptr);
6693
6694 // Upper - Lower [- 1] + Step
6695 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6696 if (!NewStep.isUsable())
6697 return std::make_pair(nullptr, nullptr);
6698
6699 // Parentheses (for dumping/debugging purposes only).
6700 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6701 if (!Diff.isUsable())
6702 return std::make_pair(nullptr, nullptr);
6703
6704 // (Upper - Lower [- 1]) / Step
6705 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6706 if (!Diff.isUsable())
6707 return std::make_pair(nullptr, nullptr);
6708
6709 // ((Upper - Lower [- 1]) / Step) * Step
6710 // Parentheses (for dumping/debugging purposes only).
6711 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6712 if (!Diff.isUsable())
6713 return std::make_pair(nullptr, nullptr);
6714
6715 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Mul, Diff.get(), NewStep.get());
6716 if (!Diff.isUsable())
6717 return std::make_pair(nullptr, nullptr);
6718
6719 // Convert to the original type or ptrdiff_t, if original type is pointer.
6720 if (!VarType->isAnyPointerType() &&
6721 !SemaRef.Context.hasSameType(Diff.get()->getType(), VarType)) {
6722 Diff = SemaRef.PerformImplicitConversion(
6723 Diff.get(), VarType, Sema::AA_Converting, /*AllowExplicit=*/true);
6724 } else if (VarType->isAnyPointerType() &&
6725 !SemaRef.Context.hasSameType(
6726 Diff.get()->getType(),
6727 SemaRef.Context.getUnsignedPointerDiffType())) {
6728 Diff = SemaRef.PerformImplicitConversion(
6729 Diff.get(), SemaRef.Context.getUnsignedPointerDiffType(),
6730 Sema::AA_Converting, /*AllowExplicit=*/true);
6731 }
6732 if (!Diff.isUsable())
6733 return std::make_pair(nullptr, nullptr);
6734
6735 // Parentheses (for dumping/debugging purposes only).
6736 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6737 if (!Diff.isUsable())
6738 return std::make_pair(nullptr, nullptr);
6739
6740 if (TestIsLessOp.getValue()) {
6741 // MinExpr = Lower;
6742 // MaxExpr = Lower + (((Upper - Lower [- 1]) / Step) * Step)
6743 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Lower, Diff.get());
6744 if (!Diff.isUsable())
6745 return std::make_pair(nullptr, nullptr);
6746 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6747 if (!Diff.isUsable())
6748 return std::make_pair(nullptr, nullptr);
6749 MaxExpr = Diff.get();
6750 } else {
6751 // MaxExpr = Upper;
6752 // MinExpr = Upper - (((Upper - Lower [- 1]) / Step) * Step)
6753 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Diff.get());
6754 if (!Diff.isUsable())
6755 return std::make_pair(nullptr, nullptr);
6756 Diff = SemaRef.ActOnFinishFullExpr(Diff.get(), /*DiscardedValue*/ false);
6757 if (!Diff.isUsable())
6758 return std::make_pair(nullptr, nullptr);
6759 MinExpr = Diff.get();
6760 }
6761
6762 return std::make_pair(MinExpr, MaxExpr);
6763}
6764
6765Expr *OpenMPIterationSpaceChecker::buildFinalCondition(Scope *S) const {
6766 if (InitDependOnLC || CondDependOnLC)
6767 return Condition;
6768 return nullptr;
6769}
6770
Alexey Bataeve3727102018-04-18 15:57:46 +00006771Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006772 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00006773 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006774 // Do not build a precondition when the condition/initialization is dependent
6775 // to prevent pessimistic early loop exit.
6776 // TODO: this can be improved by calculating min/max values but not sure that
6777 // it will be very effective.
6778 if (CondDependOnLC || InitDependOnLC)
6779 return SemaRef.PerformImplicitConversion(
6780 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get(),
6781 SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6782 /*AllowExplicit=*/true).get();
6783
Alexey Bataev62dbb972015-04-22 11:59:37 +00006784 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006785 Sema::TentativeAnalysisScope Trap(SemaRef);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006786
Alexey Bataev658ad4d2019-10-01 16:19:10 +00006787 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
6788 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00006789 if (!NewLB.isUsable() || !NewUB.isUsable())
6790 return nullptr;
6791
Alexey Bataeve3727102018-04-18 15:57:46 +00006792 ExprResult CondExpr =
6793 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00006794 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00006795 (TestIsStrictOp ? BO_LT : BO_LE) :
6796 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00006797 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006798 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00006799 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
6800 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00006801 CondExpr = SemaRef.PerformImplicitConversion(
6802 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
6803 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00006804 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +00006805
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00006806 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00006807 return CondExpr.isUsable() ? CondExpr.get() : Cond;
6808}
6809
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006810/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006811DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00006812 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
6813 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006814 auto *VD = dyn_cast<VarDecl>(LCDecl);
6815 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006816 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
6817 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006818 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006819 const DSAStackTy::DSAVarData Data =
6820 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006821 // If the loop control decl is explicitly marked as private, do not mark it
6822 // as captured again.
6823 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
6824 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006825 return Ref;
6826 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00006827 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00006828}
6829
Alexey Bataeve3727102018-04-18 15:57:46 +00006830Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006831 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006832 QualType Type = LCDecl->getType().getNonReferenceType();
6833 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00006834 SemaRef, DefaultLoc, Type, LCDecl->getName(),
6835 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
6836 isa<VarDecl>(LCDecl)
6837 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
6838 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00006839 if (PrivateVar->isInvalidDecl())
6840 return nullptr;
6841 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
6842 }
6843 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006844}
6845
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006846/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006847Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006848
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006849/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006850Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006851
Alexey Bataevf138fda2018-08-13 19:04:24 +00006852Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
6853 Scope *S, Expr *Counter,
6854 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
6855 Expr *Inc, OverloadedOperatorKind OOK) {
6856 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
6857 if (!Cnt)
6858 return nullptr;
6859 if (Inc) {
6860 assert((OOK == OO_Plus || OOK == OO_Minus) &&
6861 "Expected only + or - operations for depend clauses.");
6862 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
6863 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
6864 if (!Cnt)
6865 return nullptr;
6866 }
6867 ExprResult Diff;
6868 QualType VarType = LCDecl->getType().getNonReferenceType();
6869 if (VarType->isIntegerType() || VarType->isPointerType() ||
6870 SemaRef.getLangOpts().CPlusPlus) {
6871 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00006872 Expr *Upper = TestIsLessOp.getValue()
6873 ? Cnt
6874 : tryBuildCapture(SemaRef, UB, Captures).get();
6875 Expr *Lower = TestIsLessOp.getValue()
6876 ? tryBuildCapture(SemaRef, LB, Captures).get()
6877 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006878 if (!Upper || !Lower)
6879 return nullptr;
6880
6881 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
6882
6883 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
6884 // BuildBinOp already emitted error, this one is to point user to upper
6885 // and lower bound, and to tell what is passed to 'operator-'.
6886 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
6887 << Upper->getSourceRange() << Lower->getSourceRange();
6888 return nullptr;
6889 }
6890 }
6891
6892 if (!Diff.isUsable())
6893 return nullptr;
6894
6895 // Parentheses (for dumping/debugging purposes only).
6896 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
6897 if (!Diff.isUsable())
6898 return nullptr;
6899
6900 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
6901 if (!NewStep.isUsable())
6902 return nullptr;
6903 // (Upper - Lower) / Step
6904 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
6905 if (!Diff.isUsable())
6906 return nullptr;
6907
6908 return Diff.get();
6909}
Alexey Bataev23b69422014-06-18 07:08:49 +00006910} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006911
Alexey Bataev9c821032015-04-30 04:23:23 +00006912void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
6913 assert(getLangOpts().OpenMP && "OpenMP is not active.");
6914 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006915 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
6916 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00006917 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00006918 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00006919 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00006920 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
6921 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006922 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev05be1da2019-07-18 17:49:13 +00006923 DeclRefExpr *PrivateRef = nullptr;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006924 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006925 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006926 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00006927 } else {
Alexey Bataev05be1da2019-07-18 17:49:13 +00006928 PrivateRef = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
6929 /*WithInit=*/false);
6930 VD = cast<VarDecl>(PrivateRef->getDecl());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006931 }
6932 }
6933 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00006934 const Decl *LD = DSAStack->getPossiblyLoopCunter();
6935 if (LD != D->getCanonicalDecl()) {
6936 DSAStack->resetPossibleLoopCounter();
6937 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
6938 MarkDeclarationsReferencedInExpr(
6939 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
6940 Var->getType().getNonLValueExprType(Context),
6941 ForLoc, /*RefersToCapture=*/true));
6942 }
Alexey Bataev05be1da2019-07-18 17:49:13 +00006943 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
6944 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables
6945 // Referenced in a Construct, C/C++]. The loop iteration variable in the
6946 // associated for-loop of a simd construct with just one associated
6947 // for-loop may be listed in a linear clause with a constant-linear-step
6948 // that is the increment of the associated for-loop. The loop iteration
6949 // variable(s) in the associated for-loop(s) of a for or parallel for
6950 // construct may be listed in a private or lastprivate clause.
6951 DSAStackTy::DSAVarData DVar =
6952 DSAStack->getTopDSA(D, /*FromParent=*/false);
6953 // If LoopVarRefExpr is nullptr it means the corresponding loop variable
6954 // is declared in the loop and it is predetermined as a private.
6955 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
6956 OpenMPClauseKind PredeterminedCKind =
6957 isOpenMPSimdDirective(DKind)
6958 ? (DSAStack->hasMutipleLoops() ? OMPC_lastprivate : OMPC_linear)
6959 : OMPC_private;
6960 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6961 DVar.CKind != PredeterminedCKind && DVar.RefExpr &&
6962 (LangOpts.OpenMP <= 45 || (DVar.CKind != OMPC_lastprivate &&
6963 DVar.CKind != OMPC_private))) ||
6964 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
Alexey Bataev60e51c42019-10-10 20:13:02 +00006965 DKind == OMPD_master_taskloop ||
Alexey Bataev5bbcead2019-10-14 17:17:41 +00006966 DKind == OMPD_parallel_master_taskloop ||
Alexey Bataev05be1da2019-07-18 17:49:13 +00006967 isOpenMPDistributeDirective(DKind)) &&
6968 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
6969 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
6970 (DVar.CKind != OMPC_private || DVar.RefExpr)) {
6971 Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
6972 << getOpenMPClauseName(DVar.CKind)
6973 << getOpenMPDirectiveName(DKind)
6974 << getOpenMPClauseName(PredeterminedCKind);
6975 if (DVar.RefExpr == nullptr)
6976 DVar.CKind = PredeterminedCKind;
6977 reportOriginalDsa(*this, DSAStack, D, DVar,
6978 /*IsLoopIterVar=*/true);
6979 } else if (LoopDeclRefExpr) {
6980 // Make the loop iteration variable private (for worksharing
6981 // constructs), linear (for simd directives with the only one
6982 // associated loop) or lastprivate (for simd directives with several
6983 // collapsed or ordered loops).
6984 if (DVar.CKind == OMPC_unknown)
6985 DSAStack->addDSA(D, LoopDeclRefExpr, PredeterminedCKind,
6986 PrivateRef);
6987 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00006988 }
6989 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006990 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00006991 }
6992}
6993
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006994/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006995/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00006996static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00006997 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
6998 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00006999 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
7000 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00007001 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007002 llvm::MutableArrayRef<LoopIterationSpace> ResultIterSpaces,
Alexey Bataeve3727102018-04-18 15:57:46 +00007003 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbef93a92019-10-07 18:54:57 +00007004 // OpenMP [2.9.1, Canonical Loop Form]
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007005 // for (init-expr; test-expr; incr-expr) structured-block
Alexey Bataevbef93a92019-10-07 18:54:57 +00007006 // for (range-decl: range-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00007007 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexey Bataevbef93a92019-10-07 18:54:57 +00007008 auto *CXXFor = dyn_cast_or_null<CXXForRangeStmt>(S);
7009 // Ranged for is supported only in OpenMP 5.0.
7010 if (!For && (SemaRef.LangOpts.OpenMP <= 45 || !CXXFor)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007011 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00007012 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00007013 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00007014 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00007015 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00007016 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
7017 SemaRef.Diag(DSA.getConstructLoc(),
7018 diag::note_omp_collapse_ordered_expr)
7019 << 2 << CollapseLoopCountExpr->getSourceRange()
7020 << OrderedLoopCountExpr->getSourceRange();
7021 else if (CollapseLoopCountExpr)
7022 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7023 diag::note_omp_collapse_ordered_expr)
7024 << 0 << CollapseLoopCountExpr->getSourceRange();
7025 else
7026 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7027 diag::note_omp_collapse_ordered_expr)
7028 << 1 << OrderedLoopCountExpr->getSourceRange();
7029 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007030 return true;
7031 }
Alexey Bataevbef93a92019-10-07 18:54:57 +00007032 assert(((For && For->getBody()) || (CXXFor && CXXFor->getBody())) &&
7033 "No loop body.");
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007034
Alexey Bataevbef93a92019-10-07 18:54:57 +00007035 OpenMPIterationSpaceChecker ISC(SemaRef, DSA,
7036 For ? For->getForLoc() : CXXFor->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007037
7038 // Check init.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007039 Stmt *Init = For ? For->getInit() : CXXFor->getBeginStmt();
Alexey Bataeve3727102018-04-18 15:57:46 +00007040 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007041 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007042
7043 bool HasErrors = false;
7044
7045 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00007046 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007047 // OpenMP [2.6, Canonical Loop Form]
7048 // Var is one of the following:
7049 // A variable of signed or unsigned integer type.
7050 // For C++, a variable of a random access iterator type.
7051 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00007052 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007053 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
7054 !VarType->isPointerType() &&
7055 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007056 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007057 << SemaRef.getLangOpts().CPlusPlus;
7058 HasErrors = true;
7059 }
7060
7061 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
7062 // a Construct
7063 // The loop iteration variable(s) in the associated for-loop(s) of a for or
7064 // parallel for construct is (are) private.
7065 // The loop iteration variable in the associated for-loop of a simd
7066 // construct with just one associated for-loop is linear with a
7067 // constant-linear-step that is the increment of the associated for-loop.
7068 // Exclude loop var from the list of variables with implicitly defined data
7069 // sharing attributes.
7070 VarsWithImplicitDSA.erase(LCDecl);
7071
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007072 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
7073
7074 // Check test-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007075 HasErrors |= ISC.checkAndSetCond(For ? For->getCond() : CXXFor->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00007076
7077 // Check incr-expr.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007078 HasErrors |= ISC.checkAndSetInc(For ? For->getInc() : CXXFor->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007079 }
7080
Alexey Bataeve3727102018-04-18 15:57:46 +00007081 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007082 return HasErrors;
7083
Alexander Musmana5f070a2014-10-01 06:03:56 +00007084 // Build the loop's iteration space representation.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007085 ResultIterSpaces[CurrentNestedLoopCount].PreCond = ISC.buildPreCond(
7086 DSA.getCurScope(), For ? For->getCond() : CXXFor->getCond(), Captures);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007087 ResultIterSpaces[CurrentNestedLoopCount].NumIterations =
7088 ISC.buildNumIterations(DSA.getCurScope(), ResultIterSpaces,
7089 (isOpenMPWorksharingDirective(DKind) ||
7090 isOpenMPTaskLoopDirective(DKind) ||
7091 isOpenMPDistributeDirective(DKind)),
7092 Captures);
7093 ResultIterSpaces[CurrentNestedLoopCount].CounterVar =
7094 ISC.buildCounterVar(Captures, DSA);
7095 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar =
7096 ISC.buildPrivateCounterVar();
7097 ResultIterSpaces[CurrentNestedLoopCount].CounterInit = ISC.buildCounterInit();
7098 ResultIterSpaces[CurrentNestedLoopCount].CounterStep = ISC.buildCounterStep();
7099 ResultIterSpaces[CurrentNestedLoopCount].InitSrcRange = ISC.getInitSrcRange();
7100 ResultIterSpaces[CurrentNestedLoopCount].CondSrcRange =
7101 ISC.getConditionSrcRange();
7102 ResultIterSpaces[CurrentNestedLoopCount].IncSrcRange =
7103 ISC.getIncrementSrcRange();
7104 ResultIterSpaces[CurrentNestedLoopCount].Subtract = ISC.shouldSubtractStep();
7105 ResultIterSpaces[CurrentNestedLoopCount].IsStrictCompare =
7106 ISC.isStrictTestOp();
7107 std::tie(ResultIterSpaces[CurrentNestedLoopCount].MinValue,
7108 ResultIterSpaces[CurrentNestedLoopCount].MaxValue) =
7109 ISC.buildMinMaxValues(DSA.getCurScope(), Captures);
7110 ResultIterSpaces[CurrentNestedLoopCount].FinalCondition =
7111 ISC.buildFinalCondition(DSA.getCurScope());
7112 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularLB =
7113 ISC.doesInitDependOnLC();
7114 ResultIterSpaces[CurrentNestedLoopCount].IsNonRectangularUB =
7115 ISC.doesCondDependOnLC();
7116 ResultIterSpaces[CurrentNestedLoopCount].LoopDependentIdx =
7117 ISC.getLoopDependentIdx();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007118
Alexey Bataevf8be4762019-08-14 19:30:06 +00007119 HasErrors |=
7120 (ResultIterSpaces[CurrentNestedLoopCount].PreCond == nullptr ||
7121 ResultIterSpaces[CurrentNestedLoopCount].NumIterations == nullptr ||
7122 ResultIterSpaces[CurrentNestedLoopCount].CounterVar == nullptr ||
7123 ResultIterSpaces[CurrentNestedLoopCount].PrivateCounterVar == nullptr ||
7124 ResultIterSpaces[CurrentNestedLoopCount].CounterInit == nullptr ||
7125 ResultIterSpaces[CurrentNestedLoopCount].CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007126 if (!HasErrors && DSA.isOrderedRegion()) {
7127 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
7128 if (CurrentNestedLoopCount <
7129 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
7130 DSA.getOrderedRegionParam().second->setLoopNumIterations(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007131 CurrentNestedLoopCount,
7132 ResultIterSpaces[CurrentNestedLoopCount].NumIterations);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007133 DSA.getOrderedRegionParam().second->setLoopCounter(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007134 CurrentNestedLoopCount,
7135 ResultIterSpaces[CurrentNestedLoopCount].CounterVar);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007136 }
7137 }
7138 for (auto &Pair : DSA.getDoacrossDependClauses()) {
7139 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
7140 // Erroneous case - clause has some problems.
7141 continue;
7142 }
7143 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
7144 Pair.second.size() <= CurrentNestedLoopCount) {
7145 // Erroneous case - clause has some problems.
7146 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
7147 continue;
7148 }
7149 Expr *CntValue;
7150 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
7151 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007152 DSA.getCurScope(),
7153 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00007154 Pair.first->getDependencyLoc());
7155 else
7156 CntValue = ISC.buildOrderedLoopData(
Alexey Bataevf8be4762019-08-14 19:30:06 +00007157 DSA.getCurScope(),
7158 ResultIterSpaces[CurrentNestedLoopCount].CounterVar, Captures,
Alexey Bataevf138fda2018-08-13 19:04:24 +00007159 Pair.first->getDependencyLoc(),
7160 Pair.second[CurrentNestedLoopCount].first,
7161 Pair.second[CurrentNestedLoopCount].second);
7162 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
7163 }
7164 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007165
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007166 return HasErrors;
7167}
7168
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007169/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00007170static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00007171buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007172 ExprResult Start, bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00007173 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007174 // Build 'VarRef = Start.
Alexey Bataevf8be4762019-08-14 19:30:06 +00007175 ExprResult NewStart = IsNonRectangularLB
7176 ? Start.get()
7177 : tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00007178 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007179 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00007180 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00007181 VarRef.get()->getType())) {
7182 NewStart = SemaRef.PerformImplicitConversion(
7183 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
7184 /*AllowExplicit=*/true);
7185 if (!NewStart.isUsable())
7186 return ExprError();
7187 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007188
Alexey Bataeve3727102018-04-18 15:57:46 +00007189 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007190 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7191 return Init;
7192}
7193
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007194/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00007195static ExprResult buildCounterUpdate(
7196 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
7197 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007198 bool IsNonRectangularLB,
Alexey Bataeve3727102018-04-18 15:57:46 +00007199 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007200 // Add parentheses (for debugging purposes only).
7201 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
7202 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
7203 !Step.isUsable())
7204 return ExprError();
7205
Alexey Bataev5a3af132016-03-29 08:58:54 +00007206 ExprResult NewStep = Step;
7207 if (Captures)
7208 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007209 if (NewStep.isInvalid())
7210 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007211 ExprResult Update =
7212 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007213 if (!Update.isUsable())
7214 return ExprError();
7215
Alexey Bataevc0214e02016-02-16 12:13:49 +00007216 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
7217 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataevf8be4762019-08-14 19:30:06 +00007218 if (!Start.isUsable())
7219 return ExprError();
7220 ExprResult NewStart = SemaRef.ActOnParenExpr(Loc, Loc, Start.get());
7221 if (!NewStart.isUsable())
7222 return ExprError();
7223 if (Captures && !IsNonRectangularLB)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007224 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007225 if (NewStart.isInvalid())
7226 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007227
Alexey Bataevc0214e02016-02-16 12:13:49 +00007228 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
7229 ExprResult SavedUpdate = Update;
7230 ExprResult UpdateVal;
7231 if (VarRef.get()->getType()->isOverloadableType() ||
7232 NewStart.get()->getType()->isOverloadableType() ||
7233 Update.get()->getType()->isOverloadableType()) {
Richard Smith2e3ed4a2019-08-16 19:53:22 +00007234 Sema::TentativeAnalysisScope Trap(SemaRef);
7235
Alexey Bataevc0214e02016-02-16 12:13:49 +00007236 Update =
7237 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
7238 if (Update.isUsable()) {
7239 UpdateVal =
7240 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
7241 VarRef.get(), SavedUpdate.get());
7242 if (UpdateVal.isUsable()) {
7243 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
7244 UpdateVal.get());
7245 }
7246 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007247 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007248
Alexey Bataevc0214e02016-02-16 12:13:49 +00007249 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
7250 if (!Update.isUsable() || !UpdateVal.isUsable()) {
7251 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
7252 NewStart.get(), SavedUpdate.get());
7253 if (!Update.isUsable())
7254 return ExprError();
7255
Alexey Bataev11481f52016-02-17 10:29:05 +00007256 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
7257 VarRef.get()->getType())) {
7258 Update = SemaRef.PerformImplicitConversion(
7259 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
7260 if (!Update.isUsable())
7261 return ExprError();
7262 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00007263
7264 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
7265 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007266 return Update;
7267}
7268
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007269/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007270/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007271static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007272 if (E == nullptr)
7273 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007274 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007275 QualType OldType = E->getType();
7276 unsigned HasBits = C.getTypeSize(OldType);
7277 if (HasBits >= Bits)
7278 return ExprResult(E);
7279 // OK to convert to signed, because new type has more bits than old.
7280 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
7281 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
7282 true);
7283}
7284
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007285/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00007286/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00007287static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007288 if (E == nullptr)
7289 return false;
7290 llvm::APSInt Result;
7291 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
7292 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
7293 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007294}
7295
Alexey Bataev5a3af132016-03-29 08:58:54 +00007296/// Build preinits statement for the given declarations.
7297static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00007298 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007299 if (!PreInits.empty()) {
7300 return new (Context) DeclStmt(
7301 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
7302 SourceLocation(), SourceLocation());
7303 }
7304 return nullptr;
7305}
7306
7307/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00007308static Stmt *
7309buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00007310 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007311 if (!Captures.empty()) {
7312 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00007313 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00007314 PreInits.push_back(Pair.second->getDecl());
7315 return buildPreInits(Context, PreInits);
7316 }
7317 return nullptr;
7318}
7319
7320/// Build postupdate expression for the given list of postupdates expressions.
7321static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
7322 Expr *PostUpdate = nullptr;
7323 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007324 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007325 Expr *ConvE = S.BuildCStyleCastExpr(
7326 E->getExprLoc(),
7327 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
7328 E->getExprLoc(), E)
7329 .get();
7330 PostUpdate = PostUpdate
7331 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
7332 PostUpdate, ConvE)
7333 .get()
7334 : ConvE;
7335 }
7336 }
7337 return PostUpdate;
7338}
7339
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007340/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00007341/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
7342/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00007343static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00007344checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00007345 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
7346 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00007347 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00007348 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007349 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007350 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007351 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007352 Expr::EvalResult Result;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007353 if (!CollapseLoopCountExpr->isValueDependent() &&
7354 CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007355 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007356 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007357 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007358 return 1;
7359 }
Alexey Bataev10e775f2015-07-30 11:36:16 +00007360 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007361 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007362 if (OrderedLoopCountExpr) {
7363 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00007364 Expr::EvalResult EVResult;
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007365 if (!OrderedLoopCountExpr->isValueDependent() &&
7366 OrderedLoopCountExpr->EvaluateAsInt(EVResult,
7367 SemaRef.getASTContext())) {
Fangrui Song407659a2018-11-30 23:41:18 +00007368 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007369 if (Result.getLimitedValue() < NestedLoopCount) {
7370 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
7371 diag::err_omp_wrong_ordered_loop_count)
7372 << OrderedLoopCountExpr->getSourceRange();
7373 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
7374 diag::note_collapse_loop_count)
7375 << CollapseLoopCountExpr->getSourceRange();
7376 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007377 OrderedLoopCount = Result.getLimitedValue();
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007378 } else {
Rui Ueyama49a3ad22019-07-16 04:46:31 +00007379 Built.clear(/*Size=*/1);
Dmitri Gribenko04323c22019-05-17 17:16:53 +00007380 return 1;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00007381 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00007382 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007383 // This is helper routine for loop directives (e.g., 'for', 'simd',
7384 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00007385 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00007386 SmallVector<LoopIterationSpace, 4> IterSpaces(
7387 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00007388 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007389 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00007390 if (checkOpenMPIterationSpace(
7391 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7392 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007393 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00007394 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007395 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007396 // OpenMP [2.8.1, simd construct, Restrictions]
7397 // All loops associated with the construct must be perfectly nested; that
7398 // is, there must be no intervening code nor any OpenMP directive between
7399 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007400 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7401 CurStmt = For->getBody();
7402 } else {
7403 assert(isa<CXXForRangeStmt>(CurStmt) &&
7404 "Expected canonical for or range-based for loops.");
7405 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7406 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007407 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7408 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007409 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00007410 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
7411 if (checkOpenMPIterationSpace(
7412 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
7413 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007414 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces, Captures))
Alexey Bataevf138fda2018-08-13 19:04:24 +00007415 return 0;
7416 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
7417 // Handle initialization of captured loop iterator variables.
7418 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
7419 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
7420 Captures[DRE] = DRE;
7421 }
7422 }
7423 // Move on to the next nested for loop, or to the loop body.
7424 // OpenMP [2.8.1, simd construct, Restrictions]
7425 // All loops associated with the construct must be perfectly nested; that
7426 // is, there must be no intervening code nor any OpenMP directive between
7427 // any two loops.
Alexey Bataevbef93a92019-10-07 18:54:57 +00007428 if (auto *For = dyn_cast<ForStmt>(CurStmt)) {
7429 CurStmt = For->getBody();
7430 } else {
7431 assert(isa<CXXForRangeStmt>(CurStmt) &&
7432 "Expected canonical for or range-based for loops.");
7433 CurStmt = cast<CXXForRangeStmt>(CurStmt)->getBody();
7434 }
Alexey Bataev8bbf2e32019-11-04 09:59:11 -05007435 CurStmt = OMPLoopDirective::tryToFindNextInnerLoop(
7436 CurStmt, SemaRef.LangOpts.OpenMP >= 50);
Alexey Bataevf138fda2018-08-13 19:04:24 +00007437 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00007438
Alexander Musmana5f070a2014-10-01 06:03:56 +00007439 Built.clear(/* size */ NestedLoopCount);
7440
7441 if (SemaRef.CurContext->isDependentContext())
7442 return NestedLoopCount;
7443
7444 // An example of what is generated for the following code:
7445 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00007446 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00007447 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00007448 // for (k = 0; k < NK; ++k)
7449 // for (j = J0; j < NJ; j+=2) {
7450 // <loop body>
7451 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007452 //
7453 // We generate the code below.
7454 // Note: the loop body may be outlined in CodeGen.
7455 // Note: some counters may be C++ classes, operator- is used to find number of
7456 // iterations and operator+= to calculate counter value.
7457 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
7458 // or i64 is currently supported).
7459 //
7460 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
7461 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
7462 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
7463 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
7464 // // similar updates for vars in clauses (e.g. 'linear')
7465 // <loop body (using local i and j)>
7466 // }
7467 // i = NI; // assign final values of counters
7468 // j = NJ;
7469 //
7470
7471 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
7472 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00007473 // Precondition tests if there is at least one iteration (all conditions are
7474 // true).
7475 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00007476 Expr *N0 = IterSpaces[0].NumIterations;
7477 ExprResult LastIteration32 =
7478 widenIterationCount(/*Bits=*/32,
7479 SemaRef
7480 .PerformImplicitConversion(
7481 N0->IgnoreImpCasts(), N0->getType(),
7482 Sema::AA_Converting, /*AllowExplicit=*/true)
7483 .get(),
7484 SemaRef);
7485 ExprResult LastIteration64 = widenIterationCount(
7486 /*Bits=*/64,
7487 SemaRef
7488 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
7489 Sema::AA_Converting,
7490 /*AllowExplicit=*/true)
7491 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007492 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007493
7494 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
7495 return NestedLoopCount;
7496
Alexey Bataeve3727102018-04-18 15:57:46 +00007497 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007498 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
7499
7500 Scope *CurScope = DSA.getCurScope();
7501 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00007502 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00007503 PreCond =
7504 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
7505 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00007506 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007507 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00007508 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007509 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
7510 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007511 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007512 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007513 SemaRef
7514 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7515 Sema::AA_Converting,
7516 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007517 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007518 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007519 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007520 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00007521 SemaRef
7522 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
7523 Sema::AA_Converting,
7524 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007525 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00007526 }
7527
7528 // Choose either the 32-bit or 64-bit version.
7529 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00007530 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
7531 (LastIteration32.isUsable() &&
7532 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
7533 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
7534 fitsInto(
7535 /*Bits=*/32,
7536 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
7537 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00007538 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00007539 QualType VType = LastIteration.get()->getType();
7540 QualType RealVType = VType;
7541 QualType StrideVType = VType;
7542 if (isOpenMPTaskLoopDirective(DKind)) {
7543 VType =
7544 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
7545 StrideVType =
7546 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
7547 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007548
7549 if (!LastIteration.isUsable())
7550 return 0;
7551
7552 // Save the number of iterations.
7553 ExprResult NumIterations = LastIteration;
7554 {
7555 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007556 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
7557 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007558 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7559 if (!LastIteration.isUsable())
7560 return 0;
7561 }
7562
7563 // Calculate the last iteration number beforehand instead of doing this on
7564 // each iteration. Do not do this if the number of iterations may be kfold-ed.
7565 llvm::APSInt Result;
7566 bool IsConstant =
7567 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
7568 ExprResult CalcLastIteration;
7569 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00007570 ExprResult SaveRef =
7571 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007572 LastIteration = SaveRef;
7573
7574 // Prepare SaveRef + 1.
7575 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00007576 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00007577 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
7578 if (!NumIterations.isUsable())
7579 return 0;
7580 }
7581
7582 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
7583
David Majnemer9d168222016-08-05 17:44:54 +00007584 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007585 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007586 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7587 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007588 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007589 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
7590 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007591 SemaRef.AddInitializerToDecl(LBDecl,
7592 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7593 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007594
7595 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00007596 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
7597 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00007598 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00007599 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007600
7601 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
7602 // This will be used to implement clause 'lastprivate'.
7603 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00007604 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
7605 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007606 SemaRef.AddInitializerToDecl(ILDecl,
7607 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7608 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007609
7610 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00007611 VarDecl *STDecl =
7612 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
7613 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00007614 SemaRef.AddInitializerToDecl(STDecl,
7615 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
7616 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007617
7618 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00007619 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00007620 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
7621 UB.get(), LastIteration.get());
7622 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00007623 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
7624 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00007625 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
7626 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007627 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007628
7629 // If we have a combined directive that combines 'distribute', 'for' or
7630 // 'simd' we need to be able to access the bounds of the schedule of the
7631 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
7632 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
7633 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00007634 // Lower bound variable, initialized with zero.
7635 VarDecl *CombLBDecl =
7636 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
7637 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
7638 SemaRef.AddInitializerToDecl(
7639 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
7640 /*DirectInit*/ false);
7641
7642 // Upper bound variable, initialized with last iteration number.
7643 VarDecl *CombUBDecl =
7644 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
7645 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
7646 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
7647 /*DirectInit*/ false);
7648
7649 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
7650 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
7651 ExprResult CombCondOp =
7652 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
7653 LastIteration.get(), CombUB.get());
7654 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
7655 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007656 CombEUB =
7657 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007658
Alexey Bataeve3727102018-04-18 15:57:46 +00007659 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007660 // We expect to have at least 2 more parameters than the 'parallel'
7661 // directive does - the lower and upper bounds of the previous schedule.
7662 assert(CD->getNumParams() >= 4 &&
7663 "Unexpected number of parameters in loop combined directive");
7664
7665 // Set the proper type for the bounds given what we learned from the
7666 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00007667 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
7668 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007669
7670 // Previous lower and upper bounds are obtained from the region
7671 // parameters.
7672 PrevLB =
7673 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
7674 PrevUB =
7675 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
7676 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007677 }
7678
7679 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00007680 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007681 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007682 {
Alexey Bataev7292c292016-04-25 12:22:29 +00007683 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
7684 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00007685 Expr *RHS =
7686 (isOpenMPWorksharingDirective(DKind) ||
7687 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
7688 ? LB.get()
7689 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00007690 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007691 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007692
7693 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7694 Expr *CombRHS =
7695 (isOpenMPWorksharingDirective(DKind) ||
7696 isOpenMPTaskLoopDirective(DKind) ||
7697 isOpenMPDistributeDirective(DKind))
7698 ? CombLB.get()
7699 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
7700 CombInit =
7701 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007702 CombInit =
7703 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007704 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007705 }
7706
Alexey Bataev316ccf62019-01-29 18:51:58 +00007707 bool UseStrictCompare =
7708 RealVType->hasUnsignedIntegerRepresentation() &&
7709 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
7710 return LIS.IsStrictCompare;
7711 });
7712 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
7713 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007714 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00007715 Expr *BoundUB = UB.get();
7716 if (UseStrictCompare) {
7717 BoundUB =
7718 SemaRef
7719 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
7720 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7721 .get();
7722 BoundUB =
7723 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
7724 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007725 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007726 (isOpenMPWorksharingDirective(DKind) ||
7727 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00007728 ? SemaRef.BuildBinOp(CurScope, CondLoc,
7729 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
7730 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00007731 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7732 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007733 ExprResult CombDistCond;
7734 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007735 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
7736 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007737 }
7738
Carlo Bertolliffafe102017-04-20 00:39:39 +00007739 ExprResult CombCond;
7740 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007741 Expr *BoundCombUB = CombUB.get();
7742 if (UseStrictCompare) {
7743 BoundCombUB =
7744 SemaRef
7745 .BuildBinOp(
7746 CurScope, CondLoc, BO_Add, BoundCombUB,
7747 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7748 .get();
7749 BoundCombUB =
7750 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
7751 .get();
7752 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00007753 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007754 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7755 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007756 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007757 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007758 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007759 ExprResult Inc =
7760 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
7761 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
7762 if (!Inc.isUsable())
7763 return 0;
7764 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007765 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007766 if (!Inc.isUsable())
7767 return 0;
7768
7769 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
7770 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00007771 // In combined construct, add combined version that use CombLB and CombUB
7772 // base variables for the update
7773 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007774 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
7775 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00007776 // LB + ST
7777 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
7778 if (!NextLB.isUsable())
7779 return 0;
7780 // LB = LB + ST
7781 NextLB =
7782 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007783 NextLB =
7784 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007785 if (!NextLB.isUsable())
7786 return 0;
7787 // UB + ST
7788 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
7789 if (!NextUB.isUsable())
7790 return 0;
7791 // UB = UB + ST
7792 NextUB =
7793 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007794 NextUB =
7795 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00007796 if (!NextUB.isUsable())
7797 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00007798 if (isOpenMPLoopBoundSharingDirective(DKind)) {
7799 CombNextLB =
7800 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
7801 if (!NextLB.isUsable())
7802 return 0;
7803 // LB = LB + ST
7804 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
7805 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007806 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
7807 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007808 if (!CombNextLB.isUsable())
7809 return 0;
7810 // UB + ST
7811 CombNextUB =
7812 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
7813 if (!CombNextUB.isUsable())
7814 return 0;
7815 // UB = UB + ST
7816 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
7817 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007818 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
7819 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00007820 if (!CombNextUB.isUsable())
7821 return 0;
7822 }
Alexander Musmanc6388682014-12-15 07:07:06 +00007823 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007824
Carlo Bertolliffafe102017-04-20 00:39:39 +00007825 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00007826 // directive with for as IV = IV + ST; ensure upper bound expression based
7827 // on PrevUB instead of NumIterations - used to implement 'for' when found
7828 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007829 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007830 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00007831 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00007832 DistCond = SemaRef.BuildBinOp(
7833 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007834 assert(DistCond.isUsable() && "distribute cond expr was not built");
7835
7836 DistInc =
7837 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
7838 assert(DistInc.isUsable() && "distribute inc expr was not built");
7839 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
7840 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007841 DistInc =
7842 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007843 assert(DistInc.isUsable() && "distribute inc expr was not built");
7844
7845 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
7846 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007847 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00007848 ExprResult IsUBGreater =
7849 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
7850 ExprResult CondOp = SemaRef.ActOnConditionalOp(
7851 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
7852 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
7853 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00007854 PrevEUB =
7855 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007856
Alexey Bataev316ccf62019-01-29 18:51:58 +00007857 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
7858 // parallel for is in combination with a distribute directive with
7859 // schedule(static, 1)
7860 Expr *BoundPrevUB = PrevUB.get();
7861 if (UseStrictCompare) {
7862 BoundPrevUB =
7863 SemaRef
7864 .BuildBinOp(
7865 CurScope, CondLoc, BO_Add, BoundPrevUB,
7866 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
7867 .get();
7868 BoundPrevUB =
7869 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
7870 .get();
7871 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00007872 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00007873 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
7874 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00007875 }
7876
Alexander Musmana5f070a2014-10-01 06:03:56 +00007877 // Build updates and final values of the loop counters.
7878 bool HasErrors = false;
7879 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007880 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007881 Built.Updates.resize(NestedLoopCount);
7882 Built.Finals.resize(NestedLoopCount);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007883 Built.DependentCounters.resize(NestedLoopCount);
7884 Built.DependentInits.resize(NestedLoopCount);
7885 Built.FinalsConditions.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007886 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007887 // We implement the following algorithm for obtaining the
7888 // original loop iteration variable values based on the
7889 // value of the collapsed loop iteration variable IV.
7890 //
7891 // Let n+1 be the number of collapsed loops in the nest.
7892 // Iteration variables (I0, I1, .... In)
7893 // Iteration counts (N0, N1, ... Nn)
7894 //
7895 // Acc = IV;
7896 //
7897 // To compute Ik for loop k, 0 <= k <= n, generate:
7898 // Prod = N(k+1) * N(k+2) * ... * Nn;
7899 // Ik = Acc / Prod;
7900 // Acc -= Ik * Prod;
7901 //
7902 ExprResult Acc = IV;
7903 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00007904 LoopIterationSpace &IS = IterSpaces[Cnt];
7905 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007906 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007907
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007908 // Compute prod
7909 ExprResult Prod =
7910 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
7911 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
7912 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
7913 IterSpaces[K].NumIterations);
7914
7915 // Iter = Acc / Prod
7916 // If there is at least one more inner loop to avoid
7917 // multiplication by 1.
7918 if (Cnt + 1 < NestedLoopCount)
7919 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
7920 Acc.get(), Prod.get());
7921 else
7922 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00007923 if (!Iter.isUsable()) {
7924 HasErrors = true;
7925 break;
7926 }
7927
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00007928 // Update Acc:
7929 // Acc -= Iter * Prod
7930 // Check if there is at least one more inner loop to avoid
7931 // multiplication by 1.
7932 if (Cnt + 1 < NestedLoopCount)
7933 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
7934 Iter.get(), Prod.get());
7935 else
7936 Prod = Iter;
7937 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
7938 Acc.get(), Prod.get());
7939
Alexey Bataev39f915b82015-05-08 10:41:21 +00007940 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007941 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00007942 DeclRefExpr *CounterVar = buildDeclRefExpr(
7943 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
7944 /*RefersToCapture=*/true);
Alexey Bataevf8be4762019-08-14 19:30:06 +00007945 ExprResult Init =
7946 buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
7947 IS.CounterInit, IS.IsNonRectangularLB, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007948 if (!Init.isUsable()) {
7949 HasErrors = true;
7950 break;
7951 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007952 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00007953 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
Alexey Bataevf8be4762019-08-14 19:30:06 +00007954 IS.CounterStep, IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007955 if (!Update.isUsable()) {
7956 HasErrors = true;
7957 break;
7958 }
7959
7960 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataevf8be4762019-08-14 19:30:06 +00007961 ExprResult Final =
7962 buildCounterUpdate(SemaRef, CurScope, UpdLoc, CounterVar,
7963 IS.CounterInit, IS.NumIterations, IS.CounterStep,
7964 IS.Subtract, IS.IsNonRectangularLB, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00007965 if (!Final.isUsable()) {
7966 HasErrors = true;
7967 break;
7968 }
7969
Alexander Musmana5f070a2014-10-01 06:03:56 +00007970 if (!Update.isUsable() || !Final.isUsable()) {
7971 HasErrors = true;
7972 break;
7973 }
7974 // Save results
7975 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00007976 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00007977 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00007978 Built.Updates[Cnt] = Update.get();
7979 Built.Finals[Cnt] = Final.get();
Alexey Bataevf8be4762019-08-14 19:30:06 +00007980 Built.DependentCounters[Cnt] = nullptr;
7981 Built.DependentInits[Cnt] = nullptr;
7982 Built.FinalsConditions[Cnt] = nullptr;
Alexey Bataev658ad4d2019-10-01 16:19:10 +00007983 if (IS.IsNonRectangularLB || IS.IsNonRectangularUB) {
Alexey Bataevf8be4762019-08-14 19:30:06 +00007984 Built.DependentCounters[Cnt] =
7985 Built.Counters[NestedLoopCount - 1 - IS.LoopDependentIdx];
7986 Built.DependentInits[Cnt] =
7987 Built.Inits[NestedLoopCount - 1 - IS.LoopDependentIdx];
7988 Built.FinalsConditions[Cnt] = IS.FinalCondition;
7989 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00007990 }
7991 }
7992
7993 if (HasErrors)
7994 return 0;
7995
7996 // Save results
7997 Built.IterationVarRef = IV.get();
7998 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00007999 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00008000 Built.CalcLastIteration = SemaRef
8001 .ActOnFinishFullExpr(CalcLastIteration.get(),
Alexey Bataevf8be4762019-08-14 19:30:06 +00008002 /*DiscardedValue=*/false)
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00008003 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008004 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008005 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00008006 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008007 Built.Init = Init.get();
8008 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00008009 Built.LB = LB.get();
8010 Built.UB = UB.get();
8011 Built.IL = IL.get();
8012 Built.ST = ST.get();
8013 Built.EUB = EUB.get();
8014 Built.NLB = NextLB.get();
8015 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00008016 Built.PrevLB = PrevLB.get();
8017 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00008018 Built.DistInc = DistInc.get();
8019 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00008020 Built.DistCombinedFields.LB = CombLB.get();
8021 Built.DistCombinedFields.UB = CombUB.get();
8022 Built.DistCombinedFields.EUB = CombEUB.get();
8023 Built.DistCombinedFields.Init = CombInit.get();
8024 Built.DistCombinedFields.Cond = CombCond.get();
8025 Built.DistCombinedFields.NLB = CombNextLB.get();
8026 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00008027 Built.DistCombinedFields.DistCond = CombDistCond.get();
8028 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008029
Alexey Bataevabfc0692014-06-25 06:52:00 +00008030 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008031}
8032
Alexey Bataev10e775f2015-07-30 11:36:16 +00008033static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00008034 auto CollapseClauses =
8035 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
8036 if (CollapseClauses.begin() != CollapseClauses.end())
8037 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00008038 return nullptr;
8039}
8040
Alexey Bataev10e775f2015-07-30 11:36:16 +00008041static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00008042 auto OrderedClauses =
8043 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
8044 if (OrderedClauses.begin() != OrderedClauses.end())
8045 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00008046 return nullptr;
8047}
8048
Kelvin Lic5609492016-07-15 04:39:07 +00008049static bool checkSimdlenSafelenSpecified(Sema &S,
8050 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008051 const OMPSafelenClause *Safelen = nullptr;
8052 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00008053
Alexey Bataeve3727102018-04-18 15:57:46 +00008054 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00008055 if (Clause->getClauseKind() == OMPC_safelen)
8056 Safelen = cast<OMPSafelenClause>(Clause);
8057 else if (Clause->getClauseKind() == OMPC_simdlen)
8058 Simdlen = cast<OMPSimdlenClause>(Clause);
8059 if (Safelen && Simdlen)
8060 break;
8061 }
8062
8063 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008064 const Expr *SimdlenLength = Simdlen->getSimdlen();
8065 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00008066 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
8067 SimdlenLength->isInstantiationDependent() ||
8068 SimdlenLength->containsUnexpandedParameterPack())
8069 return false;
8070 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
8071 SafelenLength->isInstantiationDependent() ||
8072 SafelenLength->containsUnexpandedParameterPack())
8073 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00008074 Expr::EvalResult SimdlenResult, SafelenResult;
8075 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
8076 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
8077 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
8078 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00008079 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
8080 // If both simdlen and safelen clauses are specified, the value of the
8081 // simdlen parameter must be less than or equal to the value of the safelen
8082 // parameter.
8083 if (SimdlenRes > SafelenRes) {
8084 S.Diag(SimdlenLength->getExprLoc(),
8085 diag::err_omp_wrong_simdlen_safelen_values)
8086 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
8087 return true;
8088 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00008089 }
8090 return false;
8091}
8092
Alexey Bataeve3727102018-04-18 15:57:46 +00008093StmtResult
8094Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8095 SourceLocation StartLoc, SourceLocation EndLoc,
8096 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008097 if (!AStmt)
8098 return StmtError();
8099
8100 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008101 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008102 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8103 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008104 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00008105 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8106 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00008107 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008108 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008109
Alexander Musmana5f070a2014-10-01 06:03:56 +00008110 assert((CurContext->isDependentContext() || B.builtAll()) &&
8111 "omp simd loop exprs were not built");
8112
Alexander Musman3276a272015-03-21 10:12:56 +00008113 if (!CurContext->isDependentContext()) {
8114 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008115 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008116 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00008117 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008118 B.NumIterations, *this, CurScope,
8119 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00008120 return StmtError();
8121 }
8122 }
8123
Kelvin Lic5609492016-07-15 04:39:07 +00008124 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008125 return StmtError();
8126
Reid Kleckner87a31802018-03-12 21:43:02 +00008127 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008128 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8129 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00008130}
8131
Alexey Bataeve3727102018-04-18 15:57:46 +00008132StmtResult
8133Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
8134 SourceLocation StartLoc, SourceLocation EndLoc,
8135 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008136 if (!AStmt)
8137 return StmtError();
8138
8139 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008140 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008141 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8142 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008143 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00008144 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
8145 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00008146 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00008147 return StmtError();
8148
Alexander Musmana5f070a2014-10-01 06:03:56 +00008149 assert((CurContext->isDependentContext() || B.builtAll()) &&
8150 "omp for loop exprs were not built");
8151
Alexey Bataev54acd402015-08-04 11:18:19 +00008152 if (!CurContext->isDependentContext()) {
8153 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008154 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008155 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008156 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008157 B.NumIterations, *this, CurScope,
8158 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008159 return StmtError();
8160 }
8161 }
8162
Reid Kleckner87a31802018-03-12 21:43:02 +00008163 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008164 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008165 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00008166}
8167
Alexander Musmanf82886e2014-09-18 05:12:34 +00008168StmtResult Sema::ActOnOpenMPForSimdDirective(
8169 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008170 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008171 if (!AStmt)
8172 return StmtError();
8173
8174 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00008175 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008176 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8177 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00008178 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008179 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008180 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8181 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00008182 if (NestedLoopCount == 0)
8183 return StmtError();
8184
Alexander Musmanc6388682014-12-15 07:07:06 +00008185 assert((CurContext->isDependentContext() || B.builtAll()) &&
8186 "omp for simd loop exprs were not built");
8187
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008188 if (!CurContext->isDependentContext()) {
8189 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008190 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008191 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008192 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008193 B.NumIterations, *this, CurScope,
8194 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00008195 return StmtError();
8196 }
8197 }
8198
Kelvin Lic5609492016-07-15 04:39:07 +00008199 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008200 return StmtError();
8201
Reid Kleckner87a31802018-03-12 21:43:02 +00008202 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008203 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
8204 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00008205}
8206
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008207StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
8208 Stmt *AStmt,
8209 SourceLocation StartLoc,
8210 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008211 if (!AStmt)
8212 return StmtError();
8213
8214 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008215 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008216 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008217 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008218 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008219 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008220 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008221 return StmtError();
8222 // All associated statements must be '#pragma omp section' except for
8223 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008224 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008225 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8226 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008227 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008228 diag::err_omp_sections_substmt_not_section);
8229 return StmtError();
8230 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008231 cast<OMPSectionDirective>(SectionStmt)
8232 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008233 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008234 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008235 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008236 return StmtError();
8237 }
8238
Reid Kleckner87a31802018-03-12 21:43:02 +00008239 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008240
Alexey Bataev25e5b442015-09-15 12:52:43 +00008241 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8242 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00008243}
8244
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008245StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
8246 SourceLocation StartLoc,
8247 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008248 if (!AStmt)
8249 return StmtError();
8250
8251 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008252
Reid Kleckner87a31802018-03-12 21:43:02 +00008253 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00008254 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008255
Alexey Bataev25e5b442015-09-15 12:52:43 +00008256 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
8257 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00008258}
8259
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008260StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
8261 Stmt *AStmt,
8262 SourceLocation StartLoc,
8263 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008264 if (!AStmt)
8265 return StmtError();
8266
8267 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00008268
Reid Kleckner87a31802018-03-12 21:43:02 +00008269 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00008270
Alexey Bataev3255bf32015-01-19 05:20:46 +00008271 // OpenMP [2.7.3, single Construct, Restrictions]
8272 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00008273 const OMPClause *Nowait = nullptr;
8274 const OMPClause *Copyprivate = nullptr;
8275 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00008276 if (Clause->getClauseKind() == OMPC_nowait)
8277 Nowait = Clause;
8278 else if (Clause->getClauseKind() == OMPC_copyprivate)
8279 Copyprivate = Clause;
8280 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008281 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00008282 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008283 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00008284 return StmtError();
8285 }
8286 }
8287
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00008288 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8289}
8290
Alexander Musman80c22892014-07-17 08:54:58 +00008291StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
8292 SourceLocation StartLoc,
8293 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008294 if (!AStmt)
8295 return StmtError();
8296
8297 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00008298
Reid Kleckner87a31802018-03-12 21:43:02 +00008299 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00008300
8301 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
8302}
8303
Alexey Bataev28c75412015-12-15 08:19:24 +00008304StmtResult Sema::ActOnOpenMPCriticalDirective(
8305 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
8306 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008307 if (!AStmt)
8308 return StmtError();
8309
8310 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008311
Alexey Bataev28c75412015-12-15 08:19:24 +00008312 bool ErrorFound = false;
8313 llvm::APSInt Hint;
8314 SourceLocation HintLoc;
8315 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008316 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008317 if (C->getClauseKind() == OMPC_hint) {
8318 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008319 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00008320 ErrorFound = true;
8321 }
8322 Expr *E = cast<OMPHintClause>(C)->getHint();
8323 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00008324 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00008325 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008326 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00008327 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008328 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00008329 }
8330 }
8331 }
8332 if (ErrorFound)
8333 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00008334 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00008335 if (Pair.first && DirName.getName() && !DependentHint) {
8336 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
8337 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00008338 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00008339 Diag(HintLoc, diag::note_omp_critical_hint_here)
8340 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008341 else
Alexey Bataev28c75412015-12-15 08:19:24 +00008342 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00008343 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008344 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00008345 << 1
8346 << C->getHint()->EvaluateKnownConstInt(Context).toString(
8347 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00008348 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008349 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00008350 }
Alexey Bataev28c75412015-12-15 08:19:24 +00008351 }
8352 }
8353
Reid Kleckner87a31802018-03-12 21:43:02 +00008354 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008355
Alexey Bataev28c75412015-12-15 08:19:24 +00008356 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
8357 Clauses, AStmt);
8358 if (!Pair.first && DirName.getName() && !DependentHint)
8359 DSAStack->addCriticalWithHint(Dir, Hint);
8360 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00008361}
8362
Alexey Bataev4acb8592014-07-07 13:01:15 +00008363StmtResult Sema::ActOnOpenMPParallelForDirective(
8364 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008365 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008366 if (!AStmt)
8367 return StmtError();
8368
Alexey Bataeve3727102018-04-18 15:57:46 +00008369 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008370 // 1.2.2 OpenMP Language Terminology
8371 // Structured block - An executable statement with a single entry at the
8372 // top and a single exit at the bottom.
8373 // The point of exit cannot be a branch out of the structured block.
8374 // longjmp() and throw() must not violate the entry/exit criteria.
8375 CS->getCapturedDecl()->setNothrow();
8376
Alexander Musmanc6388682014-12-15 07:07:06 +00008377 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008378 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8379 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00008380 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008381 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008382 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8383 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00008384 if (NestedLoopCount == 0)
8385 return StmtError();
8386
Alexander Musmana5f070a2014-10-01 06:03:56 +00008387 assert((CurContext->isDependentContext() || B.builtAll()) &&
8388 "omp parallel for loop exprs were not built");
8389
Alexey Bataev54acd402015-08-04 11:18:19 +00008390 if (!CurContext->isDependentContext()) {
8391 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008392 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008393 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00008394 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008395 B.NumIterations, *this, CurScope,
8396 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00008397 return StmtError();
8398 }
8399 }
8400
Reid Kleckner87a31802018-03-12 21:43:02 +00008401 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00008402 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00008403 NestedLoopCount, Clauses, AStmt, B,
8404 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00008405}
8406
Alexander Musmane4e893b2014-09-23 09:33:00 +00008407StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
8408 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008409 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008410 if (!AStmt)
8411 return StmtError();
8412
Alexey Bataeve3727102018-04-18 15:57:46 +00008413 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008414 // 1.2.2 OpenMP Language Terminology
8415 // Structured block - An executable statement with a single entry at the
8416 // top and a single exit at the bottom.
8417 // The point of exit cannot be a branch out of the structured block.
8418 // longjmp() and throw() must not violate the entry/exit criteria.
8419 CS->getCapturedDecl()->setNothrow();
8420
Alexander Musmanc6388682014-12-15 07:07:06 +00008421 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008422 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8423 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00008424 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008425 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00008426 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
8427 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008428 if (NestedLoopCount == 0)
8429 return StmtError();
8430
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008431 if (!CurContext->isDependentContext()) {
8432 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008433 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008434 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008435 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008436 B.NumIterations, *this, CurScope,
8437 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00008438 return StmtError();
8439 }
8440 }
8441
Kelvin Lic5609492016-07-15 04:39:07 +00008442 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00008443 return StmtError();
8444
Reid Kleckner87a31802018-03-12 21:43:02 +00008445 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00008446 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00008447 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00008448}
8449
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008450StmtResult
cchen47d60942019-12-05 13:43:48 -05008451Sema::ActOnOpenMPParallelMasterDirective(ArrayRef<OMPClause *> Clauses,
8452 Stmt *AStmt, SourceLocation StartLoc,
8453 SourceLocation EndLoc) {
8454 if (!AStmt)
8455 return StmtError();
8456
8457 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8458 auto *CS = cast<CapturedStmt>(AStmt);
8459 // 1.2.2 OpenMP Language Terminology
8460 // Structured block - An executable statement with a single entry at the
8461 // top and a single exit at the bottom.
8462 // The point of exit cannot be a branch out of the structured block.
8463 // longjmp() and throw() must not violate the entry/exit criteria.
8464 CS->getCapturedDecl()->setNothrow();
8465
8466 setFunctionHasBranchProtectedScope();
8467
8468 return OMPParallelMasterDirective::Create(Context, StartLoc, EndLoc, Clauses,
8469 AStmt);
8470}
8471
8472StmtResult
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008473Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
8474 Stmt *AStmt, SourceLocation StartLoc,
8475 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008476 if (!AStmt)
8477 return StmtError();
8478
8479 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008480 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00008481 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008482 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00008483 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008484 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00008485 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008486 return StmtError();
8487 // All associated statements must be '#pragma omp section' except for
8488 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00008489 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008490 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
8491 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008492 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008493 diag::err_omp_parallel_sections_substmt_not_section);
8494 return StmtError();
8495 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008496 cast<OMPSectionDirective>(SectionStmt)
8497 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008498 }
8499 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008500 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008501 diag::err_omp_parallel_sections_not_compound_stmt);
8502 return StmtError();
8503 }
8504
Reid Kleckner87a31802018-03-12 21:43:02 +00008505 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008506
Alexey Bataev25e5b442015-09-15 12:52:43 +00008507 return OMPParallelSectionsDirective::Create(
8508 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00008509}
8510
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008511StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
8512 Stmt *AStmt, SourceLocation StartLoc,
8513 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008514 if (!AStmt)
8515 return StmtError();
8516
David Majnemer9d168222016-08-05 17:44:54 +00008517 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008518 // 1.2.2 OpenMP Language Terminology
8519 // Structured block - An executable statement with a single entry at the
8520 // top and a single exit at the bottom.
8521 // The point of exit cannot be a branch out of the structured block.
8522 // longjmp() and throw() must not violate the entry/exit criteria.
8523 CS->getCapturedDecl()->setNothrow();
8524
Reid Kleckner87a31802018-03-12 21:43:02 +00008525 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008526
Alexey Bataev25e5b442015-09-15 12:52:43 +00008527 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
8528 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00008529}
8530
Alexey Bataev68446b72014-07-18 07:47:19 +00008531StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
8532 SourceLocation EndLoc) {
8533 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
8534}
8535
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00008536StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
8537 SourceLocation EndLoc) {
8538 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
8539}
8540
Alexey Bataev2df347a2014-07-18 10:17:07 +00008541StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
8542 SourceLocation EndLoc) {
8543 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
8544}
8545
Alexey Bataev169d96a2017-07-18 20:17:46 +00008546StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
8547 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008548 SourceLocation StartLoc,
8549 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008550 if (!AStmt)
8551 return StmtError();
8552
8553 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008554
Reid Kleckner87a31802018-03-12 21:43:02 +00008555 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008556
Alexey Bataev169d96a2017-07-18 20:17:46 +00008557 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00008558 AStmt,
8559 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00008560}
8561
Alexey Bataev6125da92014-07-21 11:26:11 +00008562StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
8563 SourceLocation StartLoc,
8564 SourceLocation EndLoc) {
8565 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
8566 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
8567}
8568
Alexey Bataev346265e2015-09-25 10:37:12 +00008569StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
8570 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008571 SourceLocation StartLoc,
8572 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008573 const OMPClause *DependFound = nullptr;
8574 const OMPClause *DependSourceClause = nullptr;
8575 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00008576 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008577 const OMPThreadsClause *TC = nullptr;
8578 const OMPSIMDClause *SC = nullptr;
8579 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00008580 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
8581 DependFound = C;
8582 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
8583 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008584 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00008585 << getOpenMPDirectiveName(OMPD_ordered)
8586 << getOpenMPClauseName(OMPC_depend) << 2;
8587 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008588 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00008589 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00008590 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008591 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008592 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008593 << 0;
8594 ErrorFound = true;
8595 }
8596 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
8597 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008598 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008599 << 1;
8600 ErrorFound = true;
8601 }
8602 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00008603 }
Alexey Bataeve3727102018-04-18 15:57:46 +00008604 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00008605 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008606 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008607 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00008608 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008609 }
Alexey Bataeveb482352015-12-18 05:05:56 +00008610 if (!ErrorFound && !SC &&
8611 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008612 // OpenMP [2.8.1,simd Construct, Restrictions]
8613 // An ordered construct with the simd clause is the only OpenMP construct
8614 // that can appear in the simd region.
Alexey Bataevf8c12ed2019-11-11 13:44:42 -05008615 Diag(StartLoc, diag::err_omp_prohibited_region_simd)
8616 << (LangOpts.OpenMP >= 50 ? 1 : 0);
Alexey Bataeveb482352015-12-18 05:05:56 +00008617 ErrorFound = true;
8618 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008619 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00008620 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
8621 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00008622 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008623 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00008624 diag::err_omp_ordered_directive_without_param);
8625 ErrorFound = true;
8626 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00008627 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008628 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00008629 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
8630 << (TC != nullptr);
Alexey Bataevcb8e6912020-01-31 16:09:26 -05008631 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param) << 1;
Alexey Bataeveb482352015-12-18 05:05:56 +00008632 ErrorFound = true;
8633 }
8634 }
8635 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008636 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00008637
8638 if (AStmt) {
8639 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8640
Reid Kleckner87a31802018-03-12 21:43:02 +00008641 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008642 }
Alexey Bataev346265e2015-09-25 10:37:12 +00008643
8644 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00008645}
8646
Alexey Bataev1d160b12015-03-13 12:27:31 +00008647namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008648/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008649/// construct.
8650class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008651 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008652 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008653 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008654 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008655 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008656 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008657 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008658 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008659 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008660 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008661 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008662 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008663 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008664 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008665 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00008666 /// expression.
8667 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008668 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00008669 /// part.
8670 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008671 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008672 NoError
8673 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008674 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008675 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008676 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00008677 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008678 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008679 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008680 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008681 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008682 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00008683 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8684 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8685 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008686 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00008687 /// important for non-associative operations.
8688 bool IsXLHSInRHSPart;
8689 BinaryOperatorKind Op;
8690 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008691 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008692 /// if it is a prefix unary operation.
8693 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008694
8695public:
8696 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00008697 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00008698 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008699 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00008700 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00008701 /// expression. If DiagId and NoteId == 0, then only check is performed
8702 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008703 /// \param DiagId Diagnostic which should be emitted if error is found.
8704 /// \param NoteId Diagnostic note for the main error message.
8705 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00008706 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008707 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008708 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008709 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00008710 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008711 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00008712 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
8713 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
8714 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008715 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00008716 /// false otherwise.
8717 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
8718
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00008719 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00008720 /// if it is a prefix unary operation.
8721 bool isPostfixUpdate() const { return IsPostfixUpdate; }
8722
Alexey Bataev1d160b12015-03-13 12:27:31 +00008723private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00008724 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
8725 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00008726};
8727} // namespace
8728
8729bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
8730 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
8731 ExprAnalysisErrorCode ErrorFound = NoError;
8732 SourceLocation ErrorLoc, NoteLoc;
8733 SourceRange ErrorRange, NoteRange;
8734 // Allowed constructs are:
8735 // x = x binop expr;
8736 // x = expr binop x;
8737 if (AtomicBinOp->getOpcode() == BO_Assign) {
8738 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00008739 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008740 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
8741 if (AtomicInnerBinOp->isMultiplicativeOp() ||
8742 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
8743 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008744 Op = AtomicInnerBinOp->getOpcode();
8745 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00008746 Expr *LHS = AtomicInnerBinOp->getLHS();
8747 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008748 llvm::FoldingSetNodeID XId, LHSId, RHSId;
8749 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
8750 /*Canonical=*/true);
8751 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
8752 /*Canonical=*/true);
8753 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
8754 /*Canonical=*/true);
8755 if (XId == LHSId) {
8756 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008757 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008758 } else if (XId == RHSId) {
8759 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008760 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008761 } else {
8762 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8763 ErrorRange = AtomicInnerBinOp->getSourceRange();
8764 NoteLoc = X->getExprLoc();
8765 NoteRange = X->getSourceRange();
8766 ErrorFound = NotAnUpdateExpression;
8767 }
8768 } else {
8769 ErrorLoc = AtomicInnerBinOp->getExprLoc();
8770 ErrorRange = AtomicInnerBinOp->getSourceRange();
8771 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
8772 NoteRange = SourceRange(NoteLoc, NoteLoc);
8773 ErrorFound = NotABinaryOperator;
8774 }
8775 } else {
8776 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
8777 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
8778 ErrorFound = NotABinaryExpression;
8779 }
8780 } else {
8781 ErrorLoc = AtomicBinOp->getExprLoc();
8782 ErrorRange = AtomicBinOp->getSourceRange();
8783 NoteLoc = AtomicBinOp->getOperatorLoc();
8784 NoteRange = SourceRange(NoteLoc, NoteLoc);
8785 ErrorFound = NotAnAssignmentOp;
8786 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008787 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008788 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8789 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8790 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008791 }
8792 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008793 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008794 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008795}
8796
8797bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
8798 unsigned NoteId) {
8799 ExprAnalysisErrorCode ErrorFound = NoError;
8800 SourceLocation ErrorLoc, NoteLoc;
8801 SourceRange ErrorRange, NoteRange;
8802 // Allowed constructs are:
8803 // x++;
8804 // x--;
8805 // ++x;
8806 // --x;
8807 // x binop= expr;
8808 // x = x binop expr;
8809 // x = expr binop x;
8810 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
8811 AtomicBody = AtomicBody->IgnoreParenImpCasts();
8812 if (AtomicBody->getType()->isScalarType() ||
8813 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008814 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008815 AtomicBody->IgnoreParenImpCasts())) {
8816 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00008817 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00008818 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00008819 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008820 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008821 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008822 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008823 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
8824 AtomicBody->IgnoreParenImpCasts())) {
8825 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00008826 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00008827 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008828 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00008829 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008830 // Check for Unary Operation
8831 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008832 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008833 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
8834 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00008835 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00008836 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
8837 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008838 } else {
8839 ErrorFound = NotAnUnaryIncDecExpression;
8840 ErrorLoc = AtomicUnaryOp->getExprLoc();
8841 ErrorRange = AtomicUnaryOp->getSourceRange();
8842 NoteLoc = AtomicUnaryOp->getOperatorLoc();
8843 NoteRange = SourceRange(NoteLoc, NoteLoc);
8844 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008845 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008846 ErrorFound = NotABinaryOrUnaryExpression;
8847 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
8848 NoteRange = ErrorRange = AtomicBody->getSourceRange();
8849 }
8850 } else {
8851 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008852 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008853 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8854 }
8855 } else {
8856 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008857 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00008858 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
8859 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00008860 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00008861 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
8862 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
8863 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00008864 }
8865 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00008866 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00008867 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00008868 // Build an update expression of form 'OpaqueValueExpr(x) binop
8869 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
8870 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
8871 auto *OVEX = new (SemaRef.getASTContext())
8872 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
8873 auto *OVEExpr = new (SemaRef.getASTContext())
8874 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00008875 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00008876 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
8877 IsXLHSInRHSPart ? OVEExpr : OVEX);
8878 if (Update.isInvalid())
8879 return true;
8880 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
8881 Sema::AA_Casting);
8882 if (Update.isInvalid())
8883 return true;
8884 UpdateExpr = Update.get();
8885 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00008886 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00008887}
8888
Alexey Bataev0162e452014-07-22 10:10:35 +00008889StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
8890 Stmt *AStmt,
8891 SourceLocation StartLoc,
8892 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008893 if (!AStmt)
8894 return StmtError();
8895
David Majnemer9d168222016-08-05 17:44:54 +00008896 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00008897 // 1.2.2 OpenMP Language Terminology
8898 // Structured block - An executable statement with a single entry at the
8899 // top and a single exit at the bottom.
8900 // The point of exit cannot be a branch out of the structured block.
8901 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00008902 OpenMPClauseKind AtomicKind = OMPC_unknown;
8903 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00008904 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00008905 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00008906 C->getClauseKind() == OMPC_update ||
8907 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00008908 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008909 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008910 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00008911 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
8912 << getOpenMPClauseName(AtomicKind);
8913 } else {
8914 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008915 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008916 }
8917 }
8918 }
Alexey Bataev62cec442014-11-18 10:14:22 +00008919
Alexey Bataeve3727102018-04-18 15:57:46 +00008920 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00008921 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
8922 Body = EWC->getSubExpr();
8923
Alexey Bataev62cec442014-11-18 10:14:22 +00008924 Expr *X = nullptr;
8925 Expr *V = nullptr;
8926 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00008927 Expr *UE = nullptr;
8928 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00008929 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00008930 // OpenMP [2.12.6, atomic Construct]
8931 // In the next expressions:
8932 // * x and v (as applicable) are both l-value expressions with scalar type.
8933 // * During the execution of an atomic region, multiple syntactic
8934 // occurrences of x must designate the same storage location.
8935 // * Neither of v and expr (as applicable) may access the storage location
8936 // designated by x.
8937 // * Neither of x and expr (as applicable) may access the storage location
8938 // designated by v.
8939 // * expr is an expression with scalar type.
8940 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
8941 // * binop, binop=, ++, and -- are not overloaded operators.
8942 // * The expression x binop expr must be numerically equivalent to x binop
8943 // (expr). This requirement is satisfied if the operators in expr have
8944 // precedence greater than binop, or by using parentheses around expr or
8945 // subexpressions of expr.
8946 // * The expression expr binop x must be numerically equivalent to (expr)
8947 // binop x. This requirement is satisfied if the operators in expr have
8948 // precedence equal to or greater than binop, or by using parentheses around
8949 // expr or subexpressions of expr.
8950 // * For forms that allow multiple occurrences of x, the number of times
8951 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00008952 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00008953 enum {
8954 NotAnExpression,
8955 NotAnAssignmentOp,
8956 NotAScalarType,
8957 NotAnLValue,
8958 NoError
8959 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00008960 SourceLocation ErrorLoc, NoteLoc;
8961 SourceRange ErrorRange, NoteRange;
8962 // If clause is read:
8963 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00008964 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
8965 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00008966 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
8967 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
8968 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
8969 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
8970 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
8971 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
8972 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008973 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00008974 ErrorFound = NotAnLValue;
8975 ErrorLoc = AtomicBinOp->getExprLoc();
8976 ErrorRange = AtomicBinOp->getSourceRange();
8977 NoteLoc = NotLValueExpr->getExprLoc();
8978 NoteRange = NotLValueExpr->getSourceRange();
8979 }
8980 } else if (!X->isInstantiationDependent() ||
8981 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008982 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00008983 (X->isInstantiationDependent() || X->getType()->isScalarType())
8984 ? V
8985 : X;
8986 ErrorFound = NotAScalarType;
8987 ErrorLoc = AtomicBinOp->getExprLoc();
8988 ErrorRange = AtomicBinOp->getSourceRange();
8989 NoteLoc = NotScalarExpr->getExprLoc();
8990 NoteRange = NotScalarExpr->getSourceRange();
8991 }
Alexey Bataev5a195472015-09-04 12:55:50 +00008992 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00008993 ErrorFound = NotAnAssignmentOp;
8994 ErrorLoc = AtomicBody->getExprLoc();
8995 ErrorRange = AtomicBody->getSourceRange();
8996 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
8997 : AtomicBody->getExprLoc();
8998 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
8999 : AtomicBody->getSourceRange();
9000 }
9001 } else {
9002 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009003 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00009004 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00009005 }
Alexey Bataev62cec442014-11-18 10:14:22 +00009006 if (ErrorFound != NoError) {
9007 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
9008 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00009009 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
9010 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00009011 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00009012 }
9013 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00009014 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00009015 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009016 enum {
9017 NotAnExpression,
9018 NotAnAssignmentOp,
9019 NotAScalarType,
9020 NotAnLValue,
9021 NoError
9022 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00009023 SourceLocation ErrorLoc, NoteLoc;
9024 SourceRange ErrorRange, NoteRange;
9025 // If clause is write:
9026 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00009027 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
9028 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00009029 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9030 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00009031 X = AtomicBinOp->getLHS();
9032 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00009033 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
9034 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
9035 if (!X->isLValue()) {
9036 ErrorFound = NotAnLValue;
9037 ErrorLoc = AtomicBinOp->getExprLoc();
9038 ErrorRange = AtomicBinOp->getSourceRange();
9039 NoteLoc = X->getExprLoc();
9040 NoteRange = X->getSourceRange();
9041 }
9042 } else if (!X->isInstantiationDependent() ||
9043 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009044 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00009045 (X->isInstantiationDependent() || X->getType()->isScalarType())
9046 ? E
9047 : X;
9048 ErrorFound = NotAScalarType;
9049 ErrorLoc = AtomicBinOp->getExprLoc();
9050 ErrorRange = AtomicBinOp->getSourceRange();
9051 NoteLoc = NotScalarExpr->getExprLoc();
9052 NoteRange = NotScalarExpr->getSourceRange();
9053 }
Alexey Bataev5a195472015-09-04 12:55:50 +00009054 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00009055 ErrorFound = NotAnAssignmentOp;
9056 ErrorLoc = AtomicBody->getExprLoc();
9057 ErrorRange = AtomicBody->getSourceRange();
9058 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9059 : AtomicBody->getExprLoc();
9060 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9061 : AtomicBody->getSourceRange();
9062 }
9063 } else {
9064 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009065 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00009066 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00009067 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00009068 if (ErrorFound != NoError) {
9069 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
9070 << ErrorRange;
9071 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
9072 << NoteRange;
9073 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00009074 }
9075 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00009076 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00009077 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00009078 // If clause is update:
9079 // x++;
9080 // x--;
9081 // ++x;
9082 // --x;
9083 // x binop= expr;
9084 // x = x binop expr;
9085 // x = expr binop x;
9086 OpenMPAtomicUpdateChecker Checker(*this);
9087 if (Checker.checkStatement(
9088 Body, (AtomicKind == OMPC_update)
9089 ? diag::err_omp_atomic_update_not_expression_statement
9090 : diag::err_omp_atomic_not_expression_statement,
9091 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00009092 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00009093 if (!CurContext->isDependentContext()) {
9094 E = Checker.getExpr();
9095 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00009096 UE = Checker.getUpdateExpr();
9097 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00009098 }
Alexey Bataev459dec02014-07-24 06:46:57 +00009099 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009100 enum {
9101 NotAnAssignmentOp,
9102 NotACompoundStatement,
9103 NotTwoSubstatements,
9104 NotASpecificExpression,
9105 NoError
9106 } ErrorFound = NoError;
9107 SourceLocation ErrorLoc, NoteLoc;
9108 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00009109 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009110 // If clause is a capture:
9111 // v = x++;
9112 // v = x--;
9113 // v = ++x;
9114 // v = --x;
9115 // v = x binop= expr;
9116 // v = x = x binop expr;
9117 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00009118 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00009119 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
9120 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
9121 V = AtomicBinOp->getLHS();
9122 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
9123 OpenMPAtomicUpdateChecker Checker(*this);
9124 if (Checker.checkStatement(
9125 Body, diag::err_omp_atomic_capture_not_expression_statement,
9126 diag::note_omp_atomic_update))
9127 return StmtError();
9128 E = Checker.getExpr();
9129 X = Checker.getX();
9130 UE = Checker.getUpdateExpr();
9131 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
9132 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00009133 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009134 ErrorLoc = AtomicBody->getExprLoc();
9135 ErrorRange = AtomicBody->getSourceRange();
9136 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
9137 : AtomicBody->getExprLoc();
9138 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
9139 : AtomicBody->getSourceRange();
9140 ErrorFound = NotAnAssignmentOp;
9141 }
9142 if (ErrorFound != NoError) {
9143 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
9144 << ErrorRange;
9145 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9146 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009147 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009148 if (CurContext->isDependentContext())
9149 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009150 } else {
9151 // If clause is a capture:
9152 // { v = x; x = expr; }
9153 // { v = x; x++; }
9154 // { v = x; x--; }
9155 // { v = x; ++x; }
9156 // { v = x; --x; }
9157 // { v = x; x binop= expr; }
9158 // { v = x; x = x binop expr; }
9159 // { v = x; x = expr binop x; }
9160 // { x++; v = x; }
9161 // { x--; v = x; }
9162 // { ++x; v = x; }
9163 // { --x; v = x; }
9164 // { x binop= expr; v = x; }
9165 // { x = x binop expr; v = x; }
9166 // { x = expr binop x; v = x; }
9167 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
9168 // Check that this is { expr1; expr2; }
9169 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009170 Stmt *First = CS->body_front();
9171 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009172 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
9173 First = EWC->getSubExpr()->IgnoreParenImpCasts();
9174 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
9175 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
9176 // Need to find what subexpression is 'v' and what is 'x'.
9177 OpenMPAtomicUpdateChecker Checker(*this);
9178 bool IsUpdateExprFound = !Checker.checkStatement(Second);
9179 BinaryOperator *BinOp = nullptr;
9180 if (IsUpdateExprFound) {
9181 BinOp = dyn_cast<BinaryOperator>(First);
9182 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9183 }
9184 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9185 // { v = x; x++; }
9186 // { v = x; x--; }
9187 // { v = x; ++x; }
9188 // { v = x; --x; }
9189 // { v = x; x binop= expr; }
9190 // { v = x; x = x binop expr; }
9191 // { v = x; x = expr binop x; }
9192 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00009193 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009194 llvm::FoldingSetNodeID XId, PossibleXId;
9195 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9196 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9197 IsUpdateExprFound = XId == PossibleXId;
9198 if (IsUpdateExprFound) {
9199 V = BinOp->getLHS();
9200 X = Checker.getX();
9201 E = Checker.getExpr();
9202 UE = Checker.getUpdateExpr();
9203 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00009204 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009205 }
9206 }
9207 if (!IsUpdateExprFound) {
9208 IsUpdateExprFound = !Checker.checkStatement(First);
9209 BinOp = nullptr;
9210 if (IsUpdateExprFound) {
9211 BinOp = dyn_cast<BinaryOperator>(Second);
9212 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
9213 }
9214 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
9215 // { x++; v = x; }
9216 // { x--; v = x; }
9217 // { ++x; v = x; }
9218 // { --x; v = x; }
9219 // { x binop= expr; v = x; }
9220 // { x = x binop expr; v = x; }
9221 // { x = expr binop x; v = x; }
9222 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00009223 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009224 llvm::FoldingSetNodeID XId, PossibleXId;
9225 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
9226 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
9227 IsUpdateExprFound = XId == PossibleXId;
9228 if (IsUpdateExprFound) {
9229 V = BinOp->getLHS();
9230 X = Checker.getX();
9231 E = Checker.getExpr();
9232 UE = Checker.getUpdateExpr();
9233 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00009234 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00009235 }
9236 }
9237 }
9238 if (!IsUpdateExprFound) {
9239 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00009240 auto *FirstExpr = dyn_cast<Expr>(First);
9241 auto *SecondExpr = dyn_cast<Expr>(Second);
9242 if (!FirstExpr || !SecondExpr ||
9243 !(FirstExpr->isInstantiationDependent() ||
9244 SecondExpr->isInstantiationDependent())) {
9245 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
9246 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00009247 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00009248 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009249 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009250 NoteRange = ErrorRange = FirstBinOp
9251 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00009252 : SourceRange(ErrorLoc, ErrorLoc);
9253 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00009254 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
9255 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
9256 ErrorFound = NotAnAssignmentOp;
9257 NoteLoc = ErrorLoc = SecondBinOp
9258 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009259 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00009260 NoteRange = ErrorRange =
9261 SecondBinOp ? SecondBinOp->getSourceRange()
9262 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00009263 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009264 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00009265 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00009266 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00009267 SecondBinOp->getLHS()->IgnoreParenImpCasts();
9268 llvm::FoldingSetNodeID X1Id, X2Id;
9269 PossibleXRHSInFirst->Profile(X1Id, Context,
9270 /*Canonical=*/true);
9271 PossibleXLHSInSecond->Profile(X2Id, Context,
9272 /*Canonical=*/true);
9273 IsUpdateExprFound = X1Id == X2Id;
9274 if (IsUpdateExprFound) {
9275 V = FirstBinOp->getLHS();
9276 X = SecondBinOp->getLHS();
9277 E = SecondBinOp->getRHS();
9278 UE = nullptr;
9279 IsXLHSInRHSPart = false;
9280 IsPostfixUpdate = true;
9281 } else {
9282 ErrorFound = NotASpecificExpression;
9283 ErrorLoc = FirstBinOp->getExprLoc();
9284 ErrorRange = FirstBinOp->getSourceRange();
9285 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
9286 NoteRange = SecondBinOp->getRHS()->getSourceRange();
9287 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00009288 }
9289 }
9290 }
9291 }
9292 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009293 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009294 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009295 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009296 ErrorFound = NotTwoSubstatements;
9297 }
9298 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009299 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009300 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009301 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00009302 ErrorFound = NotACompoundStatement;
9303 }
9304 if (ErrorFound != NoError) {
9305 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
9306 << ErrorRange;
9307 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
9308 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00009309 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009310 if (CurContext->isDependentContext())
9311 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00009312 }
Alexey Bataevdea47612014-07-23 07:46:59 +00009313 }
Alexey Bataev0162e452014-07-22 10:10:35 +00009314
Reid Kleckner87a31802018-03-12 21:43:02 +00009315 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00009316
Alexey Bataev62cec442014-11-18 10:14:22 +00009317 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00009318 X, V, E, UE, IsXLHSInRHSPart,
9319 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00009320}
9321
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009322StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
9323 Stmt *AStmt,
9324 SourceLocation StartLoc,
9325 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009326 if (!AStmt)
9327 return StmtError();
9328
Alexey Bataeve3727102018-04-18 15:57:46 +00009329 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00009330 // 1.2.2 OpenMP Language Terminology
9331 // Structured block - An executable statement with a single entry at the
9332 // top and a single exit at the bottom.
9333 // The point of exit cannot be a branch out of the structured block.
9334 // longjmp() and throw() must not violate the entry/exit criteria.
9335 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009336 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
9337 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9338 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9339 // 1.2.2 OpenMP Language Terminology
9340 // Structured block - An executable statement with a single entry at the
9341 // top and a single exit at the bottom.
9342 // The point of exit cannot be a branch out of the structured block.
9343 // longjmp() and throw() must not violate the entry/exit criteria.
9344 CS->getCapturedDecl()->setNothrow();
9345 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009346
Alexey Bataev13314bf2014-10-09 04:18:56 +00009347 // OpenMP [2.16, Nesting of Regions]
9348 // If specified, a teams construct must be contained within a target
9349 // construct. That target construct must contain no statements or directives
9350 // outside of the teams construct.
9351 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009352 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009353 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00009354 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00009355 auto I = CS->body_begin();
9356 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009357 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00009358 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
9359 OMPTeamsFound) {
9360
Alexey Bataev13314bf2014-10-09 04:18:56 +00009361 OMPTeamsFound = false;
9362 break;
9363 }
9364 ++I;
9365 }
9366 assert(I != CS->body_end() && "Not found statement");
9367 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00009368 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00009369 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00009370 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00009371 }
9372 if (!OMPTeamsFound) {
9373 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
9374 Diag(DSAStack->getInnerTeamsRegionLoc(),
9375 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009376 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00009377 << isa<OMPExecutableDirective>(S);
9378 return StmtError();
9379 }
9380 }
9381
Reid Kleckner87a31802018-03-12 21:43:02 +00009382 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00009383
9384 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9385}
9386
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009387StmtResult
9388Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
9389 Stmt *AStmt, SourceLocation StartLoc,
9390 SourceLocation EndLoc) {
9391 if (!AStmt)
9392 return StmtError();
9393
Alexey Bataeve3727102018-04-18 15:57:46 +00009394 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009395 // 1.2.2 OpenMP Language Terminology
9396 // Structured block - An executable statement with a single entry at the
9397 // top and a single exit at the bottom.
9398 // The point of exit cannot be a branch out of the structured block.
9399 // longjmp() and throw() must not violate the entry/exit criteria.
9400 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00009401 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
9402 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9403 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9404 // 1.2.2 OpenMP Language Terminology
9405 // Structured block - An executable statement with a single entry at the
9406 // top and a single exit at the bottom.
9407 // The point of exit cannot be a branch out of the structured block.
9408 // longjmp() and throw() must not violate the entry/exit criteria.
9409 CS->getCapturedDecl()->setNothrow();
9410 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009411
Reid Kleckner87a31802018-03-12 21:43:02 +00009412 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00009413
9414 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9415 AStmt);
9416}
9417
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009418StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
9419 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009420 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009421 if (!AStmt)
9422 return StmtError();
9423
Alexey Bataeve3727102018-04-18 15:57:46 +00009424 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009425 // 1.2.2 OpenMP Language Terminology
9426 // Structured block - An executable statement with a single entry at the
9427 // top and a single exit at the bottom.
9428 // The point of exit cannot be a branch out of the structured block.
9429 // longjmp() and throw() must not violate the entry/exit criteria.
9430 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009431 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
9432 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9433 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9434 // 1.2.2 OpenMP Language Terminology
9435 // Structured block - An executable statement with a single entry at the
9436 // top and a single exit at the bottom.
9437 // The point of exit cannot be a branch out of the structured block.
9438 // longjmp() and throw() must not violate the entry/exit criteria.
9439 CS->getCapturedDecl()->setNothrow();
9440 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009441
9442 OMPLoopDirective::HelperExprs B;
9443 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9444 // define the nested loops number.
9445 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009446 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009447 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009448 VarsWithImplicitDSA, B);
9449 if (NestedLoopCount == 0)
9450 return StmtError();
9451
9452 assert((CurContext->isDependentContext() || B.builtAll()) &&
9453 "omp target parallel for loop exprs were not built");
9454
9455 if (!CurContext->isDependentContext()) {
9456 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009457 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009458 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009459 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009460 B.NumIterations, *this, CurScope,
9461 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009462 return StmtError();
9463 }
9464 }
9465
Reid Kleckner87a31802018-03-12 21:43:02 +00009466 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00009467 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
9468 NestedLoopCount, Clauses, AStmt,
9469 B, DSAStack->isCancelRegion());
9470}
9471
Alexey Bataev95b64a92017-05-30 16:00:04 +00009472/// Check for existence of a map clause in the list of clauses.
9473static bool hasClauses(ArrayRef<OMPClause *> Clauses,
9474 const OpenMPClauseKind K) {
9475 return llvm::any_of(
9476 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
9477}
Samuel Antaodf67fc42016-01-19 19:15:56 +00009478
Alexey Bataev95b64a92017-05-30 16:00:04 +00009479template <typename... Params>
9480static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
9481 const Params... ClauseTypes) {
9482 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009483}
9484
Michael Wong65f367f2015-07-21 13:44:28 +00009485StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
9486 Stmt *AStmt,
9487 SourceLocation StartLoc,
9488 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009489 if (!AStmt)
9490 return StmtError();
9491
9492 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9493
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009494 // OpenMP [2.10.1, Restrictions, p. 97]
9495 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009496 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
9497 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9498 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00009499 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00009500 return StmtError();
9501 }
9502
Reid Kleckner87a31802018-03-12 21:43:02 +00009503 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00009504
9505 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9506 AStmt);
9507}
9508
Samuel Antaodf67fc42016-01-19 19:15:56 +00009509StmtResult
9510Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
9511 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009512 SourceLocation EndLoc, Stmt *AStmt) {
9513 if (!AStmt)
9514 return StmtError();
9515
Alexey Bataeve3727102018-04-18 15:57:46 +00009516 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009517 // 1.2.2 OpenMP Language Terminology
9518 // Structured block - An executable statement with a single entry at the
9519 // top and a single exit at the bottom.
9520 // The point of exit cannot be a branch out of the structured block.
9521 // longjmp() and throw() must not violate the entry/exit criteria.
9522 CS->getCapturedDecl()->setNothrow();
9523 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
9524 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9525 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9526 // 1.2.2 OpenMP Language Terminology
9527 // Structured block - An executable statement with a single entry at the
9528 // top and a single exit at the bottom.
9529 // The point of exit cannot be a branch out of the structured block.
9530 // longjmp() and throw() must not violate the entry/exit criteria.
9531 CS->getCapturedDecl()->setNothrow();
9532 }
9533
Samuel Antaodf67fc42016-01-19 19:15:56 +00009534 // OpenMP [2.10.2, Restrictions, p. 99]
9535 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009536 if (!hasClauses(Clauses, OMPC_map)) {
9537 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9538 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009539 return StmtError();
9540 }
9541
Alexey Bataev7828b252017-11-21 17:08:48 +00009542 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9543 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00009544}
9545
Samuel Antao72590762016-01-19 20:04:50 +00009546StmtResult
9547Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
9548 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009549 SourceLocation EndLoc, Stmt *AStmt) {
9550 if (!AStmt)
9551 return StmtError();
9552
Alexey Bataeve3727102018-04-18 15:57:46 +00009553 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009554 // 1.2.2 OpenMP Language Terminology
9555 // Structured block - An executable statement with a single entry at the
9556 // top and a single exit at the bottom.
9557 // The point of exit cannot be a branch out of the structured block.
9558 // longjmp() and throw() must not violate the entry/exit criteria.
9559 CS->getCapturedDecl()->setNothrow();
9560 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
9561 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9562 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9563 // 1.2.2 OpenMP Language Terminology
9564 // Structured block - An executable statement with a single entry at the
9565 // top and a single exit at the bottom.
9566 // The point of exit cannot be a branch out of the structured block.
9567 // longjmp() and throw() must not violate the entry/exit criteria.
9568 CS->getCapturedDecl()->setNothrow();
9569 }
9570
Samuel Antao72590762016-01-19 20:04:50 +00009571 // OpenMP [2.10.3, Restrictions, p. 102]
9572 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00009573 if (!hasClauses(Clauses, OMPC_map)) {
9574 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
9575 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00009576 return StmtError();
9577 }
9578
Alexey Bataev7828b252017-11-21 17:08:48 +00009579 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
9580 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00009581}
9582
Samuel Antao686c70c2016-05-26 17:30:50 +00009583StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
9584 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00009585 SourceLocation EndLoc,
9586 Stmt *AStmt) {
9587 if (!AStmt)
9588 return StmtError();
9589
Alexey Bataeve3727102018-04-18 15:57:46 +00009590 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00009591 // 1.2.2 OpenMP Language Terminology
9592 // Structured block - An executable statement with a single entry at the
9593 // top and a single exit at the bottom.
9594 // The point of exit cannot be a branch out of the structured block.
9595 // longjmp() and throw() must not violate the entry/exit criteria.
9596 CS->getCapturedDecl()->setNothrow();
9597 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
9598 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9599 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9600 // 1.2.2 OpenMP Language Terminology
9601 // Structured block - An executable statement with a single entry at the
9602 // top and a single exit at the bottom.
9603 // The point of exit cannot be a branch out of the structured block.
9604 // longjmp() and throw() must not violate the entry/exit criteria.
9605 CS->getCapturedDecl()->setNothrow();
9606 }
9607
Alexey Bataev95b64a92017-05-30 16:00:04 +00009608 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00009609 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
9610 return StmtError();
9611 }
Alexey Bataev7828b252017-11-21 17:08:48 +00009612 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
9613 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00009614}
9615
Alexey Bataev13314bf2014-10-09 04:18:56 +00009616StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
9617 Stmt *AStmt, SourceLocation StartLoc,
9618 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009619 if (!AStmt)
9620 return StmtError();
9621
Alexey Bataeve3727102018-04-18 15:57:46 +00009622 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00009623 // 1.2.2 OpenMP Language Terminology
9624 // Structured block - An executable statement with a single entry at the
9625 // top and a single exit at the bottom.
9626 // The point of exit cannot be a branch out of the structured block.
9627 // longjmp() and throw() must not violate the entry/exit criteria.
9628 CS->getCapturedDecl()->setNothrow();
9629
Reid Kleckner87a31802018-03-12 21:43:02 +00009630 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00009631
Alexey Bataevceabd412017-11-30 18:01:54 +00009632 DSAStack->setParentTeamsRegionLoc(StartLoc);
9633
Alexey Bataev13314bf2014-10-09 04:18:56 +00009634 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
9635}
9636
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009637StmtResult
9638Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
9639 SourceLocation EndLoc,
9640 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009641 if (DSAStack->isParentNowaitRegion()) {
9642 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
9643 return StmtError();
9644 }
9645 if (DSAStack->isParentOrderedRegion()) {
9646 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
9647 return StmtError();
9648 }
9649 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
9650 CancelRegion);
9651}
9652
Alexey Bataev87933c72015-09-18 08:07:34 +00009653StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
9654 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00009655 SourceLocation EndLoc,
9656 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00009657 if (DSAStack->isParentNowaitRegion()) {
9658 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
9659 return StmtError();
9660 }
9661 if (DSAStack->isParentOrderedRegion()) {
9662 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
9663 return StmtError();
9664 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00009665 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00009666 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
9667 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00009668}
9669
Alexey Bataev382967a2015-12-08 12:06:20 +00009670static bool checkGrainsizeNumTasksClauses(Sema &S,
9671 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009672 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00009673 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00009674 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00009675 if (C->getClauseKind() == OMPC_grainsize ||
9676 C->getClauseKind() == OMPC_num_tasks) {
9677 if (!PrevClause)
9678 PrevClause = C;
9679 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009680 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009681 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
9682 << getOpenMPClauseName(C->getClauseKind())
9683 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009684 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00009685 diag::note_omp_previous_grainsize_num_tasks)
9686 << getOpenMPClauseName(PrevClause->getClauseKind());
9687 ErrorFound = true;
9688 }
9689 }
9690 }
9691 return ErrorFound;
9692}
9693
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009694static bool checkReductionClauseWithNogroup(Sema &S,
9695 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009696 const OMPClause *ReductionClause = nullptr;
9697 const OMPClause *NogroupClause = nullptr;
9698 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009699 if (C->getClauseKind() == OMPC_reduction) {
9700 ReductionClause = C;
9701 if (NogroupClause)
9702 break;
9703 continue;
9704 }
9705 if (C->getClauseKind() == OMPC_nogroup) {
9706 NogroupClause = C;
9707 if (ReductionClause)
9708 break;
9709 continue;
9710 }
9711 }
9712 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009713 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
9714 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00009715 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009716 return true;
9717 }
9718 return false;
9719}
9720
Alexey Bataev49f6e782015-12-01 04:18:41 +00009721StmtResult Sema::ActOnOpenMPTaskLoopDirective(
9722 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009723 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00009724 if (!AStmt)
9725 return StmtError();
9726
9727 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9728 OMPLoopDirective::HelperExprs B;
9729 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9730 // define the nested loops number.
9731 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009732 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009733 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00009734 VarsWithImplicitDSA, B);
9735 if (NestedLoopCount == 0)
9736 return StmtError();
9737
9738 assert((CurContext->isDependentContext() || B.builtAll()) &&
9739 "omp for loop exprs were not built");
9740
Alexey Bataev382967a2015-12-08 12:06:20 +00009741 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9742 // The grainsize clause and num_tasks clause are mutually exclusive and may
9743 // not appear on the same taskloop directive.
9744 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9745 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009746 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9747 // If a reduction clause is present on the taskloop directive, the nogroup
9748 // clause must not be specified.
9749 if (checkReductionClauseWithNogroup(*this, Clauses))
9750 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009751
Reid Kleckner87a31802018-03-12 21:43:02 +00009752 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00009753 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9754 NestedLoopCount, Clauses, AStmt, B);
9755}
9756
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009757StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
9758 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00009759 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009760 if (!AStmt)
9761 return StmtError();
9762
9763 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9764 OMPLoopDirective::HelperExprs B;
9765 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9766 // define the nested loops number.
9767 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00009768 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009769 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9770 VarsWithImplicitDSA, B);
9771 if (NestedLoopCount == 0)
9772 return StmtError();
9773
9774 assert((CurContext->isDependentContext() || B.builtAll()) &&
9775 "omp for loop exprs were not built");
9776
Alexey Bataev5a3af132016-03-29 08:58:54 +00009777 if (!CurContext->isDependentContext()) {
9778 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00009779 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00009780 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009781 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00009782 B.NumIterations, *this, CurScope,
9783 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00009784 return StmtError();
9785 }
9786 }
9787
Alexey Bataev382967a2015-12-08 12:06:20 +00009788 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9789 // The grainsize clause and num_tasks clause are mutually exclusive and may
9790 // not appear on the same taskloop directive.
9791 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9792 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00009793 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9794 // If a reduction clause is present on the taskloop directive, the nogroup
9795 // clause must not be specified.
9796 if (checkReductionClauseWithNogroup(*this, Clauses))
9797 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00009798 if (checkSimdlenSafelenSpecified(*this, Clauses))
9799 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00009800
Reid Kleckner87a31802018-03-12 21:43:02 +00009801 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00009802 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
9803 NestedLoopCount, Clauses, AStmt, B);
9804}
9805
Alexey Bataev60e51c42019-10-10 20:13:02 +00009806StmtResult Sema::ActOnOpenMPMasterTaskLoopDirective(
9807 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9808 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9809 if (!AStmt)
9810 return StmtError();
9811
9812 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9813 OMPLoopDirective::HelperExprs B;
9814 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9815 // define the nested loops number.
9816 unsigned NestedLoopCount =
9817 checkOpenMPLoop(OMPD_master_taskloop, getCollapseNumberExpr(Clauses),
9818 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9819 VarsWithImplicitDSA, B);
9820 if (NestedLoopCount == 0)
9821 return StmtError();
9822
9823 assert((CurContext->isDependentContext() || B.builtAll()) &&
9824 "omp for loop exprs were not built");
9825
9826 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9827 // The grainsize clause and num_tasks clause are mutually exclusive and may
9828 // not appear on the same taskloop directive.
9829 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9830 return StmtError();
9831 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9832 // If a reduction clause is present on the taskloop directive, the nogroup
9833 // clause must not be specified.
9834 if (checkReductionClauseWithNogroup(*this, Clauses))
9835 return StmtError();
9836
9837 setFunctionHasBranchProtectedScope();
9838 return OMPMasterTaskLoopDirective::Create(Context, StartLoc, EndLoc,
9839 NestedLoopCount, Clauses, AStmt, B);
9840}
9841
Alexey Bataevb8552ab2019-10-18 16:47:35 +00009842StmtResult Sema::ActOnOpenMPMasterTaskLoopSimdDirective(
9843 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9844 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9845 if (!AStmt)
9846 return StmtError();
9847
9848 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9849 OMPLoopDirective::HelperExprs B;
9850 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9851 // define the nested loops number.
9852 unsigned NestedLoopCount =
9853 checkOpenMPLoop(OMPD_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9854 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
9855 VarsWithImplicitDSA, B);
9856 if (NestedLoopCount == 0)
9857 return StmtError();
9858
9859 assert((CurContext->isDependentContext() || B.builtAll()) &&
9860 "omp for loop exprs were not built");
9861
9862 if (!CurContext->isDependentContext()) {
9863 // Finalize the clauses that need pre-built expressions for CodeGen.
9864 for (OMPClause *C : Clauses) {
9865 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9866 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9867 B.NumIterations, *this, CurScope,
9868 DSAStack))
9869 return StmtError();
9870 }
9871 }
9872
9873 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9874 // The grainsize clause and num_tasks clause are mutually exclusive and may
9875 // not appear on the same taskloop directive.
9876 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9877 return StmtError();
9878 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9879 // If a reduction clause is present on the taskloop directive, the nogroup
9880 // clause must not be specified.
9881 if (checkReductionClauseWithNogroup(*this, Clauses))
9882 return StmtError();
9883 if (checkSimdlenSafelenSpecified(*this, Clauses))
9884 return StmtError();
9885
9886 setFunctionHasBranchProtectedScope();
9887 return OMPMasterTaskLoopSimdDirective::Create(
9888 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9889}
9890
Alexey Bataev5bbcead2019-10-14 17:17:41 +00009891StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopDirective(
9892 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9893 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9894 if (!AStmt)
9895 return StmtError();
9896
9897 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9898 auto *CS = cast<CapturedStmt>(AStmt);
9899 // 1.2.2 OpenMP Language Terminology
9900 // Structured block - An executable statement with a single entry at the
9901 // top and a single exit at the bottom.
9902 // The point of exit cannot be a branch out of the structured block.
9903 // longjmp() and throw() must not violate the entry/exit criteria.
9904 CS->getCapturedDecl()->setNothrow();
9905 for (int ThisCaptureLevel =
9906 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop);
9907 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9908 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9909 // 1.2.2 OpenMP Language Terminology
9910 // Structured block - An executable statement with a single entry at the
9911 // top and a single exit at the bottom.
9912 // The point of exit cannot be a branch out of the structured block.
9913 // longjmp() and throw() must not violate the entry/exit criteria.
9914 CS->getCapturedDecl()->setNothrow();
9915 }
9916
9917 OMPLoopDirective::HelperExprs B;
9918 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9919 // define the nested loops number.
9920 unsigned NestedLoopCount = checkOpenMPLoop(
9921 OMPD_parallel_master_taskloop, getCollapseNumberExpr(Clauses),
9922 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9923 VarsWithImplicitDSA, B);
9924 if (NestedLoopCount == 0)
9925 return StmtError();
9926
9927 assert((CurContext->isDependentContext() || B.builtAll()) &&
9928 "omp for loop exprs were not built");
9929
9930 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9931 // The grainsize clause and num_tasks clause are mutually exclusive and may
9932 // not appear on the same taskloop directive.
9933 if (checkGrainsizeNumTasksClauses(*this, Clauses))
9934 return StmtError();
9935 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9936 // If a reduction clause is present on the taskloop directive, the nogroup
9937 // clause must not be specified.
9938 if (checkReductionClauseWithNogroup(*this, Clauses))
9939 return StmtError();
9940
9941 setFunctionHasBranchProtectedScope();
9942 return OMPParallelMasterTaskLoopDirective::Create(
9943 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
9944}
9945
Alexey Bataev14a388f2019-10-25 10:27:13 -04009946StmtResult Sema::ActOnOpenMPParallelMasterTaskLoopSimdDirective(
9947 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
9948 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
9949 if (!AStmt)
9950 return StmtError();
9951
9952 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
9953 auto *CS = cast<CapturedStmt>(AStmt);
9954 // 1.2.2 OpenMP Language Terminology
9955 // Structured block - An executable statement with a single entry at the
9956 // top and a single exit at the bottom.
9957 // The point of exit cannot be a branch out of the structured block.
9958 // longjmp() and throw() must not violate the entry/exit criteria.
9959 CS->getCapturedDecl()->setNothrow();
9960 for (int ThisCaptureLevel =
9961 getOpenMPCaptureLevels(OMPD_parallel_master_taskloop_simd);
9962 ThisCaptureLevel > 1; --ThisCaptureLevel) {
9963 CS = cast<CapturedStmt>(CS->getCapturedStmt());
9964 // 1.2.2 OpenMP Language Terminology
9965 // Structured block - An executable statement with a single entry at the
9966 // top and a single exit at the bottom.
9967 // The point of exit cannot be a branch out of the structured block.
9968 // longjmp() and throw() must not violate the entry/exit criteria.
9969 CS->getCapturedDecl()->setNothrow();
9970 }
9971
9972 OMPLoopDirective::HelperExprs B;
9973 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
9974 // define the nested loops number.
9975 unsigned NestedLoopCount = checkOpenMPLoop(
9976 OMPD_parallel_master_taskloop_simd, getCollapseNumberExpr(Clauses),
9977 /*OrderedLoopCountExpr=*/nullptr, CS, *this, *DSAStack,
9978 VarsWithImplicitDSA, B);
9979 if (NestedLoopCount == 0)
9980 return StmtError();
9981
9982 assert((CurContext->isDependentContext() || B.builtAll()) &&
9983 "omp for loop exprs were not built");
9984
9985 if (!CurContext->isDependentContext()) {
9986 // Finalize the clauses that need pre-built expressions for CodeGen.
9987 for (OMPClause *C : Clauses) {
9988 if (auto *LC = dyn_cast<OMPLinearClause>(C))
9989 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
9990 B.NumIterations, *this, CurScope,
9991 DSAStack))
9992 return StmtError();
9993 }
9994 }
9995
9996 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
9997 // The grainsize clause and num_tasks clause are mutually exclusive and may
9998 // not appear on the same taskloop directive.
9999 if (checkGrainsizeNumTasksClauses(*this, Clauses))
10000 return StmtError();
10001 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
10002 // If a reduction clause is present on the taskloop directive, the nogroup
10003 // clause must not be specified.
10004 if (checkReductionClauseWithNogroup(*this, Clauses))
10005 return StmtError();
10006 if (checkSimdlenSafelenSpecified(*this, Clauses))
10007 return StmtError();
10008
10009 setFunctionHasBranchProtectedScope();
10010 return OMPParallelMasterTaskLoopSimdDirective::Create(
10011 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10012}
10013
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010014StmtResult Sema::ActOnOpenMPDistributeDirective(
10015 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010016 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010017 if (!AStmt)
10018 return StmtError();
10019
10020 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
10021 OMPLoopDirective::HelperExprs B;
10022 // In presence of clause 'collapse' with number of loops, it will
10023 // define the nested loops number.
10024 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010025 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010026 nullptr /*ordered not a clause on distribute*/, AStmt,
10027 *this, *DSAStack, VarsWithImplicitDSA, B);
10028 if (NestedLoopCount == 0)
10029 return StmtError();
10030
10031 assert((CurContext->isDependentContext() || B.builtAll()) &&
10032 "omp for loop exprs were not built");
10033
Reid Kleckner87a31802018-03-12 21:43:02 +000010034 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010035 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
10036 NestedLoopCount, Clauses, AStmt, B);
10037}
10038
Carlo Bertolli9925f152016-06-27 14:55:37 +000010039StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
10040 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010041 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +000010042 if (!AStmt)
10043 return StmtError();
10044
Alexey Bataeve3727102018-04-18 15:57:46 +000010045 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +000010046 // 1.2.2 OpenMP Language Terminology
10047 // Structured block - An executable statement with a single entry at the
10048 // top and a single exit at the bottom.
10049 // The point of exit cannot be a branch out of the structured block.
10050 // longjmp() and throw() must not violate the entry/exit criteria.
10051 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +000010052 for (int ThisCaptureLevel =
10053 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
10054 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10055 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10056 // 1.2.2 OpenMP Language Terminology
10057 // Structured block - An executable statement with a single entry at the
10058 // top and a single exit at the bottom.
10059 // The point of exit cannot be a branch out of the structured block.
10060 // longjmp() and throw() must not violate the entry/exit criteria.
10061 CS->getCapturedDecl()->setNothrow();
10062 }
Carlo Bertolli9925f152016-06-27 14:55:37 +000010063
10064 OMPLoopDirective::HelperExprs B;
10065 // In presence of clause 'collapse' with number of loops, it will
10066 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010067 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +000010068 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +000010069 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +000010070 VarsWithImplicitDSA, B);
10071 if (NestedLoopCount == 0)
10072 return StmtError();
10073
10074 assert((CurContext->isDependentContext() || B.builtAll()) &&
10075 "omp for loop exprs were not built");
10076
Reid Kleckner87a31802018-03-12 21:43:02 +000010077 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +000010078 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +000010079 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10080 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +000010081}
10082
Kelvin Li4a39add2016-07-05 05:00:15 +000010083StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
10084 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010085 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +000010086 if (!AStmt)
10087 return StmtError();
10088
Alexey Bataeve3727102018-04-18 15:57:46 +000010089 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +000010090 // 1.2.2 OpenMP Language Terminology
10091 // Structured block - An executable statement with a single entry at the
10092 // top and a single exit at the bottom.
10093 // The point of exit cannot be a branch out of the structured block.
10094 // longjmp() and throw() must not violate the entry/exit criteria.
10095 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +000010096 for (int ThisCaptureLevel =
10097 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
10098 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10099 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10100 // 1.2.2 OpenMP Language Terminology
10101 // Structured block - An executable statement with a single entry at the
10102 // top and a single exit at the bottom.
10103 // The point of exit cannot be a branch out of the structured block.
10104 // longjmp() and throw() must not violate the entry/exit criteria.
10105 CS->getCapturedDecl()->setNothrow();
10106 }
Kelvin Li4a39add2016-07-05 05:00:15 +000010107
10108 OMPLoopDirective::HelperExprs B;
10109 // In presence of clause 'collapse' with number of loops, it will
10110 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010111 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +000010112 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +000010113 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +000010114 VarsWithImplicitDSA, B);
10115 if (NestedLoopCount == 0)
10116 return StmtError();
10117
10118 assert((CurContext->isDependentContext() || B.builtAll()) &&
10119 "omp for loop exprs were not built");
10120
Alexey Bataev438388c2017-11-22 18:34:02 +000010121 if (!CurContext->isDependentContext()) {
10122 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010123 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010124 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10125 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10126 B.NumIterations, *this, CurScope,
10127 DSAStack))
10128 return StmtError();
10129 }
10130 }
10131
Kelvin Lic5609492016-07-15 04:39:07 +000010132 if (checkSimdlenSafelenSpecified(*this, Clauses))
10133 return StmtError();
10134
Reid Kleckner87a31802018-03-12 21:43:02 +000010135 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +000010136 return OMPDistributeParallelForSimdDirective::Create(
10137 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10138}
10139
Kelvin Li787f3fc2016-07-06 04:45:38 +000010140StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
10141 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010142 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +000010143 if (!AStmt)
10144 return StmtError();
10145
Alexey Bataeve3727102018-04-18 15:57:46 +000010146 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +000010147 // 1.2.2 OpenMP Language Terminology
10148 // Structured block - An executable statement with a single entry at the
10149 // top and a single exit at the bottom.
10150 // The point of exit cannot be a branch out of the structured block.
10151 // longjmp() and throw() must not violate the entry/exit criteria.
10152 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +000010153 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
10154 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10155 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10156 // 1.2.2 OpenMP Language Terminology
10157 // Structured block - An executable statement with a single entry at the
10158 // top and a single exit at the bottom.
10159 // The point of exit cannot be a branch out of the structured block.
10160 // longjmp() and throw() must not violate the entry/exit criteria.
10161 CS->getCapturedDecl()->setNothrow();
10162 }
Kelvin Li787f3fc2016-07-06 04:45:38 +000010163
10164 OMPLoopDirective::HelperExprs B;
10165 // In presence of clause 'collapse' with number of loops, it will
10166 // define the nested loops number.
10167 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010168 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +000010169 nullptr /*ordered not a clause on distribute*/, CS, *this,
10170 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +000010171 if (NestedLoopCount == 0)
10172 return StmtError();
10173
10174 assert((CurContext->isDependentContext() || B.builtAll()) &&
10175 "omp for loop exprs were not built");
10176
Alexey Bataev438388c2017-11-22 18:34:02 +000010177 if (!CurContext->isDependentContext()) {
10178 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010179 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010180 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10181 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10182 B.NumIterations, *this, CurScope,
10183 DSAStack))
10184 return StmtError();
10185 }
10186 }
10187
Kelvin Lic5609492016-07-15 04:39:07 +000010188 if (checkSimdlenSafelenSpecified(*this, Clauses))
10189 return StmtError();
10190
Reid Kleckner87a31802018-03-12 21:43:02 +000010191 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +000010192 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
10193 NestedLoopCount, Clauses, AStmt, B);
10194}
10195
Kelvin Lia579b912016-07-14 02:54:56 +000010196StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
10197 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010198 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +000010199 if (!AStmt)
10200 return StmtError();
10201
Alexey Bataeve3727102018-04-18 15:57:46 +000010202 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +000010203 // 1.2.2 OpenMP Language Terminology
10204 // Structured block - An executable statement with a single entry at the
10205 // top and a single exit at the bottom.
10206 // The point of exit cannot be a branch out of the structured block.
10207 // longjmp() and throw() must not violate the entry/exit criteria.
10208 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010209 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
10210 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10211 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10212 // 1.2.2 OpenMP Language Terminology
10213 // Structured block - An executable statement with a single entry at the
10214 // top and a single exit at the bottom.
10215 // The point of exit cannot be a branch out of the structured block.
10216 // longjmp() and throw() must not violate the entry/exit criteria.
10217 CS->getCapturedDecl()->setNothrow();
10218 }
Kelvin Lia579b912016-07-14 02:54:56 +000010219
10220 OMPLoopDirective::HelperExprs B;
10221 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
10222 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010223 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +000010224 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +000010225 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +000010226 VarsWithImplicitDSA, B);
10227 if (NestedLoopCount == 0)
10228 return StmtError();
10229
10230 assert((CurContext->isDependentContext() || B.builtAll()) &&
10231 "omp target parallel for simd loop exprs were not built");
10232
10233 if (!CurContext->isDependentContext()) {
10234 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010235 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010236 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +000010237 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10238 B.NumIterations, *this, CurScope,
10239 DSAStack))
10240 return StmtError();
10241 }
10242 }
Kelvin Lic5609492016-07-15 04:39:07 +000010243 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +000010244 return StmtError();
10245
Reid Kleckner87a31802018-03-12 21:43:02 +000010246 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +000010247 return OMPTargetParallelForSimdDirective::Create(
10248 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10249}
10250
Kelvin Li986330c2016-07-20 22:57:10 +000010251StmtResult Sema::ActOnOpenMPTargetSimdDirective(
10252 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010253 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +000010254 if (!AStmt)
10255 return StmtError();
10256
Alexey Bataeve3727102018-04-18 15:57:46 +000010257 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +000010258 // 1.2.2 OpenMP Language Terminology
10259 // Structured block - An executable statement with a single entry at the
10260 // top and a single exit at the bottom.
10261 // The point of exit cannot be a branch out of the structured block.
10262 // longjmp() and throw() must not violate the entry/exit criteria.
10263 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +000010264 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
10265 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10266 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10267 // 1.2.2 OpenMP Language Terminology
10268 // Structured block - An executable statement with a single entry at the
10269 // top and a single exit at the bottom.
10270 // The point of exit cannot be a branch out of the structured block.
10271 // longjmp() and throw() must not violate the entry/exit criteria.
10272 CS->getCapturedDecl()->setNothrow();
10273 }
10274
Kelvin Li986330c2016-07-20 22:57:10 +000010275 OMPLoopDirective::HelperExprs B;
10276 // In presence of clause 'collapse' with number of loops, it will define the
10277 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +000010278 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010279 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +000010280 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +000010281 VarsWithImplicitDSA, B);
10282 if (NestedLoopCount == 0)
10283 return StmtError();
10284
10285 assert((CurContext->isDependentContext() || B.builtAll()) &&
10286 "omp target simd loop exprs were not built");
10287
10288 if (!CurContext->isDependentContext()) {
10289 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010290 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +000010291 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +000010292 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10293 B.NumIterations, *this, CurScope,
10294 DSAStack))
10295 return StmtError();
10296 }
10297 }
10298
10299 if (checkSimdlenSafelenSpecified(*this, Clauses))
10300 return StmtError();
10301
Reid Kleckner87a31802018-03-12 21:43:02 +000010302 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +000010303 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
10304 NestedLoopCount, Clauses, AStmt, B);
10305}
10306
Kelvin Li02532872016-08-05 14:37:37 +000010307StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
10308 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010309 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +000010310 if (!AStmt)
10311 return StmtError();
10312
Alexey Bataeve3727102018-04-18 15:57:46 +000010313 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +000010314 // 1.2.2 OpenMP Language Terminology
10315 // Structured block - An executable statement with a single entry at the
10316 // top and a single exit at the bottom.
10317 // The point of exit cannot be a branch out of the structured block.
10318 // longjmp() and throw() must not violate the entry/exit criteria.
10319 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010320 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
10321 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10322 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10323 // 1.2.2 OpenMP Language Terminology
10324 // Structured block - An executable statement with a single entry at the
10325 // top and a single exit at the bottom.
10326 // The point of exit cannot be a branch out of the structured block.
10327 // longjmp() and throw() must not violate the entry/exit criteria.
10328 CS->getCapturedDecl()->setNothrow();
10329 }
Kelvin Li02532872016-08-05 14:37:37 +000010330
10331 OMPLoopDirective::HelperExprs B;
10332 // In presence of clause 'collapse' with number of loops, it will
10333 // define the nested loops number.
10334 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +000010335 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +000010336 nullptr /*ordered not a clause on distribute*/, CS, *this,
10337 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +000010338 if (NestedLoopCount == 0)
10339 return StmtError();
10340
10341 assert((CurContext->isDependentContext() || B.builtAll()) &&
10342 "omp teams distribute loop exprs were not built");
10343
Reid Kleckner87a31802018-03-12 21:43:02 +000010344 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010345
10346 DSAStack->setParentTeamsRegionLoc(StartLoc);
10347
David Majnemer9d168222016-08-05 17:44:54 +000010348 return OMPTeamsDistributeDirective::Create(
10349 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +000010350}
10351
Kelvin Li4e325f72016-10-25 12:50:55 +000010352StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
10353 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010354 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010355 if (!AStmt)
10356 return StmtError();
10357
Alexey Bataeve3727102018-04-18 15:57:46 +000010358 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +000010359 // 1.2.2 OpenMP Language Terminology
10360 // Structured block - An executable statement with a single entry at the
10361 // top and a single exit at the bottom.
10362 // The point of exit cannot be a branch out of the structured block.
10363 // longjmp() and throw() must not violate the entry/exit criteria.
10364 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +000010365 for (int ThisCaptureLevel =
10366 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
10367 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10368 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10369 // 1.2.2 OpenMP Language Terminology
10370 // Structured block - An executable statement with a single entry at the
10371 // top and a single exit at the bottom.
10372 // The point of exit cannot be a branch out of the structured block.
10373 // longjmp() and throw() must not violate the entry/exit criteria.
10374 CS->getCapturedDecl()->setNothrow();
10375 }
10376
Kelvin Li4e325f72016-10-25 12:50:55 +000010377
10378 OMPLoopDirective::HelperExprs B;
10379 // In presence of clause 'collapse' with number of loops, it will
10380 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010381 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +000010382 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +000010383 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +000010384 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +000010385
10386 if (NestedLoopCount == 0)
10387 return StmtError();
10388
10389 assert((CurContext->isDependentContext() || B.builtAll()) &&
10390 "omp teams distribute simd loop exprs were not built");
10391
10392 if (!CurContext->isDependentContext()) {
10393 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010394 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +000010395 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10396 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10397 B.NumIterations, *this, CurScope,
10398 DSAStack))
10399 return StmtError();
10400 }
10401 }
10402
10403 if (checkSimdlenSafelenSpecified(*this, Clauses))
10404 return StmtError();
10405
Reid Kleckner87a31802018-03-12 21:43:02 +000010406 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010407
10408 DSAStack->setParentTeamsRegionLoc(StartLoc);
10409
Kelvin Li4e325f72016-10-25 12:50:55 +000010410 return OMPTeamsDistributeSimdDirective::Create(
10411 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10412}
10413
Kelvin Li579e41c2016-11-30 23:51:03 +000010414StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
10415 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010416 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010417 if (!AStmt)
10418 return StmtError();
10419
Alexey Bataeve3727102018-04-18 15:57:46 +000010420 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +000010421 // 1.2.2 OpenMP Language Terminology
10422 // Structured block - An executable statement with a single entry at the
10423 // top and a single exit at the bottom.
10424 // The point of exit cannot be a branch out of the structured block.
10425 // longjmp() and throw() must not violate the entry/exit criteria.
10426 CS->getCapturedDecl()->setNothrow();
10427
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010428 for (int ThisCaptureLevel =
10429 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
10430 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10431 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10432 // 1.2.2 OpenMP Language Terminology
10433 // Structured block - An executable statement with a single entry at the
10434 // top and a single exit at the bottom.
10435 // The point of exit cannot be a branch out of the structured block.
10436 // longjmp() and throw() must not violate the entry/exit criteria.
10437 CS->getCapturedDecl()->setNothrow();
10438 }
10439
Kelvin Li579e41c2016-11-30 23:51:03 +000010440 OMPLoopDirective::HelperExprs B;
10441 // In presence of clause 'collapse' with number of loops, it will
10442 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010443 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +000010444 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +000010445 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +000010446 VarsWithImplicitDSA, B);
10447
10448 if (NestedLoopCount == 0)
10449 return StmtError();
10450
10451 assert((CurContext->isDependentContext() || B.builtAll()) &&
10452 "omp for loop exprs were not built");
10453
10454 if (!CurContext->isDependentContext()) {
10455 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010456 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +000010457 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10458 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10459 B.NumIterations, *this, CurScope,
10460 DSAStack))
10461 return StmtError();
10462 }
10463 }
10464
10465 if (checkSimdlenSafelenSpecified(*this, Clauses))
10466 return StmtError();
10467
Reid Kleckner87a31802018-03-12 21:43:02 +000010468 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010469
10470 DSAStack->setParentTeamsRegionLoc(StartLoc);
10471
Kelvin Li579e41c2016-11-30 23:51:03 +000010472 return OMPTeamsDistributeParallelForSimdDirective::Create(
10473 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10474}
10475
Kelvin Li7ade93f2016-12-09 03:24:30 +000010476StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
10477 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010478 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +000010479 if (!AStmt)
10480 return StmtError();
10481
Alexey Bataeve3727102018-04-18 15:57:46 +000010482 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +000010483 // 1.2.2 OpenMP Language Terminology
10484 // Structured block - An executable statement with a single entry at the
10485 // top and a single exit at the bottom.
10486 // The point of exit cannot be a branch out of the structured block.
10487 // longjmp() and throw() must not violate the entry/exit criteria.
10488 CS->getCapturedDecl()->setNothrow();
10489
Carlo Bertolli62fae152017-11-20 20:46:39 +000010490 for (int ThisCaptureLevel =
10491 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
10492 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10493 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10494 // 1.2.2 OpenMP Language Terminology
10495 // Structured block - An executable statement with a single entry at the
10496 // top and a single exit at the bottom.
10497 // The point of exit cannot be a branch out of the structured block.
10498 // longjmp() and throw() must not violate the entry/exit criteria.
10499 CS->getCapturedDecl()->setNothrow();
10500 }
10501
Kelvin Li7ade93f2016-12-09 03:24:30 +000010502 OMPLoopDirective::HelperExprs B;
10503 // In presence of clause 'collapse' with number of loops, it will
10504 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010505 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +000010506 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +000010507 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +000010508 VarsWithImplicitDSA, B);
10509
10510 if (NestedLoopCount == 0)
10511 return StmtError();
10512
10513 assert((CurContext->isDependentContext() || B.builtAll()) &&
10514 "omp for loop exprs were not built");
10515
Reid Kleckner87a31802018-03-12 21:43:02 +000010516 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +000010517
10518 DSAStack->setParentTeamsRegionLoc(StartLoc);
10519
Kelvin Li7ade93f2016-12-09 03:24:30 +000010520 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +000010521 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10522 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +000010523}
10524
Kelvin Libf594a52016-12-17 05:48:59 +000010525StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
10526 Stmt *AStmt,
10527 SourceLocation StartLoc,
10528 SourceLocation EndLoc) {
10529 if (!AStmt)
10530 return StmtError();
10531
Alexey Bataeve3727102018-04-18 15:57:46 +000010532 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +000010533 // 1.2.2 OpenMP Language Terminology
10534 // Structured block - An executable statement with a single entry at the
10535 // top and a single exit at the bottom.
10536 // The point of exit cannot be a branch out of the structured block.
10537 // longjmp() and throw() must not violate the entry/exit criteria.
10538 CS->getCapturedDecl()->setNothrow();
10539
Alexey Bataevf9fc42e2017-11-22 14:25:55 +000010540 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
10541 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10542 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10543 // 1.2.2 OpenMP Language Terminology
10544 // Structured block - An executable statement with a single entry at the
10545 // top and a single exit at the bottom.
10546 // The point of exit cannot be a branch out of the structured block.
10547 // longjmp() and throw() must not violate the entry/exit criteria.
10548 CS->getCapturedDecl()->setNothrow();
10549 }
Reid Kleckner87a31802018-03-12 21:43:02 +000010550 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +000010551
10552 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
10553 AStmt);
10554}
10555
Kelvin Li83c451e2016-12-25 04:52:54 +000010556StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
10557 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010558 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +000010559 if (!AStmt)
10560 return StmtError();
10561
Alexey Bataeve3727102018-04-18 15:57:46 +000010562 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +000010563 // 1.2.2 OpenMP Language Terminology
10564 // Structured block - An executable statement with a single entry at the
10565 // top and a single exit at the bottom.
10566 // The point of exit cannot be a branch out of the structured block.
10567 // longjmp() and throw() must not violate the entry/exit criteria.
10568 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010569 for (int ThisCaptureLevel =
10570 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
10571 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10572 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10573 // 1.2.2 OpenMP Language Terminology
10574 // Structured block - An executable statement with a single entry at the
10575 // top and a single exit at the bottom.
10576 // The point of exit cannot be a branch out of the structured block.
10577 // longjmp() and throw() must not violate the entry/exit criteria.
10578 CS->getCapturedDecl()->setNothrow();
10579 }
Kelvin Li83c451e2016-12-25 04:52:54 +000010580
10581 OMPLoopDirective::HelperExprs B;
10582 // In presence of clause 'collapse' with number of loops, it will
10583 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010584 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +000010585 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
10586 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +000010587 VarsWithImplicitDSA, B);
10588 if (NestedLoopCount == 0)
10589 return StmtError();
10590
10591 assert((CurContext->isDependentContext() || B.builtAll()) &&
10592 "omp target teams distribute loop exprs were not built");
10593
Reid Kleckner87a31802018-03-12 21:43:02 +000010594 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +000010595 return OMPTargetTeamsDistributeDirective::Create(
10596 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10597}
10598
Kelvin Li80e8f562016-12-29 22:16:30 +000010599StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
10600 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010601 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +000010602 if (!AStmt)
10603 return StmtError();
10604
Alexey Bataeve3727102018-04-18 15:57:46 +000010605 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +000010606 // 1.2.2 OpenMP Language Terminology
10607 // Structured block - An executable statement with a single entry at the
10608 // top and a single exit at the bottom.
10609 // The point of exit cannot be a branch out of the structured block.
10610 // longjmp() and throw() must not violate the entry/exit criteria.
10611 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +000010612 for (int ThisCaptureLevel =
10613 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
10614 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10615 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10616 // 1.2.2 OpenMP Language Terminology
10617 // Structured block - An executable statement with a single entry at the
10618 // top and a single exit at the bottom.
10619 // The point of exit cannot be a branch out of the structured block.
10620 // longjmp() and throw() must not violate the entry/exit criteria.
10621 CS->getCapturedDecl()->setNothrow();
10622 }
10623
Kelvin Li80e8f562016-12-29 22:16:30 +000010624 OMPLoopDirective::HelperExprs B;
10625 // In presence of clause 'collapse' with number of loops, it will
10626 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010627 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +000010628 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
10629 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +000010630 VarsWithImplicitDSA, B);
10631 if (NestedLoopCount == 0)
10632 return StmtError();
10633
10634 assert((CurContext->isDependentContext() || B.builtAll()) &&
10635 "omp target teams distribute parallel for loop exprs were not built");
10636
Alexey Bataev647dd842018-01-15 20:59:40 +000010637 if (!CurContext->isDependentContext()) {
10638 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010639 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +000010640 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10641 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10642 B.NumIterations, *this, CurScope,
10643 DSAStack))
10644 return StmtError();
10645 }
10646 }
10647
Reid Kleckner87a31802018-03-12 21:43:02 +000010648 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +000010649 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +000010650 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
10651 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +000010652}
10653
Kelvin Li1851df52017-01-03 05:23:48 +000010654StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
10655 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010656 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +000010657 if (!AStmt)
10658 return StmtError();
10659
Alexey Bataeve3727102018-04-18 15:57:46 +000010660 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +000010661 // 1.2.2 OpenMP Language Terminology
10662 // Structured block - An executable statement with a single entry at the
10663 // top and a single exit at the bottom.
10664 // The point of exit cannot be a branch out of the structured block.
10665 // longjmp() and throw() must not violate the entry/exit criteria.
10666 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +000010667 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
10668 OMPD_target_teams_distribute_parallel_for_simd);
10669 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10670 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10671 // 1.2.2 OpenMP Language Terminology
10672 // Structured block - An executable statement with a single entry at the
10673 // top and a single exit at the bottom.
10674 // The point of exit cannot be a branch out of the structured block.
10675 // longjmp() and throw() must not violate the entry/exit criteria.
10676 CS->getCapturedDecl()->setNothrow();
10677 }
Kelvin Li1851df52017-01-03 05:23:48 +000010678
10679 OMPLoopDirective::HelperExprs B;
10680 // In presence of clause 'collapse' with number of loops, it will
10681 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010682 unsigned NestedLoopCount =
10683 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +000010684 getCollapseNumberExpr(Clauses),
10685 nullptr /*ordered not a clause on distribute*/, CS, *this,
10686 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +000010687 if (NestedLoopCount == 0)
10688 return StmtError();
10689
10690 assert((CurContext->isDependentContext() || B.builtAll()) &&
10691 "omp target teams distribute parallel for simd loop exprs were not "
10692 "built");
10693
10694 if (!CurContext->isDependentContext()) {
10695 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010696 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +000010697 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10698 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10699 B.NumIterations, *this, CurScope,
10700 DSAStack))
10701 return StmtError();
10702 }
10703 }
10704
Alexey Bataev438388c2017-11-22 18:34:02 +000010705 if (checkSimdlenSafelenSpecified(*this, Clauses))
10706 return StmtError();
10707
Reid Kleckner87a31802018-03-12 21:43:02 +000010708 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +000010709 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
10710 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10711}
10712
Kelvin Lida681182017-01-10 18:08:18 +000010713StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
10714 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +000010715 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +000010716 if (!AStmt)
10717 return StmtError();
10718
10719 auto *CS = cast<CapturedStmt>(AStmt);
10720 // 1.2.2 OpenMP Language Terminology
10721 // Structured block - An executable statement with a single entry at the
10722 // top and a single exit at the bottom.
10723 // The point of exit cannot be a branch out of the structured block.
10724 // longjmp() and throw() must not violate the entry/exit criteria.
10725 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010726 for (int ThisCaptureLevel =
10727 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
10728 ThisCaptureLevel > 1; --ThisCaptureLevel) {
10729 CS = cast<CapturedStmt>(CS->getCapturedStmt());
10730 // 1.2.2 OpenMP Language Terminology
10731 // Structured block - An executable statement with a single entry at the
10732 // top and a single exit at the bottom.
10733 // The point of exit cannot be a branch out of the structured block.
10734 // longjmp() and throw() must not violate the entry/exit criteria.
10735 CS->getCapturedDecl()->setNothrow();
10736 }
Kelvin Lida681182017-01-10 18:08:18 +000010737
10738 OMPLoopDirective::HelperExprs B;
10739 // In presence of clause 'collapse' with number of loops, it will
10740 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +000010741 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +000010742 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +000010743 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +000010744 VarsWithImplicitDSA, B);
10745 if (NestedLoopCount == 0)
10746 return StmtError();
10747
10748 assert((CurContext->isDependentContext() || B.builtAll()) &&
10749 "omp target teams distribute simd loop exprs were not built");
10750
Alexey Bataev438388c2017-11-22 18:34:02 +000010751 if (!CurContext->isDependentContext()) {
10752 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010753 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +000010754 if (auto *LC = dyn_cast<OMPLinearClause>(C))
10755 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
10756 B.NumIterations, *this, CurScope,
10757 DSAStack))
10758 return StmtError();
10759 }
10760 }
10761
10762 if (checkSimdlenSafelenSpecified(*this, Clauses))
10763 return StmtError();
10764
Reid Kleckner87a31802018-03-12 21:43:02 +000010765 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +000010766 return OMPTargetTeamsDistributeSimdDirective::Create(
10767 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
10768}
10769
Alexey Bataeved09d242014-05-28 05:53:51 +000010770OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010771 SourceLocation StartLoc,
10772 SourceLocation LParenLoc,
10773 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010774 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010775 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +000010776 case OMPC_final:
10777 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
10778 break;
Alexey Bataev568a8332014-03-06 06:15:19 +000010779 case OMPC_num_threads:
10780 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
10781 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +000010782 case OMPC_safelen:
10783 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
10784 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +000010785 case OMPC_simdlen:
10786 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
10787 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010788 case OMPC_allocator:
10789 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
10790 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +000010791 case OMPC_collapse:
10792 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
10793 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +000010794 case OMPC_ordered:
10795 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
10796 break;
Michael Wonge710d542015-08-07 16:16:36 +000010797 case OMPC_device:
10798 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
10799 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +000010800 case OMPC_num_teams:
10801 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
10802 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010803 case OMPC_thread_limit:
10804 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
10805 break;
Alexey Bataeva0569352015-12-01 10:17:31 +000010806 case OMPC_priority:
10807 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
10808 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010809 case OMPC_grainsize:
10810 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
10811 break;
Alexey Bataev382967a2015-12-08 12:06:20 +000010812 case OMPC_num_tasks:
10813 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
10814 break;
Alexey Bataev28c75412015-12-15 08:19:24 +000010815 case OMPC_hint:
10816 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
10817 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010818 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010819 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010820 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010821 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010822 case OMPC_private:
10823 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000010824 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010825 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000010826 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010827 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010828 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000010829 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010830 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010831 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010832 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +000010833 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010834 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010835 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010836 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010837 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010838 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010839 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010840 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010841 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010842 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010843 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010844 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +000010845 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010846 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010847 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +000010848 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010849 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010850 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010851 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010852 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010853 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010854 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010855 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010856 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010857 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010858 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010859 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010860 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010861 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000010862 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000010863 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050010864 case OMPC_nontemporal:
Alexey Bataevcb8e6912020-01-31 16:09:26 -050010865 case OMPC_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010866 llvm_unreachable("Clause is not allowed.");
10867 }
10868 return Res;
10869}
10870
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010871// An OpenMP directive such as 'target parallel' has two captured regions:
10872// for the 'target' and 'parallel' respectively. This function returns
10873// the region in which to capture expressions associated with a clause.
10874// A return value of OMPD_unknown signifies that the expression should not
10875// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010876static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050010877 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, unsigned OpenMPVersion,
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000010878 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010879 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010880 switch (CKind) {
10881 case OMPC_if:
10882 switch (DKind) {
Alexey Bataevda17a532019-12-10 11:37:03 -050010883 case OMPD_target_parallel_for_simd:
10884 if (OpenMPVersion >= 50 &&
Alexey Bataevd8c31d42019-12-11 12:59:01 -050010885 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
Alexey Bataevda17a532019-12-10 11:37:03 -050010886 CaptureRegion = OMPD_parallel;
Alexey Bataevd8c31d42019-12-11 12:59:01 -050010887 break;
10888 }
Alexey Bataevda17a532019-12-10 11:37:03 -050010889 LLVM_FALLTHROUGH;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010890 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000010891 case OMPD_target_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010892 // If this clause applies to the nested 'parallel' region, capture within
10893 // the 'target' region, otherwise do not capture.
10894 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10895 CaptureRegion = OMPD_target;
10896 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +000010897 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevfd0c91b2019-12-16 10:27:39 -050010898 if (OpenMPVersion >= 50 &&
10899 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
10900 CaptureRegion = OMPD_parallel;
10901 break;
10902 }
10903 LLVM_FALLTHROUGH;
10904 case OMPD_target_teams_distribute_parallel_for:
Carlo Bertolli52978c32018-01-03 21:12:44 +000010905 // If this clause applies to the nested 'parallel' region, capture within
10906 // the 'teams' region, otherwise do not capture.
10907 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
10908 CaptureRegion = OMPD_teams;
10909 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000010910 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataev0b978942019-12-11 15:26:38 -050010911 if (OpenMPVersion >= 50 &&
10912 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)) {
10913 CaptureRegion = OMPD_parallel;
10914 break;
10915 }
10916 LLVM_FALLTHROUGH;
10917 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli62fae152017-11-20 20:46:39 +000010918 CaptureRegion = OMPD_teams;
10919 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010920 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000010921 case OMPD_target_enter_data:
10922 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000010923 CaptureRegion = OMPD_task;
10924 break;
Alexey Bataev5bbcead2019-10-14 17:17:41 +000010925 case OMPD_parallel_master_taskloop:
10926 if (NameModifier == OMPD_unknown || NameModifier == OMPD_taskloop)
10927 CaptureRegion = OMPD_parallel;
10928 break;
Alexey Bataev5c517a62019-12-05 11:31:45 -050010929 case OMPD_parallel_master_taskloop_simd:
10930 if ((OpenMPVersion <= 45 && NameModifier == OMPD_unknown) ||
10931 NameModifier == OMPD_taskloop) {
10932 CaptureRegion = OMPD_parallel;
10933 break;
10934 }
10935 if (OpenMPVersion <= 45)
10936 break;
10937 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10938 CaptureRegion = OMPD_taskloop;
10939 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050010940 case OMPD_parallel_for_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050010941 if (OpenMPVersion <= 45)
10942 break;
Alexey Bataevf59614d2019-11-21 10:00:56 -050010943 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10944 CaptureRegion = OMPD_parallel;
10945 break;
Alexey Bataev61205822019-12-04 09:50:21 -050010946 case OMPD_taskloop_simd:
Alexey Bataev853961f2019-12-05 09:50:18 -050010947 case OMPD_master_taskloop_simd:
Alexey Bataev61205822019-12-04 09:50:21 -050010948 if (OpenMPVersion <= 45)
10949 break;
10950 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10951 CaptureRegion = OMPD_taskloop;
10952 break;
Alexey Bataev52812f22019-12-05 13:22:15 -050010953 case OMPD_distribute_parallel_for_simd:
10954 if (OpenMPVersion <= 45)
10955 break;
10956 if (NameModifier == OMPD_unknown || NameModifier == OMPD_simd)
10957 CaptureRegion = OMPD_parallel;
10958 break;
Alexey Bataevef94cd12019-12-10 12:44:45 -050010959 case OMPD_target_simd:
10960 if (OpenMPVersion >= 50 &&
10961 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
10962 CaptureRegion = OMPD_target;
10963 break;
Alexey Bataev7b774b72019-12-11 11:20:47 -050010964 case OMPD_teams_distribute_simd:
Alexey Bataev411e81a2019-12-16 11:16:46 -050010965 case OMPD_target_teams_distribute_simd:
Alexey Bataev7b774b72019-12-11 11:20:47 -050010966 if (OpenMPVersion >= 50 &&
10967 (NameModifier == OMPD_unknown || NameModifier == OMPD_simd))
10968 CaptureRegion = OMPD_teams;
10969 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010970 case OMPD_cancel:
10971 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050010972 case OMPD_parallel_master:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010973 case OMPD_parallel_sections:
10974 case OMPD_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010975 case OMPD_target:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010976 case OMPD_target_teams:
10977 case OMPD_target_teams_distribute:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010978 case OMPD_distribute_parallel_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010979 case OMPD_task:
10980 case OMPD_taskloop:
Alexey Bataev60e51c42019-10-10 20:13:02 +000010981 case OMPD_master_taskloop:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010982 case OMPD_target_data:
Alexey Bataevd08c0562019-11-19 12:07:54 -050010983 case OMPD_simd:
Alexey Bataev103f3c9e2019-11-20 15:59:03 -050010984 case OMPD_for_simd:
Alexey Bataev779a1802019-12-06 12:21:31 -050010985 case OMPD_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010986 // Do not capture if-clause expressions.
10987 break;
10988 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010989 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010990 case OMPD_taskyield:
10991 case OMPD_barrier:
10992 case OMPD_taskwait:
10993 case OMPD_cancellation_point:
10994 case OMPD_flush:
10995 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000010996 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010997 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000010998 case OMPD_declare_variant:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000010999 case OMPD_declare_target:
11000 case OMPD_end_declare_target:
11001 case OMPD_teams:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011002 case OMPD_for:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011003 case OMPD_sections:
11004 case OMPD_section:
11005 case OMPD_single:
11006 case OMPD_master:
11007 case OMPD_critical:
11008 case OMPD_taskgroup:
11009 case OMPD_distribute:
11010 case OMPD_ordered:
11011 case OMPD_atomic:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011012 case OMPD_teams_distribute:
Kelvin Li1408f912018-09-26 04:28:39 +000011013 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011014 llvm_unreachable("Unexpected OpenMP directive with if-clause");
11015 case OMPD_unknown:
11016 llvm_unreachable("Unknown OpenMP directive");
11017 }
11018 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011019 case OMPC_num_threads:
11020 switch (DKind) {
11021 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011022 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +000011023 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011024 CaptureRegion = OMPD_target;
11025 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +000011026 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011027 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011028 case OMPD_target_teams_distribute_parallel_for:
11029 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011030 CaptureRegion = OMPD_teams;
11031 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011032 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011033 case OMPD_parallel_master:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011034 case OMPD_parallel_sections:
11035 case OMPD_parallel_for:
11036 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011037 case OMPD_distribute_parallel_for:
11038 case OMPD_distribute_parallel_for_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011039 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011040 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011041 // Do not capture num_threads-clause expressions.
11042 break;
11043 case OMPD_target_data:
11044 case OMPD_target_enter_data:
11045 case OMPD_target_exit_data:
11046 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011047 case OMPD_target:
11048 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011049 case OMPD_target_teams:
11050 case OMPD_target_teams_distribute:
11051 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011052 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011053 case OMPD_task:
11054 case OMPD_taskloop:
11055 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011056 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011057 case OMPD_master_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011058 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011059 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011060 case OMPD_taskyield:
11061 case OMPD_barrier:
11062 case OMPD_taskwait:
11063 case OMPD_cancellation_point:
11064 case OMPD_flush:
11065 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011066 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011067 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011068 case OMPD_declare_variant:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011069 case OMPD_declare_target:
11070 case OMPD_end_declare_target:
11071 case OMPD_teams:
11072 case OMPD_simd:
11073 case OMPD_for:
11074 case OMPD_for_simd:
11075 case OMPD_sections:
11076 case OMPD_section:
11077 case OMPD_single:
11078 case OMPD_master:
11079 case OMPD_critical:
11080 case OMPD_taskgroup:
11081 case OMPD_distribute:
11082 case OMPD_ordered:
11083 case OMPD_atomic:
11084 case OMPD_distribute_simd:
11085 case OMPD_teams_distribute:
11086 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011087 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011088 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
11089 case OMPD_unknown:
11090 llvm_unreachable("Unknown OpenMP directive");
11091 }
11092 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011093 case OMPC_num_teams:
11094 switch (DKind) {
11095 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011096 case OMPD_target_teams_distribute:
11097 case OMPD_target_teams_distribute_simd:
11098 case OMPD_target_teams_distribute_parallel_for:
11099 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011100 CaptureRegion = OMPD_target;
11101 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011102 case OMPD_teams_distribute_parallel_for:
11103 case OMPD_teams_distribute_parallel_for_simd:
11104 case OMPD_teams:
11105 case OMPD_teams_distribute:
11106 case OMPD_teams_distribute_simd:
11107 // Do not capture num_teams-clause expressions.
11108 break;
11109 case OMPD_distribute_parallel_for:
11110 case OMPD_distribute_parallel_for_simd:
11111 case OMPD_task:
11112 case OMPD_taskloop:
11113 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011114 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011115 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011116 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011117 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011118 case OMPD_target_data:
11119 case OMPD_target_enter_data:
11120 case OMPD_target_exit_data:
11121 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011122 case OMPD_cancel:
11123 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011124 case OMPD_parallel_master:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011125 case OMPD_parallel_sections:
11126 case OMPD_parallel_for:
11127 case OMPD_parallel_for_simd:
11128 case OMPD_target:
11129 case OMPD_target_simd:
11130 case OMPD_target_parallel:
11131 case OMPD_target_parallel_for:
11132 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011133 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011134 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011135 case OMPD_taskyield:
11136 case OMPD_barrier:
11137 case OMPD_taskwait:
11138 case OMPD_cancellation_point:
11139 case OMPD_flush:
11140 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011141 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011142 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011143 case OMPD_declare_variant:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011144 case OMPD_declare_target:
11145 case OMPD_end_declare_target:
11146 case OMPD_simd:
11147 case OMPD_for:
11148 case OMPD_for_simd:
11149 case OMPD_sections:
11150 case OMPD_section:
11151 case OMPD_single:
11152 case OMPD_master:
11153 case OMPD_critical:
11154 case OMPD_taskgroup:
11155 case OMPD_distribute:
11156 case OMPD_ordered:
11157 case OMPD_atomic:
11158 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011159 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000011160 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11161 case OMPD_unknown:
11162 llvm_unreachable("Unknown OpenMP directive");
11163 }
11164 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011165 case OMPC_thread_limit:
11166 switch (DKind) {
11167 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011168 case OMPD_target_teams_distribute:
11169 case OMPD_target_teams_distribute_simd:
11170 case OMPD_target_teams_distribute_parallel_for:
11171 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011172 CaptureRegion = OMPD_target;
11173 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011174 case OMPD_teams_distribute_parallel_for:
11175 case OMPD_teams_distribute_parallel_for_simd:
11176 case OMPD_teams:
11177 case OMPD_teams_distribute:
11178 case OMPD_teams_distribute_simd:
11179 // Do not capture thread_limit-clause expressions.
11180 break;
11181 case OMPD_distribute_parallel_for:
11182 case OMPD_distribute_parallel_for_simd:
11183 case OMPD_task:
11184 case OMPD_taskloop:
11185 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011186 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011187 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011188 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011189 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011190 case OMPD_target_data:
11191 case OMPD_target_enter_data:
11192 case OMPD_target_exit_data:
11193 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011194 case OMPD_cancel:
11195 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011196 case OMPD_parallel_master:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011197 case OMPD_parallel_sections:
11198 case OMPD_parallel_for:
11199 case OMPD_parallel_for_simd:
11200 case OMPD_target:
11201 case OMPD_target_simd:
11202 case OMPD_target_parallel:
11203 case OMPD_target_parallel_for:
11204 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011205 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011206 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011207 case OMPD_taskyield:
11208 case OMPD_barrier:
11209 case OMPD_taskwait:
11210 case OMPD_cancellation_point:
11211 case OMPD_flush:
11212 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011213 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011214 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011215 case OMPD_declare_variant:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011216 case OMPD_declare_target:
11217 case OMPD_end_declare_target:
11218 case OMPD_simd:
11219 case OMPD_for:
11220 case OMPD_for_simd:
11221 case OMPD_sections:
11222 case OMPD_section:
11223 case OMPD_single:
11224 case OMPD_master:
11225 case OMPD_critical:
11226 case OMPD_taskgroup:
11227 case OMPD_distribute:
11228 case OMPD_ordered:
11229 case OMPD_atomic:
11230 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011231 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000011232 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
11233 case OMPD_unknown:
11234 llvm_unreachable("Unknown OpenMP directive");
11235 }
11236 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011237 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011238 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +000011239 case OMPD_parallel_for:
11240 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000011241 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +000011242 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011243 case OMPD_teams_distribute_parallel_for:
11244 case OMPD_teams_distribute_parallel_for_simd:
11245 case OMPD_target_parallel_for:
11246 case OMPD_target_parallel_for_simd:
11247 case OMPD_target_teams_distribute_parallel_for:
11248 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +000011249 CaptureRegion = OMPD_parallel;
11250 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011251 case OMPD_for:
11252 case OMPD_for_simd:
11253 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011254 break;
11255 case OMPD_task:
11256 case OMPD_taskloop:
11257 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011258 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011259 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011260 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011261 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011262 case OMPD_target_data:
11263 case OMPD_target_enter_data:
11264 case OMPD_target_exit_data:
11265 case OMPD_target_update:
11266 case OMPD_teams:
11267 case OMPD_teams_distribute:
11268 case OMPD_teams_distribute_simd:
11269 case OMPD_target_teams_distribute:
11270 case OMPD_target_teams_distribute_simd:
11271 case OMPD_target:
11272 case OMPD_target_simd:
11273 case OMPD_target_parallel:
11274 case OMPD_cancel:
11275 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011276 case OMPD_parallel_master:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011277 case OMPD_parallel_sections:
11278 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011279 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011280 case OMPD_taskyield:
11281 case OMPD_barrier:
11282 case OMPD_taskwait:
11283 case OMPD_cancellation_point:
11284 case OMPD_flush:
11285 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011286 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011287 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011288 case OMPD_declare_variant:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011289 case OMPD_declare_target:
11290 case OMPD_end_declare_target:
11291 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011292 case OMPD_sections:
11293 case OMPD_section:
11294 case OMPD_single:
11295 case OMPD_master:
11296 case OMPD_critical:
11297 case OMPD_taskgroup:
11298 case OMPD_distribute:
11299 case OMPD_ordered:
11300 case OMPD_atomic:
11301 case OMPD_distribute_simd:
11302 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011303 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +000011304 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11305 case OMPD_unknown:
11306 llvm_unreachable("Unknown OpenMP directive");
11307 }
11308 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011309 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011310 switch (DKind) {
11311 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011312 case OMPD_teams_distribute_parallel_for_simd:
11313 case OMPD_teams_distribute:
11314 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011315 case OMPD_target_teams_distribute_parallel_for:
11316 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011317 case OMPD_target_teams_distribute:
11318 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +000011319 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011320 break;
11321 case OMPD_distribute_parallel_for:
11322 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011323 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011324 case OMPD_distribute_simd:
11325 // Do not capture thread_limit-clause expressions.
11326 break;
11327 case OMPD_parallel_for:
11328 case OMPD_parallel_for_simd:
11329 case OMPD_target_parallel_for_simd:
11330 case OMPD_target_parallel_for:
11331 case OMPD_task:
11332 case OMPD_taskloop:
11333 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011334 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011335 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011336 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011337 case OMPD_parallel_master_taskloop_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011338 case OMPD_target_data:
11339 case OMPD_target_enter_data:
11340 case OMPD_target_exit_data:
11341 case OMPD_target_update:
11342 case OMPD_teams:
11343 case OMPD_target:
11344 case OMPD_target_simd:
11345 case OMPD_target_parallel:
11346 case OMPD_cancel:
11347 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011348 case OMPD_parallel_master:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011349 case OMPD_parallel_sections:
11350 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011351 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011352 case OMPD_taskyield:
11353 case OMPD_barrier:
11354 case OMPD_taskwait:
11355 case OMPD_cancellation_point:
11356 case OMPD_flush:
11357 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011358 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011359 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011360 case OMPD_declare_variant:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011361 case OMPD_declare_target:
11362 case OMPD_end_declare_target:
11363 case OMPD_simd:
11364 case OMPD_for:
11365 case OMPD_for_simd:
11366 case OMPD_sections:
11367 case OMPD_section:
11368 case OMPD_single:
11369 case OMPD_master:
11370 case OMPD_critical:
11371 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011372 case OMPD_ordered:
11373 case OMPD_atomic:
11374 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +000011375 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +000011376 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
11377 case OMPD_unknown:
11378 llvm_unreachable("Unknown OpenMP directive");
11379 }
11380 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011381 case OMPC_device:
11382 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011383 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +000011384 case OMPD_target_enter_data:
11385 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +000011386 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +000011387 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +000011388 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +000011389 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +000011390 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +000011391 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +000011392 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +000011393 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +000011394 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +000011395 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +000011396 CaptureRegion = OMPD_task;
11397 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +000011398 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011399 // Do not capture device-clause expressions.
11400 break;
11401 case OMPD_teams_distribute_parallel_for:
11402 case OMPD_teams_distribute_parallel_for_simd:
11403 case OMPD_teams:
11404 case OMPD_teams_distribute:
11405 case OMPD_teams_distribute_simd:
11406 case OMPD_distribute_parallel_for:
11407 case OMPD_distribute_parallel_for_simd:
11408 case OMPD_task:
11409 case OMPD_taskloop:
11410 case OMPD_taskloop_simd:
Alexey Bataev60e51c42019-10-10 20:13:02 +000011411 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011412 case OMPD_master_taskloop_simd:
Alexey Bataev5bbcead2019-10-14 17:17:41 +000011413 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011414 case OMPD_parallel_master_taskloop_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011415 case OMPD_cancel:
11416 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011417 case OMPD_parallel_master:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011418 case OMPD_parallel_sections:
11419 case OMPD_parallel_for:
11420 case OMPD_parallel_for_simd:
11421 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011422 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011423 case OMPD_taskyield:
11424 case OMPD_barrier:
11425 case OMPD_taskwait:
11426 case OMPD_cancellation_point:
11427 case OMPD_flush:
11428 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +000011429 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011430 case OMPD_declare_simd:
Alexey Bataevd158cf62019-09-13 20:18:17 +000011431 case OMPD_declare_variant:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011432 case OMPD_declare_target:
11433 case OMPD_end_declare_target:
11434 case OMPD_simd:
11435 case OMPD_for:
11436 case OMPD_for_simd:
11437 case OMPD_sections:
11438 case OMPD_section:
11439 case OMPD_single:
11440 case OMPD_master:
11441 case OMPD_critical:
11442 case OMPD_taskgroup:
11443 case OMPD_distribute:
11444 case OMPD_ordered:
11445 case OMPD_atomic:
11446 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +000011447 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +000011448 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
11449 case OMPD_unknown:
11450 llvm_unreachable("Unknown OpenMP directive");
11451 }
11452 break;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011453 case OMPC_grainsize:
Alexey Bataevd88c7de2019-10-14 20:44:34 +000011454 case OMPC_num_tasks:
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011455 case OMPC_final:
Alexey Bataev31ba4762019-10-16 18:09:37 +000011456 case OMPC_priority:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011457 switch (DKind) {
11458 case OMPD_task:
11459 case OMPD_taskloop:
11460 case OMPD_taskloop_simd:
11461 case OMPD_master_taskloop:
Alexey Bataevb8552ab2019-10-18 16:47:35 +000011462 case OMPD_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011463 break;
11464 case OMPD_parallel_master_taskloop:
Alexey Bataev14a388f2019-10-25 10:27:13 -040011465 case OMPD_parallel_master_taskloop_simd:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011466 CaptureRegion = OMPD_parallel;
11467 break;
11468 case OMPD_target_update:
11469 case OMPD_target_enter_data:
11470 case OMPD_target_exit_data:
11471 case OMPD_target:
11472 case OMPD_target_simd:
11473 case OMPD_target_teams:
11474 case OMPD_target_parallel:
11475 case OMPD_target_teams_distribute:
11476 case OMPD_target_teams_distribute_simd:
11477 case OMPD_target_parallel_for:
11478 case OMPD_target_parallel_for_simd:
11479 case OMPD_target_teams_distribute_parallel_for:
11480 case OMPD_target_teams_distribute_parallel_for_simd:
11481 case OMPD_target_data:
11482 case OMPD_teams_distribute_parallel_for:
11483 case OMPD_teams_distribute_parallel_for_simd:
11484 case OMPD_teams:
11485 case OMPD_teams_distribute:
11486 case OMPD_teams_distribute_simd:
11487 case OMPD_distribute_parallel_for:
11488 case OMPD_distribute_parallel_for_simd:
11489 case OMPD_cancel:
11490 case OMPD_parallel:
cchen47d60942019-12-05 13:43:48 -050011491 case OMPD_parallel_master:
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011492 case OMPD_parallel_sections:
11493 case OMPD_parallel_for:
11494 case OMPD_parallel_for_simd:
11495 case OMPD_threadprivate:
11496 case OMPD_allocate:
11497 case OMPD_taskyield:
11498 case OMPD_barrier:
11499 case OMPD_taskwait:
11500 case OMPD_cancellation_point:
11501 case OMPD_flush:
11502 case OMPD_declare_reduction:
11503 case OMPD_declare_mapper:
11504 case OMPD_declare_simd:
11505 case OMPD_declare_variant:
11506 case OMPD_declare_target:
11507 case OMPD_end_declare_target:
11508 case OMPD_simd:
11509 case OMPD_for:
11510 case OMPD_for_simd:
11511 case OMPD_sections:
11512 case OMPD_section:
11513 case OMPD_single:
11514 case OMPD_master:
11515 case OMPD_critical:
11516 case OMPD_taskgroup:
11517 case OMPD_distribute:
11518 case OMPD_ordered:
11519 case OMPD_atomic:
11520 case OMPD_distribute_simd:
11521 case OMPD_requires:
11522 llvm_unreachable("Unexpected OpenMP directive with grainsize-clause");
11523 case OMPD_unknown:
11524 llvm_unreachable("Unknown OpenMP directive");
11525 }
11526 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011527 case OMPC_firstprivate:
11528 case OMPC_lastprivate:
11529 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011530 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011531 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011532 case OMPC_linear:
11533 case OMPC_default:
11534 case OMPC_proc_bind:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011535 case OMPC_safelen:
11536 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011537 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011538 case OMPC_collapse:
11539 case OMPC_private:
11540 case OMPC_shared:
11541 case OMPC_aligned:
11542 case OMPC_copyin:
11543 case OMPC_copyprivate:
11544 case OMPC_ordered:
11545 case OMPC_nowait:
11546 case OMPC_untied:
11547 case OMPC_mergeable:
11548 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011549 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011550 case OMPC_flush:
11551 case OMPC_read:
11552 case OMPC_write:
11553 case OMPC_update:
11554 case OMPC_capture:
11555 case OMPC_seq_cst:
11556 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011557 case OMPC_threads:
11558 case OMPC_simd:
11559 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011560 case OMPC_nogroup:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011561 case OMPC_hint:
11562 case OMPC_defaultmap:
11563 case OMPC_unknown:
11564 case OMPC_uniform:
11565 case OMPC_to:
11566 case OMPC_from:
11567 case OMPC_use_device_ptr:
11568 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011569 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011570 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000011571 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000011572 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011573 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000011574 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000011575 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050011576 case OMPC_nontemporal:
Alexey Bataevcb8e6912020-01-31 16:09:26 -050011577 case OMPC_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011578 llvm_unreachable("Unexpected OpenMP clause.");
11579 }
11580 return CaptureRegion;
11581}
11582
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011583OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
11584 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011585 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011586 SourceLocation NameModifierLoc,
11587 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011588 SourceLocation EndLoc) {
11589 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011590 Stmt *HelperValStmt = nullptr;
11591 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011592 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11593 !Condition->isInstantiationDependent() &&
11594 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011595 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011596 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011597 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011598
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011599 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011600
11601 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011602 CaptureRegion = getOpenMPCaptureRegionForClause(
11603 DKind, OMPC_if, LangOpts.OpenMP, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011604 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011605 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011606 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011607 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11608 HelperValStmt = buildPreInits(Context, Captures);
11609 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011610 }
11611
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +000011612 return new (Context)
11613 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
11614 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011615}
11616
Alexey Bataev3778b602014-07-17 07:32:53 +000011617OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
11618 SourceLocation StartLoc,
11619 SourceLocation LParenLoc,
11620 SourceLocation EndLoc) {
11621 Expr *ValExpr = Condition;
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011622 Stmt *HelperValStmt = nullptr;
11623 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev3778b602014-07-17 07:32:53 +000011624 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
11625 !Condition->isInstantiationDependent() &&
11626 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +000011627 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +000011628 if (Val.isInvalid())
11629 return nullptr;
11630
Richard Smith03a4aa32016-06-23 19:02:52 +000011631 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011632
11633 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050011634 CaptureRegion =
11635 getOpenMPCaptureRegionForClause(DKind, OMPC_final, LangOpts.OpenMP);
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011636 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
11637 ValExpr = MakeFullExpr(ValExpr).get();
11638 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11639 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11640 HelperValStmt = buildPreInits(Context, Captures);
11641 }
Alexey Bataev3778b602014-07-17 07:32:53 +000011642 }
11643
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011644 return new (Context) OMPFinalClause(ValExpr, HelperValStmt, CaptureRegion,
11645 StartLoc, LParenLoc, EndLoc);
Alexey Bataev3778b602014-07-17 07:32:53 +000011646}
Alexey Bataev3a842ec2019-10-15 19:37:05 +000011647
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011648ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
11649 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +000011650 if (!Op)
11651 return ExprError();
11652
11653 class IntConvertDiagnoser : public ICEConvertDiagnoser {
11654 public:
11655 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +000011656 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +000011657 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
11658 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011659 return S.Diag(Loc, diag::err_omp_not_integral) << T;
11660 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011661 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
11662 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011663 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
11664 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011665 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
11666 QualType T,
11667 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011668 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
11669 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011670 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
11671 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011672 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011673 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011674 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011675 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
11676 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011677 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
11678 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011679 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
11680 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011681 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +000011682 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +000011683 }
Alexey Bataeved09d242014-05-28 05:53:51 +000011684 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
11685 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +000011686 llvm_unreachable("conversion functions are permitted");
11687 }
11688 } ConvertDiagnoser;
11689 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
11690}
11691
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011692static bool
11693isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef, OpenMPClauseKind CKind,
11694 bool StrictlyPositive, bool BuildCapture = false,
11695 OpenMPDirectiveKind DKind = OMPD_unknown,
11696 OpenMPDirectiveKind *CaptureRegion = nullptr,
11697 Stmt **HelperValStmt = nullptr) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011698 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
11699 !ValExpr->isInstantiationDependent()) {
11700 SourceLocation Loc = ValExpr->getExprLoc();
11701 ExprResult Value =
11702 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
11703 if (Value.isInvalid())
11704 return false;
11705
11706 ValExpr = Value.get();
11707 // The expression must evaluate to a non-negative integer value.
11708 llvm::APSInt Result;
11709 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +000011710 Result.isSigned() &&
11711 !((!StrictlyPositive && Result.isNonNegative()) ||
11712 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011713 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000011714 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11715 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011716 return false;
11717 }
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011718 if (!BuildCapture)
11719 return true;
Alexey Bataev61205822019-12-04 09:50:21 -050011720 *CaptureRegion =
11721 getOpenMPCaptureRegionForClause(DKind, CKind, SemaRef.LangOpts.OpenMP);
Alexey Bataevb9c55e22019-10-14 19:29:52 +000011722 if (*CaptureRegion != OMPD_unknown &&
11723 !SemaRef.CurContext->isDependentContext()) {
11724 ValExpr = SemaRef.MakeFullExpr(ValExpr).get();
11725 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
11726 ValExpr = tryBuildCapture(SemaRef, ValExpr, Captures).get();
11727 *HelperValStmt = buildPreInits(SemaRef.Context, Captures);
11728 }
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011729 }
11730 return true;
11731}
11732
Alexey Bataev568a8332014-03-06 06:15:19 +000011733OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
11734 SourceLocation StartLoc,
11735 SourceLocation LParenLoc,
11736 SourceLocation EndLoc) {
11737 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011738 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011739
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011740 // OpenMP [2.5, Restrictions]
11741 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000011742 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +000011743 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011744 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +000011745
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011746 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011747 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050011748 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000011749 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011750 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011751 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +000011752 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11753 HelperValStmt = buildPreInits(Context, Captures);
11754 }
11755
11756 return new (Context) OMPNumThreadsClause(
11757 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +000011758}
11759
Alexey Bataev62c87d22014-03-21 04:51:18 +000011760ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011761 OpenMPClauseKind CKind,
11762 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011763 if (!E)
11764 return ExprError();
11765 if (E->isValueDependent() || E->isTypeDependent() ||
11766 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +000011767 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011768 llvm::APSInt Result;
11769 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
11770 if (ICE.isInvalid())
11771 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011772 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
11773 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +000011774 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011775 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
11776 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +000011777 return ExprError();
11778 }
Alexander Musman09184fe2014-09-30 05:29:28 +000011779 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
11780 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
11781 << E->getSourceRange();
11782 return ExprError();
11783 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011784 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
11785 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +000011786 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011787 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +000011788 return ICE;
11789}
11790
11791OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
11792 SourceLocation LParenLoc,
11793 SourceLocation EndLoc) {
11794 // OpenMP [2.8.1, simd construct, Description]
11795 // The parameter of the safelen clause must be a constant
11796 // positive integer expression.
11797 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
11798 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011799 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +000011800 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011801 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +000011802}
11803
Alexey Bataev66b15b52015-08-21 11:14:16 +000011804OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
11805 SourceLocation LParenLoc,
11806 SourceLocation EndLoc) {
11807 // OpenMP [2.8.1, simd construct, Description]
11808 // The parameter of the simdlen clause must be a constant
11809 // positive integer expression.
11810 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
11811 if (Simdlen.isInvalid())
11812 return nullptr;
11813 return new (Context)
11814 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
11815}
11816
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011817/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011818static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
11819 DSAStackTy *Stack) {
11820 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011821 if (!OMPAllocatorHandleT.isNull())
11822 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011823 // Build the predefined allocator expressions.
11824 bool ErrorFound = false;
11825 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
11826 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
11827 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
11828 StringRef Allocator =
11829 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
11830 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
11831 auto *VD = dyn_cast_or_null<ValueDecl>(
11832 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
11833 if (!VD) {
11834 ErrorFound = true;
11835 break;
11836 }
11837 QualType AllocatorType =
11838 VD->getType().getNonLValueExprType(S.getASTContext());
11839 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
11840 if (!Res.isUsable()) {
11841 ErrorFound = true;
11842 break;
11843 }
11844 if (OMPAllocatorHandleT.isNull())
11845 OMPAllocatorHandleT = AllocatorType;
11846 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
11847 ErrorFound = true;
11848 break;
11849 }
11850 Stack->setAllocator(AllocatorKind, Res.get());
11851 }
11852 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011853 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
11854 return false;
11855 }
Alexey Bataev27ef9512019-03-20 20:14:22 +000011856 OMPAllocatorHandleT.addConst();
11857 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011858 return true;
11859}
11860
11861OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
11862 SourceLocation LParenLoc,
11863 SourceLocation EndLoc) {
11864 // OpenMP [2.11.3, allocate Directive, Description]
11865 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +000011866 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011867 return nullptr;
11868
11869 ExprResult Allocator = DefaultLvalueConversion(A);
11870 if (Allocator.isInvalid())
11871 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +000011872 Allocator = PerformImplicitConversion(Allocator.get(),
11873 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011874 Sema::AA_Initializing,
11875 /*AllowExplicit=*/true);
11876 if (Allocator.isInvalid())
11877 return nullptr;
11878 return new (Context)
11879 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
11880}
11881
Alexander Musman64d33f12014-06-04 07:53:32 +000011882OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
11883 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +000011884 SourceLocation LParenLoc,
11885 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +000011886 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011887 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +000011888 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +000011889 // The parameter of the collapse clause must be a constant
11890 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +000011891 ExprResult NumForLoopsResult =
11892 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
11893 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +000011894 return nullptr;
11895 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +000011896 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +000011897}
11898
Alexey Bataev10e775f2015-07-30 11:36:16 +000011899OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
11900 SourceLocation EndLoc,
11901 SourceLocation LParenLoc,
11902 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +000011903 // OpenMP [2.7.1, loop construct, Description]
11904 // OpenMP [2.8.1, simd construct, Description]
11905 // OpenMP [2.9.6, distribute construct, Description]
11906 // The parameter of the ordered clause must be a constant
11907 // positive integer expression if any.
11908 if (NumForLoops && LParenLoc.isValid()) {
11909 ExprResult NumForLoopsResult =
11910 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
11911 if (NumForLoopsResult.isInvalid())
11912 return nullptr;
11913 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011914 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +000011915 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011916 }
Alexey Bataevf138fda2018-08-13 19:04:24 +000011917 auto *Clause = OMPOrderedClause::Create(
11918 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
11919 StartLoc, LParenLoc, EndLoc);
11920 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
11921 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +000011922}
11923
Alexey Bataeved09d242014-05-28 05:53:51 +000011924OMPClause *Sema::ActOnOpenMPSimpleClause(
11925 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
11926 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011927 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011928 switch (Kind) {
11929 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011930 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +000011931 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
11932 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011933 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011934 case OMPC_proc_bind:
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060011935 Res = ActOnOpenMPProcBindClause(static_cast<ProcBindKind>(Argument),
11936 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000011937 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000011938 case OMPC_atomic_default_mem_order:
11939 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
11940 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
11941 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
11942 break;
Alexey Bataevcb8e6912020-01-31 16:09:26 -050011943 case OMPC_order:
11944 Res = ActOnOpenMPOrderClause(static_cast<OpenMPOrderClauseKind>(Argument),
11945 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
11946 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000011947 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000011948 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000011949 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000011950 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000011951 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000011952 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000011953 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +000011954 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011955 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +000011956 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +000011957 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +000011958 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +000011959 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000011960 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000011961 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +000011962 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011963 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011964 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000011965 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000011966 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000011967 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000011968 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000011969 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011970 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000011971 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000011972 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000011973 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000011974 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000011975 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000011976 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000011977 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011978 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000011979 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000011980 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000011981 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000011982 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000011983 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011984 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000011985 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000011986 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000011987 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000011988 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000011989 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000011990 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000011991 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000011992 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000011993 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000011994 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000011995 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000011996 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000011997 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000011998 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000011999 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012000 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012001 case OMPC_dynamic_allocators:
Alexey Bataev729e2422019-08-23 16:11:14 +000012002 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012003 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050012004 case OMPC_nontemporal:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012005 llvm_unreachable("Clause is not allowed.");
12006 }
12007 return Res;
12008}
12009
Alexey Bataev6402bca2015-12-28 07:25:51 +000012010static std::string
12011getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
12012 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012013 SmallString<256> Buffer;
12014 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +000012015 unsigned Skipped = Exclude.size();
12016 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +000012017 for (unsigned I = First; I < Last; ++I) {
12018 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000012019 --Skipped;
12020 continue;
12021 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012022 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
Alexey Bataev87a004d2020-01-02 09:26:32 -050012023 if (I + Skipped + 2 == Last)
Alexey Bataeve3727102018-04-18 15:57:46 +000012024 Out << " or ";
Alexey Bataev87a004d2020-01-02 09:26:32 -050012025 else if (I + Skipped + 1 != Last)
Alexey Bataeve3727102018-04-18 15:57:46 +000012026 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +000012027 }
Benjamin Krameradcd0262020-01-28 20:23:46 +010012028 return std::string(Out.str());
Alexey Bataev6402bca2015-12-28 07:25:51 +000012029}
12030
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012031OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
12032 SourceLocation KindKwLoc,
12033 SourceLocation StartLoc,
12034 SourceLocation LParenLoc,
12035 SourceLocation EndLoc) {
12036 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +000012037 static_assert(OMPC_DEFAULT_unknown > 0,
12038 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012039 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012040 << getListOfPossibleValues(OMPC_default, /*First=*/0,
12041 /*Last=*/OMPC_DEFAULT_unknown)
12042 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012043 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012044 }
Alexey Bataev758e55e2013-09-06 18:03:48 +000012045 switch (Kind) {
12046 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012047 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012048 break;
12049 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012050 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012051 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012052 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012053 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000012054 break;
12055 }
Alexey Bataeved09d242014-05-28 05:53:51 +000012056 return new (Context)
12057 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012058}
12059
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012060OMPClause *Sema::ActOnOpenMPProcBindClause(ProcBindKind Kind,
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012061 SourceLocation KindKwLoc,
12062 SourceLocation StartLoc,
12063 SourceLocation LParenLoc,
12064 SourceLocation EndLoc) {
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012065 if (Kind == OMP_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012066 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Johannes Doerfert6c5d1f402019-12-25 18:15:36 -060012067 << getListOfPossibleValues(OMPC_proc_bind,
12068 /*First=*/unsigned(OMP_PROC_BIND_master),
12069 /*Last=*/5)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012070 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012071 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012072 }
Alexey Bataeved09d242014-05-28 05:53:51 +000012073 return new (Context)
12074 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012075}
12076
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012077OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
12078 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
12079 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
12080 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
12081 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12082 << getListOfPossibleValues(
12083 OMPC_atomic_default_mem_order, /*First=*/0,
12084 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
12085 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
12086 return nullptr;
12087 }
12088 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
12089 LParenLoc, EndLoc);
12090}
12091
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012092OMPClause *Sema::ActOnOpenMPOrderClause(OpenMPOrderClauseKind Kind,
12093 SourceLocation KindKwLoc,
12094 SourceLocation StartLoc,
12095 SourceLocation LParenLoc,
12096 SourceLocation EndLoc) {
12097 if (Kind == OMPC_ORDER_unknown) {
12098 static_assert(OMPC_ORDER_unknown > 0,
12099 "OMPC_ORDER_unknown not greater than 0");
12100 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
12101 << getListOfPossibleValues(OMPC_order, /*First=*/0,
12102 /*Last=*/OMPC_ORDER_unknown)
12103 << getOpenMPClauseName(OMPC_order);
12104 return nullptr;
12105 }
12106 return new (Context)
12107 OMPOrderClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
12108}
12109
Alexey Bataev56dafe82014-06-20 07:16:17 +000012110OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012111 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012112 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000012113 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012114 SourceLocation EndLoc) {
12115 OMPClause *Res = nullptr;
12116 switch (Kind) {
12117 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000012118 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
12119 assert(Argument.size() == NumberOfElements &&
12120 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012121 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012122 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
12123 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
12124 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
12125 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
12126 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012127 break;
12128 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000012129 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
12130 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
12131 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
12132 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000012133 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012134 case OMPC_dist_schedule:
12135 Res = ActOnOpenMPDistScheduleClause(
12136 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
12137 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
12138 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012139 case OMPC_defaultmap:
12140 enum { Modifier, DefaultmapKind };
12141 Res = ActOnOpenMPDefaultmapClause(
12142 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
12143 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000012144 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
12145 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012146 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000012147 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012148 case OMPC_num_threads:
12149 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012150 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012151 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012152 case OMPC_collapse:
12153 case OMPC_default:
12154 case OMPC_proc_bind:
12155 case OMPC_private:
12156 case OMPC_firstprivate:
12157 case OMPC_lastprivate:
12158 case OMPC_shared:
12159 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012160 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012161 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012162 case OMPC_linear:
12163 case OMPC_aligned:
12164 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012165 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012166 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012167 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012168 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012169 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012170 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012171 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012172 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012173 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012174 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012175 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012176 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012177 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012178 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012179 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012180 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012181 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012182 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012183 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012184 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012185 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012186 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012187 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012188 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012189 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012190 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012191 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012192 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012193 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012194 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012195 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000012196 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012197 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012198 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012199 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012200 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012201 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012202 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050012203 case OMPC_nontemporal:
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012204 case OMPC_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012205 llvm_unreachable("Clause is not allowed.");
12206 }
12207 return Res;
12208}
12209
Alexey Bataev6402bca2015-12-28 07:25:51 +000012210static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
12211 OpenMPScheduleClauseModifier M2,
12212 SourceLocation M1Loc, SourceLocation M2Loc) {
12213 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
12214 SmallVector<unsigned, 2> Excluded;
12215 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
12216 Excluded.push_back(M2);
12217 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
12218 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
12219 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
12220 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
12221 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
12222 << getListOfPossibleValues(OMPC_schedule,
12223 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
12224 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
12225 Excluded)
12226 << getOpenMPClauseName(OMPC_schedule);
12227 return true;
12228 }
12229 return false;
12230}
12231
Alexey Bataev56dafe82014-06-20 07:16:17 +000012232OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000012233 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000012234 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000012235 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
12236 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
12237 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
12238 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
12239 return nullptr;
12240 // OpenMP, 2.7.1, Loop Construct, Restrictions
12241 // Either the monotonic modifier or the nonmonotonic modifier can be specified
12242 // but not both.
12243 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
12244 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
12245 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
12246 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
12247 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
12248 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
12249 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
12250 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
12251 return nullptr;
12252 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000012253 if (Kind == OMPC_SCHEDULE_unknown) {
12254 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000012255 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
12256 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
12257 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
12258 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
12259 Exclude);
12260 } else {
12261 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
12262 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012263 }
12264 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12265 << Values << getOpenMPClauseName(OMPC_schedule);
12266 return nullptr;
12267 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000012268 // OpenMP, 2.7.1, Loop Construct, Restrictions
12269 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
12270 // schedule(guided).
12271 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
12272 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
12273 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
12274 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
12275 diag::err_omp_schedule_nonmonotonic_static);
12276 return nullptr;
12277 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000012278 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012279 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000012280 if (ChunkSize) {
12281 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12282 !ChunkSize->isInstantiationDependent() &&
12283 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012284 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000012285 ExprResult Val =
12286 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12287 if (Val.isInvalid())
12288 return nullptr;
12289
12290 ValExpr = Val.get();
12291
12292 // OpenMP [2.7.1, Restrictions]
12293 // chunk_size must be a loop invariant integer expression with a positive
12294 // value.
12295 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000012296 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12297 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12298 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000012299 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000012300 return nullptr;
12301 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012302 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050012303 DSAStack->getCurrentDirective(), OMPC_schedule,
12304 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012305 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012306 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012307 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000012308 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12309 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012310 }
12311 }
12312 }
12313
Alexey Bataev6402bca2015-12-28 07:25:51 +000012314 return new (Context)
12315 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000012316 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000012317}
12318
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012319OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
12320 SourceLocation StartLoc,
12321 SourceLocation EndLoc) {
12322 OMPClause *Res = nullptr;
12323 switch (Kind) {
12324 case OMPC_ordered:
12325 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
12326 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000012327 case OMPC_nowait:
12328 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
12329 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012330 case OMPC_untied:
12331 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
12332 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012333 case OMPC_mergeable:
12334 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
12335 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012336 case OMPC_read:
12337 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
12338 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000012339 case OMPC_write:
12340 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
12341 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000012342 case OMPC_update:
12343 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
12344 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000012345 case OMPC_capture:
12346 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
12347 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012348 case OMPC_seq_cst:
12349 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
12350 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000012351 case OMPC_threads:
12352 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
12353 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012354 case OMPC_simd:
12355 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
12356 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000012357 case OMPC_nogroup:
12358 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
12359 break;
Kelvin Li1408f912018-09-26 04:28:39 +000012360 case OMPC_unified_address:
12361 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
12362 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000012363 case OMPC_unified_shared_memory:
12364 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12365 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012366 case OMPC_reverse_offload:
12367 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
12368 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012369 case OMPC_dynamic_allocators:
12370 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
12371 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012372 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012373 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012374 case OMPC_num_threads:
12375 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012376 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012377 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012378 case OMPC_collapse:
12379 case OMPC_schedule:
12380 case OMPC_private:
12381 case OMPC_firstprivate:
12382 case OMPC_lastprivate:
12383 case OMPC_shared:
12384 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000012385 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000012386 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012387 case OMPC_linear:
12388 case OMPC_aligned:
12389 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000012390 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012391 case OMPC_default:
12392 case OMPC_proc_bind:
12393 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000012394 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000012395 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012396 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000012397 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000012398 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012399 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012400 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012401 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012402 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000012403 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012404 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012405 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012406 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012407 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012408 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000012409 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000012410 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000012411 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000012412 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012413 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012414 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012415 case OMPC_match:
Alexey Bataevb6e70842019-12-16 15:54:17 -050012416 case OMPC_nontemporal:
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012417 case OMPC_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012418 llvm_unreachable("Clause is not allowed.");
12419 }
12420 return Res;
12421}
12422
Alexey Bataev236070f2014-06-20 11:19:47 +000012423OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
12424 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000012425 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000012426 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
12427}
12428
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012429OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
12430 SourceLocation EndLoc) {
12431 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
12432}
12433
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012434OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
12435 SourceLocation EndLoc) {
12436 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
12437}
12438
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012439OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
12440 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012441 return new (Context) OMPReadClause(StartLoc, EndLoc);
12442}
12443
Alexey Bataevdea47612014-07-23 07:46:59 +000012444OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
12445 SourceLocation EndLoc) {
12446 return new (Context) OMPWriteClause(StartLoc, EndLoc);
12447}
12448
Alexey Bataev67a4f222014-07-23 10:25:33 +000012449OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
12450 SourceLocation EndLoc) {
12451 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
12452}
12453
Alexey Bataev459dec02014-07-24 06:46:57 +000012454OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
12455 SourceLocation EndLoc) {
12456 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
12457}
12458
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012459OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
12460 SourceLocation EndLoc) {
12461 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
12462}
12463
Alexey Bataev346265e2015-09-25 10:37:12 +000012464OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
12465 SourceLocation EndLoc) {
12466 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
12467}
12468
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012469OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
12470 SourceLocation EndLoc) {
12471 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
12472}
12473
Alexey Bataevb825de12015-12-07 10:51:44 +000012474OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
12475 SourceLocation EndLoc) {
12476 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
12477}
12478
Kelvin Li1408f912018-09-26 04:28:39 +000012479OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
12480 SourceLocation EndLoc) {
12481 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
12482}
12483
Patrick Lyster4a370b92018-10-01 13:47:43 +000012484OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
12485 SourceLocation EndLoc) {
12486 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
12487}
12488
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012489OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
12490 SourceLocation EndLoc) {
12491 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
12492}
12493
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012494OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
12495 SourceLocation EndLoc) {
12496 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
12497}
12498
Alexey Bataevc5e02582014-06-16 07:08:35 +000012499OMPClause *Sema::ActOnOpenMPVarListClause(
12500 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012501 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
12502 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012503 DeclarationNameInfo &ReductionOrMapperId, int ExtraModifier,
Kelvin Lief579432018-12-18 22:18:41 +000012504 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012505 ArrayRef<SourceLocation> MapTypeModifiersLoc, bool IsMapTypeImplicit,
12506 SourceLocation DepLinMapLastLoc) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000012507 SourceLocation StartLoc = Locs.StartLoc;
12508 SourceLocation LParenLoc = Locs.LParenLoc;
12509 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012510 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012511 switch (Kind) {
12512 case OMPC_private:
12513 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12514 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012515 case OMPC_firstprivate:
12516 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12517 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000012518 case OMPC_lastprivate:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012519 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LASTPRIVATE_unknown &&
12520 "Unexpected lastprivate modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012521 Res = ActOnOpenMPLastprivateClause(
12522 VarList, static_cast<OpenMPLastprivateModifier>(ExtraModifier),
12523 DepLinMapLastLoc, ColonLoc, StartLoc, LParenLoc, EndLoc);
Alexander Musman1bb328c2014-06-04 13:06:39 +000012524 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000012525 case OMPC_shared:
12526 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
12527 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012528 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000012529 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012530 EndLoc, ReductionOrMapperIdScopeSpec,
12531 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012532 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000012533 case OMPC_task_reduction:
12534 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000012535 EndLoc, ReductionOrMapperIdScopeSpec,
12536 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000012537 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000012538 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012539 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
12540 EndLoc, ReductionOrMapperIdScopeSpec,
12541 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000012542 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000012543 case OMPC_linear:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012544 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_LINEAR_unknown &&
12545 "Unexpected linear modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012546 Res = ActOnOpenMPLinearClause(
12547 VarList, TailExpr, StartLoc, LParenLoc,
12548 static_cast<OpenMPLinearClauseKind>(ExtraModifier), DepLinMapLastLoc,
12549 ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000012550 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012551 case OMPC_aligned:
12552 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
12553 ColonLoc, EndLoc);
12554 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012555 case OMPC_copyin:
12556 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
12557 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012558 case OMPC_copyprivate:
12559 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
12560 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000012561 case OMPC_flush:
12562 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
12563 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012564 case OMPC_depend:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012565 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_DEPEND_unknown &&
12566 "Unexpected depend modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012567 Res = ActOnOpenMPDependClause(
12568 static_cast<OpenMPDependClauseKind>(ExtraModifier), DepLinMapLastLoc,
12569 ColonLoc, VarList, StartLoc, LParenLoc, EndLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012570 break;
12571 case OMPC_map:
Alexey Bataev3732f4e2019-12-24 16:02:58 -050012572 assert(0 <= ExtraModifier && ExtraModifier <= OMPC_MAP_unknown &&
12573 "Unexpected map modifier.");
Alexey Bataev93dc40d2019-12-20 11:04:57 -050012574 Res = ActOnOpenMPMapClause(
12575 MapTypeModifiers, MapTypeModifiersLoc, ReductionOrMapperIdScopeSpec,
12576 ReductionOrMapperId, static_cast<OpenMPMapClauseKind>(ExtraModifier),
12577 IsMapTypeImplicit, DepLinMapLastLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012578 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012579 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000012580 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
12581 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000012582 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000012583 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000012584 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
12585 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000012586 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000012587 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012588 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012589 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000012590 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000012591 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000012592 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000012593 case OMPC_allocate:
12594 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
12595 ColonLoc, EndLoc);
12596 break;
Alexey Bataevb6e70842019-12-16 15:54:17 -050012597 case OMPC_nontemporal:
12598 Res = ActOnOpenMPNontemporalClause(VarList, StartLoc, LParenLoc, EndLoc);
12599 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000012600 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000012601 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000012602 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000012603 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000012604 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000012605 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000012606 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012607 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000012608 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000012609 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000012610 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000012611 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000012612 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000012613 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012614 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000012615 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000012616 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000012617 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000012618 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000012619 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000012620 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000012621 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000012622 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000012623 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012624 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000012625 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012626 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000012627 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000012628 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000012629 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000012630 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012631 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012632 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000012633 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000012634 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000012635 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000012636 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000012637 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000012638 case OMPC_atomic_default_mem_order:
Alexey Bataev729e2422019-08-23 16:11:14 +000012639 case OMPC_device_type:
Alexey Bataevdba792c2019-09-23 18:13:31 +000012640 case OMPC_match:
Alexey Bataevcb8e6912020-01-31 16:09:26 -050012641 case OMPC_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012642 llvm_unreachable("Clause is not allowed.");
12643 }
12644 return Res;
12645}
12646
Alexey Bataev90c228f2016-02-08 09:29:13 +000012647ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000012648 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000012649 ExprResult Res = BuildDeclRefExpr(
12650 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
12651 if (!Res.isUsable())
12652 return ExprError();
12653 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
12654 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
12655 if (!Res.isUsable())
12656 return ExprError();
12657 }
12658 if (VK != VK_LValue && Res.get()->isGLValue()) {
12659 Res = DefaultLvalueConversion(Res.get());
12660 if (!Res.isUsable())
12661 return ExprError();
12662 }
12663 return Res;
12664}
12665
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012666OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
12667 SourceLocation StartLoc,
12668 SourceLocation LParenLoc,
12669 SourceLocation EndLoc) {
12670 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000012671 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000012672 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012673 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012674 SourceLocation ELoc;
12675 SourceRange ERange;
12676 Expr *SimpleRefExpr = RefExpr;
12677 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012678 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012679 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012680 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012681 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012682 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012683 ValueDecl *D = Res.first;
12684 if (!D)
12685 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012686
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012687 QualType Type = D->getType();
12688 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012689
12690 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12691 // A variable that appears in a private clause must not have an incomplete
12692 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012693 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012694 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012695 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012696
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012697 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12698 // A variable that is privatized must not have a const-qualified type
12699 // unless it is of class type with a mutable member. This restriction does
12700 // not apply to the firstprivate clause.
12701 //
12702 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
12703 // A variable that appears in a private clause must not have a
12704 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000012705 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000012706 continue;
12707
Alexey Bataev758e55e2013-09-06 18:03:48 +000012708 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12709 // in a Construct]
12710 // Variables with the predetermined data-sharing attributes may not be
12711 // listed in data-sharing attributes clauses, except for the cases
12712 // listed below. For these exceptions only, listing a predetermined
12713 // variable in a data-sharing attribute clause is allowed and overrides
12714 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000012715 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012716 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012717 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12718 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000012719 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000012720 continue;
12721 }
12722
Alexey Bataeve3727102018-04-18 15:57:46 +000012723 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012724 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012725 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000012726 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012727 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
12728 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000012729 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012730 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012731 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012732 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012733 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012734 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012735 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012736 continue;
12737 }
12738
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012739 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12740 // A list item cannot appear in both a map clause and a data-sharing
12741 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012742 //
12743 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12744 // A list item cannot appear in both a map clause and a data-sharing
12745 // attribute clause on the same construct unless the construct is a
12746 // combined construct.
12747 if ((LangOpts.OpenMP <= 45 && isOpenMPTargetExecutionDirective(CurrDir)) ||
12748 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012749 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012750 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012751 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000012752 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
12753 OpenMPClauseKind WhereFoundClauseKind) -> bool {
12754 ConflictKind = WhereFoundClauseKind;
12755 return true;
12756 })) {
12757 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012758 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000012759 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000012760 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000012761 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012762 continue;
12763 }
12764 }
12765
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012766 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
12767 // A variable of class type (or array thereof) that appears in a private
12768 // clause requires an accessible, unambiguous default constructor for the
12769 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000012770 // Generate helper private variable and initialize it with the default
12771 // value. The address of the original variable is replaced by the address of
12772 // the new private variable in CodeGen. This new variable is not added to
12773 // IdResolver, so the code in the OpenMP region uses original variable for
12774 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012775 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012776 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012777 buildVarDecl(*this, ELoc, Type, D->getName(),
12778 D->hasAttrs() ? &D->getAttrs() : nullptr,
12779 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000012780 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012781 if (VDPrivate->isInvalidDecl())
12782 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000012783 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012784 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012785
Alexey Bataev90c228f2016-02-08 09:29:13 +000012786 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012787 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000012788 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000012789 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012790 Vars.push_back((VD || CurContext->isDependentContext())
12791 ? RefExpr->IgnoreParens()
12792 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000012793 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012794 }
12795
Alexey Bataeved09d242014-05-28 05:53:51 +000012796 if (Vars.empty())
12797 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012798
Alexey Bataev03b340a2014-10-21 03:16:40 +000012799 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12800 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000012801}
12802
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012803namespace {
12804class DiagsUninitializedSeveretyRAII {
12805private:
12806 DiagnosticsEngine &Diags;
12807 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000012808 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012809
12810public:
12811 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
12812 bool IsIgnored)
12813 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
12814 if (!IsIgnored) {
12815 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
12816 /*Map*/ diag::Severity::Ignored, Loc);
12817 }
12818 }
12819 ~DiagsUninitializedSeveretyRAII() {
12820 if (!IsIgnored)
12821 Diags.popMappings(SavedLoc);
12822 }
12823};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000012824}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012825
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012826OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
12827 SourceLocation StartLoc,
12828 SourceLocation LParenLoc,
12829 SourceLocation EndLoc) {
12830 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012831 SmallVector<Expr *, 8> PrivateCopies;
12832 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000012833 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012834 bool IsImplicitClause =
12835 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000012836 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012837
Alexey Bataeve3727102018-04-18 15:57:46 +000012838 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012839 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000012840 SourceLocation ELoc;
12841 SourceRange ERange;
12842 Expr *SimpleRefExpr = RefExpr;
12843 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000012844 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012845 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012846 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000012847 PrivateCopies.push_back(nullptr);
12848 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012849 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000012850 ValueDecl *D = Res.first;
12851 if (!D)
12852 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012853
Alexey Bataev60da77e2016-02-29 05:54:20 +000012854 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000012855 QualType Type = D->getType();
12856 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012857
12858 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
12859 // A variable that appears in a private clause must not have an incomplete
12860 // type or a reference type.
12861 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000012862 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012863 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012864 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012865
12866 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
12867 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000012868 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012869 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012870 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012871
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012872 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000012873 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012874 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012875 DSAStackTy::DSAVarData DVar =
12876 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000012877 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012878 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012879 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012880 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
12881 // A list item that specifies a given variable may not appear in more
12882 // than one clause on the same directive, except that a variable may be
12883 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012884 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
12885 // A list item may appear in a firstprivate or lastprivate clause but not
12886 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012887 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000012888 (isOpenMPDistributeDirective(CurrDir) ||
12889 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012890 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012891 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012892 << getOpenMPClauseName(DVar.CKind)
12893 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012894 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012895 continue;
12896 }
12897
12898 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12899 // in a Construct]
12900 // Variables with the predetermined data-sharing attributes may not be
12901 // listed in data-sharing attributes clauses, except for the cases
12902 // listed below. For these exceptions only, listing a predetermined
12903 // variable in a data-sharing attribute clause is allowed and overrides
12904 // the variable's predetermined data-sharing attributes.
12905 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
12906 // in a Construct, C/C++, p.2]
12907 // Variables with const-qualified type having no mutable member may be
12908 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000012909 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012910 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
12911 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000012912 << getOpenMPClauseName(DVar.CKind)
12913 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012914 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012915 continue;
12916 }
12917
12918 // OpenMP [2.9.3.4, Restrictions, p.2]
12919 // A list item that is private within a parallel region must not appear
12920 // in a firstprivate clause on a worksharing construct if any of the
12921 // worksharing regions arising from the worksharing construct ever bind
12922 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012923 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12924 // A list item that is private within a teams region must not appear in a
12925 // firstprivate clause on a distribute construct if any of the distribute
12926 // regions arising from the distribute construct ever bind to any of the
12927 // teams regions arising from the teams construct.
12928 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
12929 // A list item that appears in a reduction clause of a teams construct
12930 // must not appear in a firstprivate clause on a distribute construct if
12931 // any of the distribute regions arising from the distribute construct
12932 // ever bind to any of the teams regions arising from the teams construct.
12933 if ((isOpenMPWorksharingDirective(CurrDir) ||
12934 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000012935 !isOpenMPParallelDirective(CurrDir) &&
12936 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000012937 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012938 if (DVar.CKind != OMPC_shared &&
12939 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012940 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012941 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000012942 Diag(ELoc, diag::err_omp_required_access)
12943 << getOpenMPClauseName(OMPC_firstprivate)
12944 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000012945 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000012946 continue;
12947 }
12948 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000012949 // OpenMP [2.9.3.4, Restrictions, p.3]
12950 // A list item that appears in a reduction clause of a parallel construct
12951 // must not appear in a firstprivate clause on a worksharing or task
12952 // construct if any of the worksharing or task regions arising from the
12953 // worksharing or task construct ever bind to any of the parallel regions
12954 // arising from the parallel construct.
12955 // OpenMP [2.9.3.4, Restrictions, p.4]
12956 // A list item that appears in a reduction clause in worksharing
12957 // construct must not appear in a firstprivate clause in a task construct
12958 // encountered during execution of any of the worksharing regions arising
12959 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000012960 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012961 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000012962 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
12963 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012964 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012965 isOpenMPWorksharingDirective(K) ||
12966 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000012967 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012968 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012969 if (DVar.CKind == OMPC_reduction &&
12970 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000012971 isOpenMPWorksharingDirective(DVar.DKind) ||
12972 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012973 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
12974 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000012975 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000012976 continue;
12977 }
12978 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000012979
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012980 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12981 // A list item cannot appear in both a map clause and a data-sharing
12982 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000012983 //
12984 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
12985 // A list item cannot appear in both a map clause and a data-sharing
12986 // attribute clause on the same construct unless the construct is a
12987 // combined construct.
12988 if ((LangOpts.OpenMP <= 45 &&
12989 isOpenMPTargetExecutionDirective(CurrDir)) ||
12990 CurrDir == OMPD_target) {
Samuel Antao6890b092016-07-28 14:25:09 +000012991 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000012992 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000012993 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000012994 [&ConflictKind](
12995 OMPClauseMappableExprCommon::MappableExprComponentListRef,
12996 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000012997 ConflictKind = WhereFoundClauseKind;
12998 return true;
12999 })) {
13000 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013001 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000013002 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013003 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000013004 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013005 continue;
13006 }
13007 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013008 }
13009
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013010 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000013011 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000013012 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013013 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
13014 << getOpenMPClauseName(OMPC_firstprivate) << Type
13015 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13016 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000013017 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013018 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000013019 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013020 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000013021 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000013022 continue;
13023 }
13024
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013025 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013026 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013027 buildVarDecl(*this, ELoc, Type, D->getName(),
13028 D->hasAttrs() ? &D->getAttrs() : nullptr,
13029 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013030 // Generate helper private variable and initialize it with the value of the
13031 // original variable. The address of the original variable is replaced by
13032 // the address of the new private variable in the CodeGen. This new variable
13033 // is not added to IdResolver, so the code in the OpenMP region uses
13034 // original variable for proper diagnostics and variable capturing.
13035 Expr *VDInitRefExpr = nullptr;
13036 // For arrays generate initializer for single element and replace it by the
13037 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013038 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013039 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000013040 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013041 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000013042 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000013043 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013044 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
13045 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000013046 InitializedEntity Entity =
13047 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013048 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
13049
13050 InitializationSequence InitSeq(*this, Entity, Kind, Init);
13051 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
13052 if (Result.isInvalid())
13053 VDPrivate->setInvalidDecl();
13054 else
13055 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013056 // Remove temp variable declaration.
13057 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013058 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000013059 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
13060 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000013061 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
13062 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000013063 AddInitializerToDecl(VDPrivate,
13064 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000013065 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013066 }
13067 if (VDPrivate->isInvalidDecl()) {
13068 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000013069 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013070 diag::note_omp_task_predetermined_firstprivate_here);
13071 }
13072 continue;
13073 }
13074 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013075 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000013076 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
13077 RefExpr->getExprLoc());
13078 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013079 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013080 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013081 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000013082 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000013083 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000013084 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000013085 ExprCaptures.push_back(Ref->getDecl());
13086 }
Alexey Bataev417089f2016-02-17 13:19:37 +000013087 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000013088 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013089 Vars.push_back((VD || CurContext->isDependentContext())
13090 ? RefExpr->IgnoreParens()
13091 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000013092 PrivateCopies.push_back(VDPrivateRefExpr);
13093 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013094 }
13095
Alexey Bataeved09d242014-05-28 05:53:51 +000013096 if (Vars.empty())
13097 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013098
13099 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013100 Vars, PrivateCopies, Inits,
13101 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000013102}
13103
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013104OMPClause *Sema::ActOnOpenMPLastprivateClause(
13105 ArrayRef<Expr *> VarList, OpenMPLastprivateModifier LPKind,
13106 SourceLocation LPKindLoc, SourceLocation ColonLoc, SourceLocation StartLoc,
13107 SourceLocation LParenLoc, SourceLocation EndLoc) {
13108 if (LPKind == OMPC_LASTPRIVATE_unknown && LPKindLoc.isValid()) {
13109 assert(ColonLoc.isValid() && "Colon location must be valid.");
13110 Diag(LPKindLoc, diag::err_omp_unexpected_clause_value)
13111 << getListOfPossibleValues(OMPC_lastprivate, /*First=*/0,
13112 /*Last=*/OMPC_LASTPRIVATE_unknown)
13113 << getOpenMPClauseName(OMPC_lastprivate);
13114 return nullptr;
13115 }
13116
Alexander Musman1bb328c2014-06-04 13:06:39 +000013117 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000013118 SmallVector<Expr *, 8> SrcExprs;
13119 SmallVector<Expr *, 8> DstExprs;
13120 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000013121 SmallVector<Decl *, 4> ExprCaptures;
13122 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000013123 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000013124 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000013125 SourceLocation ELoc;
13126 SourceRange ERange;
13127 Expr *SimpleRefExpr = RefExpr;
13128 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000013129 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000013130 // It will be analyzed later.
13131 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000013132 SrcExprs.push_back(nullptr);
13133 DstExprs.push_back(nullptr);
13134 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013135 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000013136 ValueDecl *D = Res.first;
13137 if (!D)
13138 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000013139
Alexey Bataev74caaf22016-02-20 04:09:36 +000013140 QualType Type = D->getType();
13141 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013142
13143 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
13144 // A variable that appears in a lastprivate clause must not have an
13145 // incomplete type or a reference type.
13146 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000013147 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000013148 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000013149 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000013150
Joel E. Dennye6234d1422019-01-04 22:11:31 +000013151 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
13152 // A variable that is privatized must not have a const-qualified type
13153 // unless it is of class type with a mutable member. This restriction does
13154 // not apply to the firstprivate clause.
13155 //
13156 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
13157 // A variable that appears in a lastprivate clause must not have a
13158 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013159 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000013160 continue;
13161
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013162 // OpenMP 5.0 [2.19.4.5 lastprivate Clause, Restrictions]
13163 // A list item that appears in a lastprivate clause with the conditional
13164 // modifier must be a scalar variable.
13165 if (LPKind == OMPC_LASTPRIVATE_conditional && !Type->isScalarType()) {
13166 Diag(ELoc, diag::err_omp_lastprivate_conditional_non_scalar);
13167 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13168 VarDecl::DeclarationOnly;
13169 Diag(D->getLocation(),
13170 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
13171 << D;
13172 continue;
13173 }
13174
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013175 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000013176 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13177 // in a Construct]
13178 // Variables with the predetermined data-sharing attributes may not be
13179 // listed in data-sharing attributes clauses, except for the cases
13180 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013181 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
13182 // A list item may appear in a firstprivate or lastprivate clause but not
13183 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000013184 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013185 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000013186 (isOpenMPDistributeDirective(CurrDir) ||
13187 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000013188 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
13189 Diag(ELoc, diag::err_omp_wrong_dsa)
13190 << getOpenMPClauseName(DVar.CKind)
13191 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013192 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000013193 continue;
13194 }
13195
Alexey Bataevf29276e2014-06-18 04:14:57 +000013196 // OpenMP [2.14.3.5, Restrictions, p.2]
13197 // A list item that is private within a parallel region, or that appears in
13198 // the reduction clause of a parallel construct, must not appear in a
13199 // lastprivate clause on a worksharing construct if any of the corresponding
13200 // worksharing regions ever binds to any of the corresponding parallel
13201 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000013202 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000013203 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000013204 !isOpenMPParallelDirective(CurrDir) &&
13205 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000013206 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013207 if (DVar.CKind != OMPC_shared) {
13208 Diag(ELoc, diag::err_omp_required_access)
13209 << getOpenMPClauseName(OMPC_lastprivate)
13210 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013211 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000013212 continue;
13213 }
13214 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000013215
Alexander Musman1bb328c2014-06-04 13:06:39 +000013216 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000013217 // A variable of class type (or array thereof) that appears in a
13218 // lastprivate clause requires an accessible, unambiguous default
13219 // constructor for the class type, unless the list item is also specified
13220 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000013221 // A variable of class type (or array thereof) that appears in a
13222 // lastprivate clause requires an accessible, unambiguous copy assignment
13223 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000013224 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013225 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
13226 Type.getUnqualifiedType(), ".lastprivate.src",
13227 D->hasAttrs() ? &D->getAttrs() : nullptr);
13228 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000013229 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000013230 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000013231 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000013232 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000013233 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000013234 // For arrays generate assignment operation for single element and replace
13235 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000013236 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
13237 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000013238 if (AssignmentOp.isInvalid())
13239 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000013240 AssignmentOp =
13241 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000013242 if (AssignmentOp.isInvalid())
13243 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000013244
Alexey Bataev74caaf22016-02-20 04:09:36 +000013245 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013246 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013247 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013248 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000013249 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000013250 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000013251 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000013252 ExprCaptures.push_back(Ref->getDecl());
13253 }
13254 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013255 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000013256 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000013257 ExprResult RefRes = DefaultLvalueConversion(Ref);
13258 if (!RefRes.isUsable())
13259 continue;
13260 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000013261 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
13262 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000013263 if (!PostUpdateRes.isUsable())
13264 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000013265 ExprPostUpdates.push_back(
13266 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000013267 }
13268 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013269 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013270 Vars.push_back((VD || CurContext->isDependentContext())
13271 ? RefExpr->IgnoreParens()
13272 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000013273 SrcExprs.push_back(PseudoSrcExpr);
13274 DstExprs.push_back(PseudoDstExpr);
13275 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000013276 }
13277
13278 if (Vars.empty())
13279 return nullptr;
13280
13281 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000013282 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev93dc40d2019-12-20 11:04:57 -050013283 LPKind, LPKindLoc, ColonLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000013284 buildPreInits(Context, ExprCaptures),
13285 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000013286}
13287
Alexey Bataev758e55e2013-09-06 18:03:48 +000013288OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
13289 SourceLocation StartLoc,
13290 SourceLocation LParenLoc,
13291 SourceLocation EndLoc) {
13292 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000013293 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013294 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000013295 SourceLocation ELoc;
13296 SourceRange ERange;
13297 Expr *SimpleRefExpr = RefExpr;
13298 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013299 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000013300 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000013301 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013302 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013303 ValueDecl *D = Res.first;
13304 if (!D)
13305 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013306
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013307 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013308 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
13309 // in a Construct]
13310 // Variables with the predetermined data-sharing attributes may not be
13311 // listed in data-sharing attributes clauses, except for the cases
13312 // listed below. For these exceptions only, listing a predetermined
13313 // variable in a data-sharing attribute clause is allowed and overrides
13314 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000013315 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000013316 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
13317 DVar.RefExpr) {
13318 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
13319 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000013320 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013321 continue;
13322 }
13323
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013324 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013325 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000013326 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000013327 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000013328 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
13329 ? RefExpr->IgnoreParens()
13330 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000013331 }
13332
Alexey Bataeved09d242014-05-28 05:53:51 +000013333 if (Vars.empty())
13334 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000013335
13336 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
13337}
13338
Alexey Bataevc5e02582014-06-16 07:08:35 +000013339namespace {
13340class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
13341 DSAStackTy *Stack;
13342
13343public:
13344 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013345 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
13346 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013347 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
13348 return false;
13349 if (DVar.CKind != OMPC_unknown)
13350 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000013351 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000013352 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000013353 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000013354 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013355 }
13356 return false;
13357 }
13358 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013359 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013360 if (Child && Visit(Child))
13361 return true;
13362 }
13363 return false;
13364 }
Alexey Bataev23b69422014-06-18 07:08:49 +000013365 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000013366};
Alexey Bataev23b69422014-06-18 07:08:49 +000013367} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000013368
Alexey Bataev60da77e2016-02-29 05:54:20 +000013369namespace {
13370// Transform MemberExpression for specified FieldDecl of current class to
13371// DeclRefExpr to specified OMPCapturedExprDecl.
13372class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
13373 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000013374 ValueDecl *Field = nullptr;
13375 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013376
13377public:
13378 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
13379 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
13380
13381 ExprResult TransformMemberExpr(MemberExpr *E) {
13382 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
13383 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000013384 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000013385 return CapturedExpr;
13386 }
13387 return BaseTransform::TransformMemberExpr(E);
13388 }
13389 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
13390};
13391} // namespace
13392
Alexey Bataev97d18bf2018-04-11 19:21:00 +000013393template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000013394static T filterLookupForUDReductionAndMapper(
13395 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013396 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013397 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013398 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013399 return Res;
13400 }
13401 }
13402 return T();
13403}
13404
Alexey Bataev43b90b72018-09-12 16:31:59 +000013405static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
13406 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
13407
13408 for (auto RD : D->redecls()) {
13409 // Don't bother with extra checks if we already know this one isn't visible.
13410 if (RD == D)
13411 continue;
13412
13413 auto ND = cast<NamedDecl>(RD);
13414 if (LookupResult::isVisible(SemaRef, ND))
13415 return ND;
13416 }
13417
13418 return nullptr;
13419}
13420
13421static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000013422argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000013423 SourceLocation Loc, QualType Ty,
13424 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
13425 // Find all of the associated namespaces and classes based on the
13426 // arguments we have.
13427 Sema::AssociatedNamespaceSet AssociatedNamespaces;
13428 Sema::AssociatedClassSet AssociatedClasses;
13429 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
13430 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
13431 AssociatedClasses);
13432
13433 // C++ [basic.lookup.argdep]p3:
13434 // Let X be the lookup set produced by unqualified lookup (3.4.1)
13435 // and let Y be the lookup set produced by argument dependent
13436 // lookup (defined as follows). If X contains [...] then Y is
13437 // empty. Otherwise Y is the set of declarations found in the
13438 // namespaces associated with the argument types as described
13439 // below. The set of declarations found by the lookup of the name
13440 // is the union of X and Y.
13441 //
13442 // Here, we compute Y and add its members to the overloaded
13443 // candidate set.
13444 for (auto *NS : AssociatedNamespaces) {
13445 // When considering an associated namespace, the lookup is the
13446 // same as the lookup performed when the associated namespace is
13447 // used as a qualifier (3.4.3.2) except that:
13448 //
13449 // -- Any using-directives in the associated namespace are
13450 // ignored.
13451 //
13452 // -- Any namespace-scope friend functions declared in
13453 // associated classes are visible within their respective
13454 // namespaces even if they are not visible during an ordinary
13455 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000013456 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000013457 for (auto *D : R) {
13458 auto *Underlying = D;
13459 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13460 Underlying = USD->getTargetDecl();
13461
Michael Kruse4304e9d2019-02-19 16:38:20 +000013462 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
13463 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000013464 continue;
13465
13466 if (!SemaRef.isVisible(D)) {
13467 D = findAcceptableDecl(SemaRef, D);
13468 if (!D)
13469 continue;
13470 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
13471 Underlying = USD->getTargetDecl();
13472 }
13473 Lookups.emplace_back();
13474 Lookups.back().addDecl(Underlying);
13475 }
13476 }
13477}
13478
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013479static ExprResult
13480buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
13481 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
13482 const DeclarationNameInfo &ReductionId, QualType Ty,
13483 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
13484 if (ReductionIdScopeSpec.isInvalid())
13485 return ExprError();
13486 SmallVector<UnresolvedSet<8>, 4> Lookups;
13487 if (S) {
13488 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13489 Lookup.suppressDiagnostics();
13490 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013491 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013492 do {
13493 S = S->getParent();
13494 } while (S && !S->isDeclScope(D));
13495 if (S)
13496 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000013497 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013498 Lookups.back().append(Lookup.begin(), Lookup.end());
13499 Lookup.clear();
13500 }
13501 } else if (auto *ULE =
13502 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
13503 Lookups.push_back(UnresolvedSet<8>());
13504 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000013505 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013506 if (D == PrevD)
13507 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000013508 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013509 Lookups.back().addDecl(DRD);
13510 PrevD = D;
13511 }
13512 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000013513 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
13514 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013515 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000013516 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013517 return !D->isInvalidDecl() &&
13518 (D->getType()->isDependentType() ||
13519 D->getType()->isInstantiationDependentType() ||
13520 D->getType()->containsUnexpandedParameterPack());
13521 })) {
13522 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000013523 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000013524 if (Set.empty())
13525 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013526 ResSet.append(Set.begin(), Set.end());
13527 // The last item marks the end of all declarations at the specified scope.
13528 ResSet.addDecl(Set[Set.size() - 1]);
13529 }
13530 return UnresolvedLookupExpr::Create(
13531 SemaRef.Context, /*NamingClass=*/nullptr,
13532 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
13533 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
13534 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000013535 // Lookup inside the classes.
13536 // C++ [over.match.oper]p3:
13537 // For a unary operator @ with an operand of a type whose
13538 // cv-unqualified version is T1, and for a binary operator @ with
13539 // a left operand of a type whose cv-unqualified version is T1 and
13540 // a right operand of a type whose cv-unqualified version is T2,
13541 // three sets of candidate functions, designated member
13542 // candidates, non-member candidates and built-in candidates, are
13543 // constructed as follows:
13544 // -- If T1 is a complete class type or a class currently being
13545 // defined, the set of member candidates is the result of the
13546 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
13547 // the set of member candidates is empty.
13548 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
13549 Lookup.suppressDiagnostics();
13550 if (const auto *TyRec = Ty->getAs<RecordType>()) {
13551 // Complete the type if it can be completed.
13552 // If the type is neither complete nor being defined, bail out now.
13553 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
13554 TyRec->getDecl()->getDefinition()) {
13555 Lookup.clear();
13556 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
13557 if (Lookup.empty()) {
13558 Lookups.emplace_back();
13559 Lookups.back().append(Lookup.begin(), Lookup.end());
13560 }
13561 }
13562 }
13563 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000013564 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000013565 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000013566 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13567 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
13568 if (!D->isInvalidDecl() &&
13569 SemaRef.Context.hasSameType(D->getType(), Ty))
13570 return D;
13571 return nullptr;
13572 }))
13573 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
13574 VK_LValue, Loc);
13575 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000013576 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13577 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
13578 if (!D->isInvalidDecl() &&
13579 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
13580 !Ty.isMoreQualifiedThan(D->getType()))
13581 return D;
13582 return nullptr;
13583 })) {
13584 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13585 /*DetectVirtual=*/false);
13586 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
13587 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13588 VD->getType().getUnqualifiedType()))) {
13589 if (SemaRef.CheckBaseClassAccess(
13590 Loc, VD->getType(), Ty, Paths.front(),
13591 /*DiagID=*/0) != Sema::AR_inaccessible) {
13592 SemaRef.BuildBasePathArray(Paths, BasePath);
13593 return SemaRef.BuildDeclRefExpr(
13594 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
13595 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013596 }
13597 }
13598 }
13599 }
13600 if (ReductionIdScopeSpec.isSet()) {
Alexey Bataevadd743b2020-01-03 11:58:16 -050013601 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier)
13602 << Ty << Range;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013603 return ExprError();
13604 }
13605 return ExprEmpty();
13606}
13607
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013608namespace {
13609/// Data for the reduction-based clauses.
13610struct ReductionData {
13611 /// List of original reduction items.
13612 SmallVector<Expr *, 8> Vars;
13613 /// List of private copies of the reduction items.
13614 SmallVector<Expr *, 8> Privates;
13615 /// LHS expressions for the reduction_op expressions.
13616 SmallVector<Expr *, 8> LHSs;
13617 /// RHS expressions for the reduction_op expressions.
13618 SmallVector<Expr *, 8> RHSs;
13619 /// Reduction operation expression.
13620 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000013621 /// Taskgroup descriptors for the corresponding reduction items in
13622 /// in_reduction clauses.
13623 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013624 /// List of captures for clause.
13625 SmallVector<Decl *, 4> ExprCaptures;
13626 /// List of postupdate expressions.
13627 SmallVector<Expr *, 4> ExprPostUpdates;
13628 ReductionData() = delete;
13629 /// Reserves required memory for the reduction data.
13630 ReductionData(unsigned Size) {
13631 Vars.reserve(Size);
13632 Privates.reserve(Size);
13633 LHSs.reserve(Size);
13634 RHSs.reserve(Size);
13635 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000013636 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013637 ExprCaptures.reserve(Size);
13638 ExprPostUpdates.reserve(Size);
13639 }
13640 /// Stores reduction item and reduction operation only (required for dependent
13641 /// reduction item).
13642 void push(Expr *Item, Expr *ReductionOp) {
13643 Vars.emplace_back(Item);
13644 Privates.emplace_back(nullptr);
13645 LHSs.emplace_back(nullptr);
13646 RHSs.emplace_back(nullptr);
13647 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013648 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013649 }
13650 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000013651 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
13652 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013653 Vars.emplace_back(Item);
13654 Privates.emplace_back(Private);
13655 LHSs.emplace_back(LHS);
13656 RHSs.emplace_back(RHS);
13657 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000013658 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013659 }
13660};
13661} // namespace
13662
Alexey Bataeve3727102018-04-18 15:57:46 +000013663static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013664 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
13665 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
13666 const Expr *Length = OASE->getLength();
13667 if (Length == nullptr) {
13668 // For array sections of the form [1:] or [:], we would need to analyze
13669 // the lower bound...
13670 if (OASE->getColonLoc().isValid())
13671 return false;
13672
13673 // This is an array subscript which has implicit length 1!
13674 SingleElement = true;
13675 ArraySizes.push_back(llvm::APSInt::get(1));
13676 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013677 Expr::EvalResult Result;
13678 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013679 return false;
13680
Fangrui Song407659a2018-11-30 23:41:18 +000013681 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013682 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
13683 ArraySizes.push_back(ConstantLengthValue);
13684 }
13685
13686 // Get the base of this array section and walk up from there.
13687 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
13688
13689 // We require length = 1 for all array sections except the right-most to
13690 // guarantee that the memory region is contiguous and has no holes in it.
13691 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
13692 Length = TempOASE->getLength();
13693 if (Length == nullptr) {
13694 // For array sections of the form [1:] or [:], we would need to analyze
13695 // the lower bound...
13696 if (OASE->getColonLoc().isValid())
13697 return false;
13698
13699 // This is an array subscript which has implicit length 1!
13700 ArraySizes.push_back(llvm::APSInt::get(1));
13701 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000013702 Expr::EvalResult Result;
13703 if (!Length->EvaluateAsInt(Result, Context))
13704 return false;
13705
13706 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
13707 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000013708 return false;
13709
13710 ArraySizes.push_back(ConstantLengthValue);
13711 }
13712 Base = TempOASE->getBase()->IgnoreParenImpCasts();
13713 }
13714
13715 // If we have a single element, we don't need to add the implicit lengths.
13716 if (!SingleElement) {
13717 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
13718 // Has implicit length 1!
13719 ArraySizes.push_back(llvm::APSInt::get(1));
13720 Base = TempASE->getBase()->IgnoreParenImpCasts();
13721 }
13722 }
13723
13724 // This array section can be privatized as a single value or as a constant
13725 // sized array.
13726 return true;
13727}
13728
Alexey Bataeve3727102018-04-18 15:57:46 +000013729static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000013730 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
13731 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
13732 SourceLocation ColonLoc, SourceLocation EndLoc,
13733 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013734 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013735 DeclarationName DN = ReductionId.getName();
13736 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013737 BinaryOperatorKind BOK = BO_Comma;
13738
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013739 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013740 // OpenMP [2.14.3.6, reduction clause]
13741 // C
13742 // reduction-identifier is either an identifier or one of the following
13743 // operators: +, -, *, &, |, ^, && and ||
13744 // C++
13745 // reduction-identifier is either an id-expression or one of the following
13746 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000013747 switch (OOK) {
13748 case OO_Plus:
13749 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013750 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013751 break;
13752 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013753 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013754 break;
13755 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013756 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013757 break;
13758 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013759 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013760 break;
13761 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013762 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000013763 break;
13764 case OO_AmpAmp:
13765 BOK = BO_LAnd;
13766 break;
13767 case OO_PipePipe:
13768 BOK = BO_LOr;
13769 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013770 case OO_New:
13771 case OO_Delete:
13772 case OO_Array_New:
13773 case OO_Array_Delete:
13774 case OO_Slash:
13775 case OO_Percent:
13776 case OO_Tilde:
13777 case OO_Exclaim:
13778 case OO_Equal:
13779 case OO_Less:
13780 case OO_Greater:
13781 case OO_LessEqual:
13782 case OO_GreaterEqual:
13783 case OO_PlusEqual:
13784 case OO_MinusEqual:
13785 case OO_StarEqual:
13786 case OO_SlashEqual:
13787 case OO_PercentEqual:
13788 case OO_CaretEqual:
13789 case OO_AmpEqual:
13790 case OO_PipeEqual:
13791 case OO_LessLess:
13792 case OO_GreaterGreater:
13793 case OO_LessLessEqual:
13794 case OO_GreaterGreaterEqual:
13795 case OO_EqualEqual:
13796 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000013797 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013798 case OO_PlusPlus:
13799 case OO_MinusMinus:
13800 case OO_Comma:
13801 case OO_ArrowStar:
13802 case OO_Arrow:
13803 case OO_Call:
13804 case OO_Subscript:
13805 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000013806 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000013807 case NUM_OVERLOADED_OPERATORS:
13808 llvm_unreachable("Unexpected reduction identifier");
13809 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000013810 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013811 if (II->isStr("max"))
13812 BOK = BO_GT;
13813 else if (II->isStr("min"))
13814 BOK = BO_LT;
13815 }
13816 break;
13817 }
13818 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013819 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000013820 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000013821 else
13822 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013823 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000013824
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013825 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
13826 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013827 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000013828 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000013829 // OpenMP [2.1, C/C++]
13830 // A list item is a variable or array section, subject to the restrictions
13831 // specified in Section 2.4 on page 42 and in each of the sections
13832 // describing clauses and directives for which a list appears.
13833 // OpenMP [2.14.3.3, Restrictions, p.1]
13834 // A variable that is part of another variable (as an array or
13835 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013836 if (!FirstIter && IR != ER)
13837 ++IR;
13838 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013839 SourceLocation ELoc;
13840 SourceRange ERange;
13841 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013842 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000013843 /*AllowArraySection=*/true);
13844 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013845 // Try to find 'declare reduction' corresponding construct before using
13846 // builtin/overloaded operators.
13847 QualType Type = Context.DependentTy;
13848 CXXCastPath BasePath;
13849 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013850 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013851 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013852 Expr *ReductionOp = nullptr;
13853 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013854 (DeclareReductionRef.isUnset() ||
13855 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013856 ReductionOp = DeclareReductionRef.get();
13857 // It will be analyzed later.
13858 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000013859 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013860 ValueDecl *D = Res.first;
13861 if (!D)
13862 continue;
13863
Alexey Bataev88202be2017-07-27 13:20:36 +000013864 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000013865 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000013866 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
13867 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000013868 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000013869 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013870 } else if (OASE) {
13871 QualType BaseType =
13872 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
13873 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000013874 Type = ATy->getElementType();
13875 else
13876 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000013877 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013878 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000013879 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000013880 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000013881 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000013882
Alexey Bataevc5e02582014-06-16 07:08:35 +000013883 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
13884 // A variable that appears in a private clause must not have an incomplete
13885 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000013886 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013887 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013888 continue;
13889 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000013890 // A list item that appears in a reduction clause must not be
13891 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000013892 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
13893 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000013894 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000013895
13896 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000013897 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
13898 // If a list-item is a reference type then it must bind to the same object
13899 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000013900 if (!ASE && !OASE) {
13901 if (VD) {
13902 VarDecl *VDDef = VD->getDefinition();
13903 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
13904 DSARefChecker Check(Stack);
13905 if (Check.Visit(VDDef->getInit())) {
13906 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
13907 << getOpenMPClauseName(ClauseKind) << ERange;
13908 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
13909 continue;
13910 }
Alexey Bataeva1764212015-09-30 09:22:36 +000013911 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000013912 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013913
Alexey Bataevbc529672018-09-28 19:33:14 +000013914 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
13915 // in a Construct]
13916 // Variables with the predetermined data-sharing attributes may not be
13917 // listed in data-sharing attributes clauses, except for the cases
13918 // listed below. For these exceptions only, listing a predetermined
13919 // variable in a data-sharing attribute clause is allowed and overrides
13920 // the variable's predetermined data-sharing attributes.
13921 // OpenMP [2.14.3.6, Restrictions, p.3]
13922 // Any number of reduction clauses can be specified on the directive,
13923 // but a list item can appear only once in the reduction clauses for that
13924 // directive.
13925 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
13926 if (DVar.CKind == OMPC_reduction) {
13927 S.Diag(ELoc, diag::err_omp_once_referenced)
13928 << getOpenMPClauseName(ClauseKind);
13929 if (DVar.RefExpr)
13930 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
13931 continue;
13932 }
13933 if (DVar.CKind != OMPC_unknown) {
13934 S.Diag(ELoc, diag::err_omp_wrong_dsa)
13935 << getOpenMPClauseName(DVar.CKind)
13936 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000013937 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013938 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000013939 }
Alexey Bataevbc529672018-09-28 19:33:14 +000013940
13941 // OpenMP [2.14.3.6, Restrictions, p.1]
13942 // A list item that appears in a reduction clause of a worksharing
13943 // construct must be shared in the parallel regions to which any of the
13944 // worksharing regions arising from the worksharing construct bind.
13945 if (isOpenMPWorksharingDirective(CurrDir) &&
13946 !isOpenMPParallelDirective(CurrDir) &&
13947 !isOpenMPTeamsDirective(CurrDir)) {
13948 DVar = Stack->getImplicitDSA(D, true);
13949 if (DVar.CKind != OMPC_shared) {
13950 S.Diag(ELoc, diag::err_omp_required_access)
13951 << getOpenMPClauseName(OMPC_reduction)
13952 << getOpenMPClauseName(OMPC_shared);
13953 reportOriginalDsa(S, Stack, D, DVar);
13954 continue;
13955 }
13956 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000013957 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000013958
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013959 // Try to find 'declare reduction' corresponding construct before using
13960 // builtin/overloaded operators.
13961 CXXCastPath BasePath;
13962 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013963 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013964 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
13965 if (DeclareReductionRef.isInvalid())
13966 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013967 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013968 (DeclareReductionRef.isUnset() ||
13969 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013970 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013971 continue;
13972 }
13973 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
13974 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013975 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013976 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013977 << Type << ReductionIdRange;
13978 continue;
13979 }
13980
13981 // OpenMP [2.14.3.6, reduction clause, Restrictions]
13982 // The type of a list item that appears in a reduction clause must be valid
13983 // for the reduction-identifier. For a max or min reduction in C, the type
13984 // of the list item must be an allowed arithmetic data type: char, int,
13985 // float, double, or _Bool, possibly modified with long, short, signed, or
13986 // unsigned. For a max or min reduction in C++, the type of the list item
13987 // must be an allowed arithmetic data type: char, wchar_t, int, float,
13988 // double, or bool, possibly modified with long, short, signed, or unsigned.
13989 if (DeclareReductionRef.isUnset()) {
13990 if ((BOK == BO_GT || BOK == BO_LT) &&
13991 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013992 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
13993 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000013994 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013995 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000013996 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
13997 VarDecl::DeclarationOnly;
13998 S.Diag(D->getLocation(),
13999 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014000 << D;
14001 }
14002 continue;
14003 }
14004 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014005 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000014006 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
14007 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014008 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014009 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14010 VarDecl::DeclarationOnly;
14011 S.Diag(D->getLocation(),
14012 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014013 << D;
14014 }
14015 continue;
14016 }
14017 }
14018
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014019 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014020 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
14021 D->hasAttrs() ? &D->getAttrs() : nullptr);
14022 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
14023 D->hasAttrs() ? &D->getAttrs() : nullptr);
14024 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000014025
14026 // Try if we can determine constant lengths for all array sections and avoid
14027 // the VLA.
14028 bool ConstantLengthOASE = false;
14029 if (OASE) {
14030 bool SingleElement;
14031 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000014032 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000014033 Context, OASE, SingleElement, ArraySizes);
14034
14035 // If we don't have a single element, we must emit a constant array type.
14036 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014037 for (llvm::APSInt &Size : ArraySizes)
Richard Smith772e2662019-10-04 01:25:59 +000014038 PrivateTy = Context.getConstantArrayType(PrivateTy, Size, nullptr,
14039 ArrayType::Normal,
14040 /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000014041 }
14042 }
14043
14044 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000014045 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000014046 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Alexey Bataev85260312019-07-11 20:35:31 +000014047 if (!Context.getTargetInfo().isVLASupported()) {
14048 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective())) {
14049 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
14050 S.Diag(ELoc, diag::note_vla_unsupported);
14051 } else {
14052 S.targetDiag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
14053 S.targetDiag(ELoc, diag::note_vla_unsupported);
14054 }
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000014055 continue;
14056 }
David Majnemer9d168222016-08-05 17:44:54 +000014057 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014058 // Create pseudo array type for private copy. The size for this array will
14059 // be generated during codegen.
14060 // For array subscripts or single variables Private Ty is the same as Type
14061 // (type of the variable or single array element).
14062 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014063 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000014064 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014065 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000014066 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000014067 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000014068 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014069 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014070 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000014071 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014072 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
14073 D->hasAttrs() ? &D->getAttrs() : nullptr,
14074 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014075 // Add initializer for private variable.
14076 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014077 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
14078 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014079 if (DeclareReductionRef.isUsable()) {
14080 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
14081 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
14082 if (DRD->getInitializer()) {
14083 Init = DRDRef;
14084 RHSVD->setInit(DRDRef);
14085 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014086 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014087 } else {
14088 switch (BOK) {
14089 case BO_Add:
14090 case BO_Xor:
14091 case BO_Or:
14092 case BO_LOr:
14093 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
14094 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014095 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014096 break;
14097 case BO_Mul:
14098 case BO_LAnd:
14099 if (Type->isScalarType() || Type->isAnyComplexType()) {
14100 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014101 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000014102 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014103 break;
14104 case BO_And: {
14105 // '&' reduction op - initializer is '~0'.
14106 QualType OrigType = Type;
14107 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
14108 Type = ComplexTy->getElementType();
14109 if (Type->isRealFloatingType()) {
14110 llvm::APFloat InitValue =
14111 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
14112 /*isIEEE=*/true);
14113 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
14114 Type, ELoc);
14115 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014116 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014117 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
14118 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
14119 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
14120 }
14121 if (Init && OrigType->isAnyComplexType()) {
14122 // Init = 0xFFFF + 0xFFFFi;
14123 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014124 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014125 }
14126 Type = OrigType;
14127 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014128 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014129 case BO_LT:
14130 case BO_GT: {
14131 // 'min' reduction op - initializer is 'Largest representable number in
14132 // the reduction list item type'.
14133 // 'max' reduction op - initializer is 'Least representable number in
14134 // the reduction list item type'.
14135 if (Type->isIntegerType() || Type->isPointerType()) {
14136 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014137 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014138 QualType IntTy =
14139 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
14140 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014141 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
14142 : llvm::APInt::getMinValue(Size)
14143 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
14144 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014145 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
14146 if (Type->isPointerType()) {
14147 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014148 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000014149 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014150 if (CastExpr.isInvalid())
14151 continue;
14152 Init = CastExpr.get();
14153 }
14154 } else if (Type->isRealFloatingType()) {
14155 llvm::APFloat InitValue = llvm::APFloat::getLargest(
14156 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
14157 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
14158 Type, ELoc);
14159 }
14160 break;
14161 }
14162 case BO_PtrMemD:
14163 case BO_PtrMemI:
14164 case BO_MulAssign:
14165 case BO_Div:
14166 case BO_Rem:
14167 case BO_Sub:
14168 case BO_Shl:
14169 case BO_Shr:
14170 case BO_LE:
14171 case BO_GE:
14172 case BO_EQ:
14173 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000014174 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014175 case BO_AndAssign:
14176 case BO_XorAssign:
14177 case BO_OrAssign:
14178 case BO_Assign:
14179 case BO_AddAssign:
14180 case BO_SubAssign:
14181 case BO_DivAssign:
14182 case BO_RemAssign:
14183 case BO_ShlAssign:
14184 case BO_ShrAssign:
14185 case BO_Comma:
14186 llvm_unreachable("Unexpected reduction operation");
14187 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014188 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014189 if (Init && DeclareReductionRef.isUnset())
14190 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
14191 else if (!Init)
14192 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014193 if (RHSVD->isInvalidDecl())
14194 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000014195 if (!RHSVD->hasInit() &&
14196 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014197 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
14198 << Type << ReductionIdRange;
14199 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
14200 VarDecl::DeclarationOnly;
14201 S.Diag(D->getLocation(),
14202 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000014203 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014204 continue;
14205 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000014206 // Store initializer for single element in private copy. Will be used during
14207 // codegen.
14208 PrivateVD->setInit(RHSVD->getInit());
14209 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000014210 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014211 ExprResult ReductionOp;
14212 if (DeclareReductionRef.isUsable()) {
14213 QualType RedTy = DeclareReductionRef.get()->getType();
14214 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014215 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
14216 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014217 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014218 LHS = S.DefaultLvalueConversion(LHS.get());
14219 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014220 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
14221 CK_UncheckedDerivedToBase, LHS.get(),
14222 &BasePath, LHS.get()->getValueKind());
14223 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
14224 CK_UncheckedDerivedToBase, RHS.get(),
14225 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000014226 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014227 FunctionProtoType::ExtProtoInfo EPI;
14228 QualType Params[] = {PtrRedTy, PtrRedTy};
14229 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
14230 auto *OVE = new (Context) OpaqueValueExpr(
14231 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014232 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014233 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000014234 ReductionOp =
14235 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014236 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014237 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014238 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014239 if (ReductionOp.isUsable()) {
14240 if (BOK != BO_LT && BOK != BO_GT) {
14241 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014242 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014243 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014244 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000014245 auto *ConditionalOp = new (Context)
14246 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
14247 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014248 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014249 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014250 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014251 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000014252 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014253 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
14254 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014255 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000014256 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014257 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000014258 }
14259
Alexey Bataevfa312f32017-07-21 18:48:21 +000014260 // OpenMP [2.15.4.6, Restrictions, p.2]
14261 // A list item that appears in an in_reduction clause of a task construct
14262 // must appear in a task_reduction clause of a construct associated with a
14263 // taskgroup region that includes the participating task in its taskgroup
14264 // set. The construct associated with the innermost region that meets this
14265 // condition must specify the same reduction-identifier as the in_reduction
14266 // clause.
14267 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000014268 SourceRange ParentSR;
14269 BinaryOperatorKind ParentBOK;
14270 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000014271 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000014272 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000014273 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
14274 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014275 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000014276 Stack->getTopMostTaskgroupReductionData(
14277 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014278 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
14279 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
14280 if (!IsParentBOK && !IsParentReductionOp) {
14281 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
14282 continue;
14283 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000014284 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
14285 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
14286 IsParentReductionOp) {
14287 bool EmitError = true;
14288 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
14289 llvm::FoldingSetNodeID RedId, ParentRedId;
14290 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
14291 DeclareReductionRef.get()->Profile(RedId, Context,
14292 /*Canonical=*/true);
14293 EmitError = RedId != ParentRedId;
14294 }
14295 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014296 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000014297 diag::err_omp_reduction_identifier_mismatch)
14298 << ReductionIdRange << RefExpr->getSourceRange();
14299 S.Diag(ParentSR.getBegin(),
14300 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000014301 << ParentSR
14302 << (IsParentBOK ? ParentBOKDSA.RefExpr
14303 : ParentReductionOpDSA.RefExpr)
14304 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000014305 continue;
14306 }
14307 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014308 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
14309 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000014310 }
14311
Alexey Bataev60da77e2016-02-29 05:54:20 +000014312 DeclRefExpr *Ref = nullptr;
14313 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014314 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000014315 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014316 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000014317 VarsExpr =
14318 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
14319 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000014320 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014321 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000014322 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014323 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014324 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014325 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014326 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000014327 if (!RefRes.isUsable())
14328 continue;
14329 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014330 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
14331 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000014332 if (!PostUpdateRes.isUsable())
14333 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014334 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
14335 Stack->getCurrentDirective() == OMPD_taskgroup) {
14336 S.Diag(RefExpr->getExprLoc(),
14337 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000014338 << RefExpr->getSourceRange();
14339 continue;
14340 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014341 RD.ExprPostUpdates.emplace_back(
14342 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000014343 }
14344 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000014345 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000014346 // All reduction items are still marked as reduction (to do not increase
14347 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014348 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014349 if (CurrDir == OMPD_taskgroup) {
14350 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014351 Stack->addTaskgroupReductionData(D, ReductionIdRange,
14352 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000014353 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000014354 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000014355 }
Alexey Bataev88202be2017-07-27 13:20:36 +000014356 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
14357 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000014358 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014359 return RD.Vars.empty();
14360}
Alexey Bataevc5e02582014-06-16 07:08:35 +000014361
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014362OMPClause *Sema::ActOnOpenMPReductionClause(
14363 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14364 SourceLocation ColonLoc, SourceLocation EndLoc,
14365 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14366 ArrayRef<Expr *> UnresolvedReductions) {
14367 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014368 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014369 StartLoc, LParenLoc, ColonLoc, EndLoc,
14370 ReductionIdScopeSpec, ReductionId,
14371 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000014372 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000014373
Alexey Bataevc5e02582014-06-16 07:08:35 +000014374 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000014375 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14376 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14377 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14378 buildPreInits(Context, RD.ExprCaptures),
14379 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000014380}
14381
Alexey Bataev169d96a2017-07-18 20:17:46 +000014382OMPClause *Sema::ActOnOpenMPTaskReductionClause(
14383 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14384 SourceLocation ColonLoc, SourceLocation EndLoc,
14385 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14386 ArrayRef<Expr *> UnresolvedReductions) {
14387 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014388 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
14389 StartLoc, LParenLoc, ColonLoc, EndLoc,
14390 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000014391 UnresolvedReductions, RD))
14392 return nullptr;
14393
14394 return OMPTaskReductionClause::Create(
14395 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14396 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
14397 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
14398 buildPreInits(Context, RD.ExprCaptures),
14399 buildPostUpdate(*this, RD.ExprPostUpdates));
14400}
14401
Alexey Bataevfa312f32017-07-21 18:48:21 +000014402OMPClause *Sema::ActOnOpenMPInReductionClause(
14403 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
14404 SourceLocation ColonLoc, SourceLocation EndLoc,
14405 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
14406 ArrayRef<Expr *> UnresolvedReductions) {
14407 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000014408 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014409 StartLoc, LParenLoc, ColonLoc, EndLoc,
14410 ReductionIdScopeSpec, ReductionId,
14411 UnresolvedReductions, RD))
14412 return nullptr;
14413
14414 return OMPInReductionClause::Create(
14415 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
14416 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000014417 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000014418 buildPreInits(Context, RD.ExprCaptures),
14419 buildPostUpdate(*this, RD.ExprPostUpdates));
14420}
14421
Alexey Bataevecba70f2016-04-12 11:02:11 +000014422bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
14423 SourceLocation LinLoc) {
14424 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
14425 LinKind == OMPC_LINEAR_unknown) {
14426 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
14427 return true;
14428 }
14429 return false;
14430}
14431
Alexey Bataeve3727102018-04-18 15:57:46 +000014432bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000014433 OpenMPLinearClauseKind LinKind,
14434 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014435 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000014436 // A variable must not have an incomplete type or a reference type.
14437 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
14438 return true;
14439 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
14440 !Type->isReferenceType()) {
14441 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
14442 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
14443 return true;
14444 }
14445 Type = Type.getNonReferenceType();
14446
Joel E. Dennybae586f2019-01-04 22:12:13 +000014447 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
14448 // A variable that is privatized must not have a const-qualified type
14449 // unless it is of class type with a mutable member. This restriction does
14450 // not apply to the firstprivate clause.
14451 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000014452 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014453
14454 // A list item must be of integral or pointer type.
14455 Type = Type.getUnqualifiedType().getCanonicalType();
14456 const auto *Ty = Type.getTypePtrOrNull();
Alexey Bataev3f2e3dc2020-01-07 09:26:10 -050014457 if (!Ty || (LinKind != OMPC_LINEAR_ref && !Ty->isDependentType() &&
14458 !Ty->isIntegralType(Context) && !Ty->isPointerType())) {
Alexey Bataevecba70f2016-04-12 11:02:11 +000014459 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
14460 if (D) {
14461 bool IsDecl =
14462 !VD ||
14463 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
14464 Diag(D->getLocation(),
14465 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
14466 << D;
14467 }
14468 return true;
14469 }
14470 return false;
14471}
14472
Alexey Bataev182227b2015-08-20 10:54:39 +000014473OMPClause *Sema::ActOnOpenMPLinearClause(
14474 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
14475 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
14476 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014477 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014478 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000014479 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000014480 SmallVector<Decl *, 4> ExprCaptures;
14481 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014482 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000014483 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000014484 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014485 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014486 SourceLocation ELoc;
14487 SourceRange ERange;
14488 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014489 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014490 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000014491 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014492 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014493 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014494 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000014495 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014496 ValueDecl *D = Res.first;
14497 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000014498 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000014499
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014500 QualType Type = D->getType();
14501 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000014502
14503 // OpenMP [2.14.3.7, linear clause]
14504 // A list-item cannot appear in more than one linear clause.
14505 // A list-item that appears in a linear clause cannot appear in any
14506 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014507 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000014508 if (DVar.RefExpr) {
14509 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
14510 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000014511 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000014512 continue;
14513 }
14514
Alexey Bataevecba70f2016-04-12 11:02:11 +000014515 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000014516 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000014517 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000014518
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014519 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000014520 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014521 buildVarDecl(*this, ELoc, Type, D->getName(),
14522 D->hasAttrs() ? &D->getAttrs() : nullptr,
14523 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014524 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014525 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014526 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014527 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014528 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014529 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014530 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014531 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000014532 ExprCaptures.push_back(Ref->getDecl());
14533 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
14534 ExprResult RefRes = DefaultLvalueConversion(Ref);
14535 if (!RefRes.isUsable())
14536 continue;
14537 ExprResult PostUpdateRes =
14538 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
14539 SimpleRefExpr, RefRes.get());
14540 if (!PostUpdateRes.isUsable())
14541 continue;
14542 ExprPostUpdates.push_back(
14543 IgnoredValueConversions(PostUpdateRes.get()).get());
14544 }
14545 }
14546 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014547 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014548 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014549 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014550 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014551 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014552 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014553 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000014554
14555 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000014556 Vars.push_back((VD || CurContext->isDependentContext())
14557 ? RefExpr->IgnoreParens()
14558 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014559 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000014560 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000014561 }
14562
14563 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014564 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014565
14566 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000014567 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000014568 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
14569 !Step->isInstantiationDependent() &&
14570 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014571 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000014572 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000014573 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000014574 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000014575 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000014576
Alexander Musman3276a272015-03-21 10:12:56 +000014577 // Build var to save the step value.
14578 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014579 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000014580 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000014581 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000014582 ExprResult CalcStep =
14583 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014584 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014585
Alexander Musman8dba6642014-04-22 13:09:42 +000014586 // Warn about zero linear step (it would be probably better specified as
14587 // making corresponding variables 'const').
14588 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000014589 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
14590 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000014591 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
14592 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000014593 if (!IsConstant && CalcStep.isUsable()) {
14594 // Calculate the step beforehand instead of doing this on each iteration.
14595 // (This is not used if the number of iterations may be kfold-ed).
14596 CalcStepExpr = CalcStep.get();
14597 }
Alexander Musman8dba6642014-04-22 13:09:42 +000014598 }
14599
Alexey Bataev182227b2015-08-20 10:54:39 +000014600 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
14601 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000014602 StepExpr, CalcStepExpr,
14603 buildPreInits(Context, ExprCaptures),
14604 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000014605}
14606
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014607static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
14608 Expr *NumIterations, Sema &SemaRef,
14609 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000014610 // Walk the vars and build update/final expressions for the CodeGen.
14611 SmallVector<Expr *, 8> Updates;
14612 SmallVector<Expr *, 8> Finals;
Alexey Bataev195ae902019-08-08 13:42:45 +000014613 SmallVector<Expr *, 8> UsedExprs;
Alexander Musman3276a272015-03-21 10:12:56 +000014614 Expr *Step = Clause.getStep();
14615 Expr *CalcStep = Clause.getCalcStep();
14616 // OpenMP [2.14.3.7, linear clause]
14617 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000014618 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000014619 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014620 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000014621 Step = cast<BinaryOperator>(CalcStep)->getLHS();
14622 bool HasErrors = false;
14623 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014624 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000014625 OpenMPLinearClauseKind LinKind = Clause.getModifier();
14626 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014627 SourceLocation ELoc;
14628 SourceRange ERange;
14629 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014630 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014631 ValueDecl *D = Res.first;
14632 if (Res.second || !D) {
14633 Updates.push_back(nullptr);
14634 Finals.push_back(nullptr);
14635 HasErrors = true;
14636 continue;
14637 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014638 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000014639 // OpenMP [2.15.11, distribute simd Construct]
14640 // A list item may not appear in a linear clause, unless it is the loop
14641 // iteration variable.
14642 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
14643 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
14644 SemaRef.Diag(ELoc,
14645 diag::err_omp_linear_distribute_var_non_loop_iteration);
14646 Updates.push_back(nullptr);
14647 Finals.push_back(nullptr);
14648 HasErrors = true;
14649 continue;
14650 }
Alexander Musman3276a272015-03-21 10:12:56 +000014651 Expr *InitExpr = *CurInit;
14652
14653 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000014654 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000014655 Expr *CapturedRef;
14656 if (LinKind == OMPC_LINEAR_uval)
14657 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
14658 else
14659 CapturedRef =
14660 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
14661 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
14662 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000014663
14664 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014665 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000014666 if (!Info.first)
Alexey Bataevf8be4762019-08-14 19:30:06 +000014667 Update = buildCounterUpdate(
14668 SemaRef, S, RefExpr->getExprLoc(), *CurPrivate, InitExpr, IV, Step,
14669 /*Subtract=*/false, /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014670 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014671 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014672 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014673 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000014674
14675 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014676 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000014677 if (!Info.first)
14678 Final =
14679 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
Alexey Bataevf8be4762019-08-14 19:30:06 +000014680 InitExpr, NumIterations, Step, /*Subtract=*/false,
14681 /*IsNonRectangularLB=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000014682 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014683 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014684 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014685 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000014686
Alexander Musman3276a272015-03-21 10:12:56 +000014687 if (!Update.isUsable() || !Final.isUsable()) {
14688 Updates.push_back(nullptr);
14689 Finals.push_back(nullptr);
Alexey Bataev195ae902019-08-08 13:42:45 +000014690 UsedExprs.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014691 HasErrors = true;
14692 } else {
14693 Updates.push_back(Update.get());
14694 Finals.push_back(Final.get());
Alexey Bataev195ae902019-08-08 13:42:45 +000014695 if (!Info.first)
14696 UsedExprs.push_back(SimpleRefExpr);
Alexander Musman3276a272015-03-21 10:12:56 +000014697 }
Richard Trieucc3949d2016-02-18 22:34:54 +000014698 ++CurInit;
14699 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000014700 }
Alexey Bataev195ae902019-08-08 13:42:45 +000014701 if (Expr *S = Clause.getStep())
14702 UsedExprs.push_back(S);
14703 // Fill the remaining part with the nullptr.
14704 UsedExprs.append(Clause.varlist_size() + 1 - UsedExprs.size(), nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000014705 Clause.setUpdates(Updates);
14706 Clause.setFinals(Finals);
Alexey Bataev195ae902019-08-08 13:42:45 +000014707 Clause.setUsedExprs(UsedExprs);
Alexander Musman3276a272015-03-21 10:12:56 +000014708 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000014709}
14710
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014711OMPClause *Sema::ActOnOpenMPAlignedClause(
14712 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
14713 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014714 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000014715 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000014716 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14717 SourceLocation ELoc;
14718 SourceRange ERange;
14719 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014720 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000014721 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014722 // It will be analyzed later.
14723 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014724 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000014725 ValueDecl *D = Res.first;
14726 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014727 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014728
Alexey Bataev1efd1662016-03-29 10:59:56 +000014729 QualType QType = D->getType();
14730 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014731
14732 // OpenMP [2.8.1, simd construct, Restrictions]
14733 // The type of list items appearing in the aligned clause must be
14734 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014735 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014736 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000014737 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014738 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014739 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014740 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000014741 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014742 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000014743 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014744 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000014745 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014746 continue;
14747 }
14748
14749 // OpenMP [2.8.1, simd construct, Restrictions]
14750 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000014751 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevb6e70842019-12-16 15:54:17 -050014752 Diag(ELoc, diag::err_omp_used_in_clause_twice)
14753 << 0 << getOpenMPClauseName(OMPC_aligned) << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014754 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
14755 << getOpenMPClauseName(OMPC_aligned);
14756 continue;
14757 }
14758
Alexey Bataev1efd1662016-03-29 10:59:56 +000014759 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000014760 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000014761 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14762 Vars.push_back(DefaultFunctionArrayConversion(
14763 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
14764 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000014765 }
14766
14767 // OpenMP [2.8.1, simd construct, Description]
14768 // The parameter of the aligned clause, alignment, must be a constant
14769 // positive integer expression.
14770 // If no optional parameter is specified, implementation-defined default
14771 // alignments for SIMD instructions on the target platforms are assumed.
14772 if (Alignment != nullptr) {
14773 ExprResult AlignResult =
14774 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
14775 if (AlignResult.isInvalid())
14776 return nullptr;
14777 Alignment = AlignResult.get();
14778 }
14779 if (Vars.empty())
14780 return nullptr;
14781
14782 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
14783 EndLoc, Vars, Alignment);
14784}
14785
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014786OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
14787 SourceLocation StartLoc,
14788 SourceLocation LParenLoc,
14789 SourceLocation EndLoc) {
14790 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014791 SmallVector<Expr *, 8> SrcExprs;
14792 SmallVector<Expr *, 8> DstExprs;
14793 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014794 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000014795 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
14796 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014797 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000014798 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014799 SrcExprs.push_back(nullptr);
14800 DstExprs.push_back(nullptr);
14801 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014802 continue;
14803 }
14804
Alexey Bataeved09d242014-05-28 05:53:51 +000014805 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014806 // OpenMP [2.1, C/C++]
14807 // A list item is a variable name.
14808 // OpenMP [2.14.4.1, Restrictions, p.1]
14809 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000014810 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014811 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000014812 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
14813 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014814 continue;
14815 }
14816
14817 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014818 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014819
14820 QualType Type = VD->getType();
14821 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
14822 // It will be analyzed later.
14823 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014824 SrcExprs.push_back(nullptr);
14825 DstExprs.push_back(nullptr);
14826 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014827 continue;
14828 }
14829
14830 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
14831 // A list item that appears in a copyin clause must be threadprivate.
14832 if (!DSAStack->isThreadPrivate(VD)) {
14833 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000014834 << getOpenMPClauseName(OMPC_copyin)
14835 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014836 continue;
14837 }
14838
14839 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14840 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000014841 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014842 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000014843 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
14844 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014845 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014846 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014847 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014848 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000014849 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014850 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000014851 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014852 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000014853 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014854 // For arrays generate assignment operation for single element and replace
14855 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000014856 ExprResult AssignmentOp =
14857 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
14858 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014859 if (AssignmentOp.isInvalid())
14860 continue;
14861 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014862 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014863 if (AssignmentOp.isInvalid())
14864 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014865
14866 DSAStack->addDSA(VD, DE, OMPC_copyin);
14867 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014868 SrcExprs.push_back(PseudoSrcExpr);
14869 DstExprs.push_back(PseudoDstExpr);
14870 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014871 }
14872
Alexey Bataeved09d242014-05-28 05:53:51 +000014873 if (Vars.empty())
14874 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014875
Alexey Bataevf56f98c2015-04-16 05:39:01 +000014876 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
14877 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000014878}
14879
Alexey Bataevbae9a792014-06-27 10:37:06 +000014880OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
14881 SourceLocation StartLoc,
14882 SourceLocation LParenLoc,
14883 SourceLocation EndLoc) {
14884 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000014885 SmallVector<Expr *, 8> SrcExprs;
14886 SmallVector<Expr *, 8> DstExprs;
14887 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000014888 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014889 assert(RefExpr && "NULL expr in OpenMP linear clause.");
14890 SourceLocation ELoc;
14891 SourceRange ERange;
14892 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000014893 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000014894 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014895 // It will be analyzed later.
14896 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014897 SrcExprs.push_back(nullptr);
14898 DstExprs.push_back(nullptr);
14899 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014900 }
Alexey Bataeve122da12016-03-17 10:50:17 +000014901 ValueDecl *D = Res.first;
14902 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000014903 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014904
Alexey Bataeve122da12016-03-17 10:50:17 +000014905 QualType Type = D->getType();
14906 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014907
14908 // OpenMP [2.14.4.2, Restrictions, p.2]
14909 // A list item that appears in a copyprivate clause may not appear in a
14910 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000014911 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014912 DSAStackTy::DSAVarData DVar =
14913 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014914 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
14915 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000014916 Diag(ELoc, diag::err_omp_wrong_dsa)
14917 << getOpenMPClauseName(DVar.CKind)
14918 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014919 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014920 continue;
14921 }
14922
14923 // OpenMP [2.11.4.2, Restrictions, p.1]
14924 // All list items that appear in a copyprivate clause must be either
14925 // threadprivate or private in the enclosing context.
14926 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000014927 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014928 if (DVar.CKind == OMPC_shared) {
14929 Diag(ELoc, diag::err_omp_required_access)
14930 << getOpenMPClauseName(OMPC_copyprivate)
14931 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000014932 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014933 continue;
14934 }
14935 }
14936 }
14937
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014938 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000014939 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014940 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014941 << getOpenMPClauseName(OMPC_copyprivate) << Type
14942 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014943 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000014944 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014945 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000014946 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014947 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000014948 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000014949 continue;
14950 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000014951
Alexey Bataevbae9a792014-06-27 10:37:06 +000014952 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
14953 // A variable of class type (or array thereof) that appears in a
14954 // copyin clause requires an accessible, unambiguous copy assignment
14955 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000014956 Type = Context.getBaseElementType(Type.getNonReferenceType())
14957 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000014958 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014959 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000014960 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014961 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
14962 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014963 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000014964 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000014965 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
14966 ExprResult AssignmentOp = BuildBinOp(
14967 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014968 if (AssignmentOp.isInvalid())
14969 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000014970 AssignmentOp =
14971 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000014972 if (AssignmentOp.isInvalid())
14973 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000014974
14975 // No need to mark vars as copyprivate, they are already threadprivate or
14976 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000014977 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000014978 Vars.push_back(
14979 VD ? RefExpr->IgnoreParens()
14980 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000014981 SrcExprs.push_back(PseudoSrcExpr);
14982 DstExprs.push_back(PseudoDstExpr);
14983 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000014984 }
14985
14986 if (Vars.empty())
14987 return nullptr;
14988
Alexey Bataeva63048e2015-03-23 06:18:07 +000014989 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
14990 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000014991}
14992
Alexey Bataev6125da92014-07-21 11:26:11 +000014993OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
14994 SourceLocation StartLoc,
14995 SourceLocation LParenLoc,
14996 SourceLocation EndLoc) {
14997 if (VarList.empty())
14998 return nullptr;
14999
15000 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
15001}
Alexey Bataevdea47612014-07-23 07:46:59 +000015002
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015003OMPClause *
15004Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
15005 SourceLocation DepLoc, SourceLocation ColonLoc,
15006 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
15007 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000015008 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015009 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000015010 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000015011 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000015012 return nullptr;
15013 }
15014 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015015 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
15016 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000015017 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015018 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000015019 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
15020 /*Last=*/OMPC_DEPEND_unknown, Except)
15021 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015022 return nullptr;
15023 }
15024 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000015025 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015026 llvm::APSInt DepCounter(/*BitWidth=*/32);
15027 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000015028 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
15029 if (const Expr *OrderedCountExpr =
15030 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015031 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
15032 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015033 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015034 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015035 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000015036 assert(RefExpr && "NULL expr in OpenMP shared clause.");
15037 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
15038 // It will be analyzed later.
15039 Vars.push_back(RefExpr);
15040 continue;
15041 }
15042
15043 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000015044 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000015045 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000015046 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000015047 DepCounter >= TotalDepCount) {
15048 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
15049 continue;
15050 }
15051 ++DepCounter;
15052 // OpenMP [2.13.9, Summary]
15053 // depend(dependence-type : vec), where dependence-type is:
15054 // 'sink' and where vec is the iteration vector, which has the form:
15055 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
15056 // where n is the value specified by the ordered clause in the loop
15057 // directive, xi denotes the loop iteration variable of the i-th nested
15058 // loop associated with the loop directive, and di is a constant
15059 // non-negative integer.
15060 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015061 // It will be analyzed later.
15062 Vars.push_back(RefExpr);
15063 continue;
15064 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015065 SimpleExpr = SimpleExpr->IgnoreImplicit();
15066 OverloadedOperatorKind OOK = OO_None;
15067 SourceLocation OOLoc;
15068 Expr *LHS = SimpleExpr;
15069 Expr *RHS = nullptr;
15070 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
15071 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
15072 OOLoc = BO->getOperatorLoc();
15073 LHS = BO->getLHS()->IgnoreParenImpCasts();
15074 RHS = BO->getRHS()->IgnoreParenImpCasts();
15075 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
15076 OOK = OCE->getOperator();
15077 OOLoc = OCE->getOperatorLoc();
15078 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
15079 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
15080 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
15081 OOK = MCE->getMethodDecl()
15082 ->getNameInfo()
15083 .getName()
15084 .getCXXOverloadedOperator();
15085 OOLoc = MCE->getCallee()->getExprLoc();
15086 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
15087 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015088 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015089 SourceLocation ELoc;
15090 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000015091 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000015092 if (Res.second) {
15093 // It will be analyzed later.
15094 Vars.push_back(RefExpr);
15095 }
15096 ValueDecl *D = Res.first;
15097 if (!D)
15098 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015099
Alexey Bataev17daedf2018-02-15 22:42:57 +000015100 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
15101 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
15102 continue;
15103 }
15104 if (RHS) {
15105 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
15106 RHS, OMPC_depend, /*StrictlyPositive=*/false);
15107 if (RHSRes.isInvalid())
15108 continue;
15109 }
15110 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000015111 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000015112 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015113 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000015114 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000015115 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000015116 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
15117 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000015118 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000015119 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000015120 continue;
15121 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015122 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000015123 } else {
Kelvin Li427ffa22020-01-03 11:55:37 -050015124 // OpenMP 5.0 [2.17.11, Restrictions]
15125 // List items used in depend clauses cannot be zero-length array sections.
15126 const auto *OASE = dyn_cast<OMPArraySectionExpr>(SimpleExpr);
15127 if (OASE) {
15128 const Expr *Length = OASE->getLength();
15129 Expr::EvalResult Result;
15130 if (Length && !Length->isValueDependent() &&
15131 Length->EvaluateAsInt(Result, Context) &&
15132 Result.Val.getInt().isNullValue()) {
15133 Diag(ELoc,
15134 diag::err_omp_depend_zero_length_array_section_not_allowed)
15135 << SimpleExpr->getSourceRange();
15136 continue;
15137 }
15138 }
15139
Alexey Bataev17daedf2018-02-15 22:42:57 +000015140 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
15141 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
15142 (ASE &&
15143 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
15144 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
15145 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
15146 << RefExpr->getSourceRange();
15147 continue;
15148 }
Richard Smith2e3ed4a2019-08-16 19:53:22 +000015149
15150 ExprResult Res;
15151 {
15152 Sema::TentativeAnalysisScope Trap(*this);
15153 Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
15154 RefExpr->IgnoreParenImpCasts());
15155 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015156 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
15157 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
15158 << RefExpr->getSourceRange();
15159 continue;
15160 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015161 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015162 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000015163 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000015164
15165 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
15166 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000015167 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000015168 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
15169 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
15170 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
15171 }
15172 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
15173 Vars.empty())
15174 return nullptr;
15175
Alexey Bataev8b427062016-05-25 12:36:08 +000015176 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000015177 DepKind, DepLoc, ColonLoc, Vars,
15178 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000015179 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
15180 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000015181 DSAStack->addDoacrossDependClause(C, OpsOffs);
15182 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000015183}
Michael Wonge710d542015-08-07 16:16:36 +000015184
15185OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
15186 SourceLocation LParenLoc,
15187 SourceLocation EndLoc) {
15188 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000015189 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000015190
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015191 // OpenMP [2.9.1, Restrictions]
15192 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000015193 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000015194 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000015195 return nullptr;
15196
Alexey Bataev931e19b2017-10-02 16:32:39 +000015197 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000015198 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050015199 getOpenMPCaptureRegionForClause(DKind, OMPC_device, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000015200 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000015201 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000015202 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000015203 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
15204 HelperValStmt = buildPreInits(Context, Captures);
15205 }
15206
Alexey Bataev8451efa2018-01-15 19:06:12 +000015207 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
15208 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000015209}
Kelvin Li0bff7af2015-11-23 05:32:03 +000015210
Alexey Bataeve3727102018-04-18 15:57:46 +000015211static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000015212 DSAStackTy *Stack, QualType QTy,
15213 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000015214 NamedDecl *ND;
15215 if (QTy->isIncompleteType(&ND)) {
15216 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
15217 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015218 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000015219 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
Jonas Hahnfeld071dca22019-12-07 13:31:46 +010015220 !QTy.isTriviallyCopyableType(SemaRef.Context))
Alexey Bataev95c23e72018-02-27 21:31:11 +000015221 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015222 return true;
15223}
15224
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000015225/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015226/// (array section or array subscript) does NOT specify the whole size of the
15227/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000015228static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015229 const Expr *E,
15230 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015231 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015232
15233 // If this is an array subscript, it refers to the whole size if the size of
15234 // the dimension is constant and equals 1. Also, an array section assumes the
15235 // format of an array subscript if no colon is used.
15236 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015237 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015238 return ATy->getSize().getSExtValue() != 1;
15239 // Size can't be evaluated statically.
15240 return false;
15241 }
15242
15243 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000015244 const Expr *LowerBound = OASE->getLowerBound();
15245 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015246
15247 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000015248 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015249 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000015250 Expr::EvalResult Result;
15251 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015252 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000015253
15254 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015255 if (ConstLowerBound.getSExtValue())
15256 return true;
15257 }
15258
15259 // If we don't have a length we covering the whole dimension.
15260 if (!Length)
15261 return false;
15262
15263 // If the base is a pointer, we don't have a way to get the size of the
15264 // pointee.
15265 if (BaseQTy->isPointerType())
15266 return false;
15267
15268 // We can only check if the length is the same as the size of the dimension
15269 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000015270 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015271 if (!CATy)
15272 return false;
15273
Fangrui Song407659a2018-11-30 23:41:18 +000015274 Expr::EvalResult Result;
15275 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015276 return false; // Can't get the integer value as a constant.
15277
Fangrui Song407659a2018-11-30 23:41:18 +000015278 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015279 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
15280}
15281
15282// Return true if it can be proven that the provided array expression (array
15283// section or array subscript) does NOT specify a single element of the array
15284// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000015285static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000015286 const Expr *E,
15287 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015288 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015289
15290 // An array subscript always refer to a single element. Also, an array section
15291 // assumes the format of an array subscript if no colon is used.
15292 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
15293 return false;
15294
15295 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000015296 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015297
15298 // If we don't have a length we have to check if the array has unitary size
15299 // for this dimension. Also, we should always expect a length if the base type
15300 // is pointer.
15301 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015302 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015303 return ATy->getSize().getSExtValue() != 1;
15304 // We cannot assume anything.
15305 return false;
15306 }
15307
15308 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000015309 Expr::EvalResult Result;
15310 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015311 return false; // Can't get the integer value as a constant.
15312
Fangrui Song407659a2018-11-30 23:41:18 +000015313 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015314 return ConstLength.getSExtValue() != 1;
15315}
15316
Samuel Antao661c0902016-05-26 17:39:58 +000015317// Return the expression of the base of the mappable expression or null if it
15318// cannot be determined and do all the necessary checks to see if the expression
15319// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000015320// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015321static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000015322 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000015323 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015324 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015325 SourceLocation ELoc = E->getExprLoc();
15326 SourceRange ERange = E->getSourceRange();
15327
15328 // The base of elements of list in a map clause have to be either:
15329 // - a reference to variable or field.
15330 // - a member expression.
15331 // - an array expression.
15332 //
15333 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
15334 // reference to 'r'.
15335 //
15336 // If we have:
15337 //
15338 // struct SS {
15339 // Bla S;
15340 // foo() {
15341 // #pragma omp target map (S.Arr[:12]);
15342 // }
15343 // }
15344 //
15345 // We want to retrieve the member expression 'this->S';
15346
Alexey Bataeve3727102018-04-18 15:57:46 +000015347 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015348
Samuel Antao5de996e2016-01-22 20:21:36 +000015349 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
15350 // If a list item is an array section, it must specify contiguous storage.
15351 //
15352 // For this restriction it is sufficient that we make sure only references
15353 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015354 // exist except in the rightmost expression (unless they cover the whole
15355 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000015356 //
15357 // r.ArrS[3:5].Arr[6:7]
15358 //
15359 // r.ArrS[3:5].x
15360 //
15361 // but these would be valid:
15362 // r.ArrS[3].Arr[6:7]
15363 //
15364 // r.ArrS[3].x
15365
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015366 bool AllowUnitySizeArraySection = true;
15367 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015368
Dmitry Polukhin644a9252016-03-11 07:58:34 +000015369 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015370 E = E->IgnoreParenImpCasts();
15371
15372 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
15373 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000015374 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015375
15376 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015377
15378 // If we got a reference to a declaration, we should not expect any array
15379 // section before that.
15380 AllowUnitySizeArraySection = false;
15381 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015382
15383 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015384 CurComponents.emplace_back(CurE, CurE->getDecl());
15385 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015386 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000015387
15388 if (isa<CXXThisExpr>(BaseE))
15389 // We found a base expression: this->Val.
15390 RelevantExpr = CurE;
15391 else
15392 E = BaseE;
15393
15394 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015395 if (!NoDiagnose) {
15396 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
15397 << CurE->getSourceRange();
15398 return nullptr;
15399 }
15400 if (RelevantExpr)
15401 return nullptr;
15402 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015403 }
15404
15405 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
15406
15407 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
15408 // A bit-field cannot appear in a map clause.
15409 //
15410 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015411 if (!NoDiagnose) {
15412 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
15413 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
15414 return nullptr;
15415 }
15416 if (RelevantExpr)
15417 return nullptr;
15418 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015419 }
15420
15421 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15422 // If the type of a list item is a reference to a type T then the type
15423 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015424 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015425
15426 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
15427 // A list item cannot be a variable that is a member of a structure with
15428 // a union type.
15429 //
Alexey Bataeve3727102018-04-18 15:57:46 +000015430 if (CurType->isUnionType()) {
15431 if (!NoDiagnose) {
15432 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
15433 << CurE->getSourceRange();
15434 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015435 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015436 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015437 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015438
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015439 // If we got a member expression, we should not expect any array section
15440 // before that:
15441 //
15442 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
15443 // If a list item is an element of a structure, only the rightmost symbol
15444 // of the variable reference can be an array section.
15445 //
15446 AllowUnitySizeArraySection = false;
15447 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015448
15449 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015450 CurComponents.emplace_back(CurE, FD);
15451 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015452 E = CurE->getBase()->IgnoreParenImpCasts();
15453
15454 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015455 if (!NoDiagnose) {
15456 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15457 << 0 << CurE->getSourceRange();
15458 return nullptr;
15459 }
15460 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000015461 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015462
15463 // If we got an array subscript that express the whole dimension we
15464 // can have any array expressions before. If it only expressing part of
15465 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000015466 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015467 E->getType()))
15468 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000015469
Patrick Lystere13b1e32019-01-02 19:28:48 +000015470 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15471 Expr::EvalResult Result;
15472 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
15473 if (!Result.Val.getInt().isNullValue()) {
15474 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15475 diag::err_omp_invalid_map_this_expr);
15476 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
15477 diag::note_omp_invalid_subscript_on_this_ptr_map);
15478 }
15479 }
15480 RelevantExpr = TE;
15481 }
15482
Samuel Antao90927002016-04-26 14:54:23 +000015483 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015484 CurComponents.emplace_back(CurE, nullptr);
15485 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015486 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000015487 E = CurE->getBase()->IgnoreParenImpCasts();
15488
Alexey Bataev27041fa2017-12-05 15:22:49 +000015489 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015490 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15491
Samuel Antao5de996e2016-01-22 20:21:36 +000015492 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15493 // If the type of a list item is a reference to a type T then the type
15494 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000015495 if (CurType->isReferenceType())
15496 CurType = CurType->getPointeeType();
15497
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015498 bool IsPointer = CurType->isAnyPointerType();
15499
15500 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015501 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
15502 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015503 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015504 }
15505
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015506 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000015507 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015508 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000015509 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015510
Samuel Antaodab51bb2016-07-18 23:22:11 +000015511 if (AllowWholeSizeArraySection) {
15512 // Any array section is currently allowed. Allowing a whole size array
15513 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015514 //
15515 // If this array section refers to the whole dimension we can still
15516 // accept other array sections before this one, except if the base is a
15517 // pointer. Otherwise, only unitary sections are accepted.
15518 if (NotWhole || IsPointer)
15519 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000015520 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015521 // A unity or whole array section is not allowed and that is not
15522 // compatible with the properties of the current array section.
15523 SemaRef.Diag(
15524 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
15525 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000015526 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000015527 }
Samuel Antao90927002016-04-26 14:54:23 +000015528
Patrick Lystere13b1e32019-01-02 19:28:48 +000015529 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
15530 Expr::EvalResult ResultR;
15531 Expr::EvalResult ResultL;
15532 if (CurE->getLength()->EvaluateAsInt(ResultR,
15533 SemaRef.getASTContext())) {
15534 if (!ResultR.Val.getInt().isOneValue()) {
15535 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15536 diag::err_omp_invalid_map_this_expr);
15537 SemaRef.Diag(CurE->getLength()->getExprLoc(),
15538 diag::note_omp_invalid_length_on_this_ptr_mapping);
15539 }
15540 }
15541 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
15542 ResultL, SemaRef.getASTContext())) {
15543 if (!ResultL.Val.getInt().isNullValue()) {
15544 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15545 diag::err_omp_invalid_map_this_expr);
15546 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
15547 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
15548 }
15549 }
15550 RelevantExpr = TE;
15551 }
15552
Samuel Antao90927002016-04-26 14:54:23 +000015553 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000015554 CurComponents.emplace_back(CurE, nullptr);
15555 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000015556 if (!NoDiagnose) {
15557 // If nothing else worked, this is not a valid map clause expression.
15558 SemaRef.Diag(
15559 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
15560 << ERange;
15561 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000015562 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015563 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015564 }
15565
15566 return RelevantExpr;
15567}
15568
15569// Return true if expression E associated with value VD has conflicts with other
15570// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000015571static bool checkMapConflicts(
15572 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000015573 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000015574 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
15575 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015576 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000015577 SourceLocation ELoc = E->getExprLoc();
15578 SourceRange ERange = E->getSourceRange();
15579
15580 // In order to easily check the conflicts we need to match each component of
15581 // the expression under test with the components of the expressions that are
15582 // already in the stack.
15583
Samuel Antao5de996e2016-01-22 20:21:36 +000015584 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015585 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015586 "Map clause expression with unexpected base!");
15587
15588 // Variables to help detecting enclosing problems in data environment nests.
15589 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000015590 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000015591
Samuel Antao90927002016-04-26 14:54:23 +000015592 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
15593 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000015594 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
15595 ERange, CKind, &EnclosingExpr,
15596 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
15597 StackComponents,
15598 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015599 assert(!StackComponents.empty() &&
15600 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000015601 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000015602 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000015603 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000015604
Samuel Antao90927002016-04-26 14:54:23 +000015605 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000015606 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000015607
Samuel Antao5de996e2016-01-22 20:21:36 +000015608 // Expressions must start from the same base. Here we detect at which
15609 // point both expressions diverge from each other and see if we can
15610 // detect if the memory referred to both expressions is contiguous and
15611 // do not overlap.
15612 auto CI = CurComponents.rbegin();
15613 auto CE = CurComponents.rend();
15614 auto SI = StackComponents.rbegin();
15615 auto SE = StackComponents.rend();
15616 for (; CI != CE && SI != SE; ++CI, ++SI) {
15617
15618 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
15619 // At most one list item can be an array item derived from a given
15620 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000015621 if (CurrentRegionOnly &&
15622 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
15623 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
15624 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
15625 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
15626 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000015627 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000015628 << CI->getAssociatedExpression()->getSourceRange();
15629 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
15630 diag::note_used_here)
15631 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000015632 return true;
15633 }
15634
15635 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000015636 if (CI->getAssociatedExpression()->getStmtClass() !=
15637 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000015638 break;
15639
15640 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000015641 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000015642 break;
15643 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000015644 // Check if the extra components of the expressions in the enclosing
15645 // data environment are redundant for the current base declaration.
15646 // If they are, the maps completely overlap, which is legal.
15647 for (; SI != SE; ++SI) {
15648 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000015649 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000015650 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000015651 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000015652 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000015653 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015654 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000015655 Type =
15656 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
15657 }
15658 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000015659 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000015660 SemaRef, SI->getAssociatedExpression(), Type))
15661 break;
15662 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015663
15664 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15665 // List items of map clauses in the same construct must not share
15666 // original storage.
15667 //
15668 // If the expressions are exactly the same or one is a subset of the
15669 // other, it means they are sharing storage.
15670 if (CI == CE && SI == SE) {
15671 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015672 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000015673 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015674 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015675 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015676 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15677 << ERange;
15678 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015679 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15680 << RE->getSourceRange();
15681 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015682 }
Alexey Bataeve3727102018-04-18 15:57:46 +000015683 // If we find the same expression in the enclosing data environment,
15684 // that is legal.
15685 IsEnclosedByDataEnvironmentExpr = true;
15686 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000015687 }
15688
Samuel Antao90927002016-04-26 14:54:23 +000015689 QualType DerivedType =
15690 std::prev(CI)->getAssociatedDeclaration()->getType();
15691 SourceLocation DerivedLoc =
15692 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000015693
15694 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
15695 // If the type of a list item is a reference to a type T then the type
15696 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000015697 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000015698
15699 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
15700 // A variable for which the type is pointer and an array section
15701 // derived from that variable must not appear as list items of map
15702 // clauses of the same construct.
15703 //
15704 // Also, cover one of the cases in:
15705 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15706 // If any part of the original storage of a list item has corresponding
15707 // storage in the device data environment, all of the original storage
15708 // must have corresponding storage in the device data environment.
15709 //
15710 if (DerivedType->isAnyPointerType()) {
15711 if (CI == CE || SI == SE) {
15712 SemaRef.Diag(
15713 DerivedLoc,
15714 diag::err_omp_pointer_mapped_along_with_derived_section)
15715 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015716 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15717 << RE->getSourceRange();
15718 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000015719 }
15720 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000015721 SI->getAssociatedExpression()->getStmtClass() ||
15722 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
15723 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000015724 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000015725 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000015726 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000015727 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15728 << RE->getSourceRange();
15729 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000015730 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015731 }
15732
15733 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
15734 // List items of map clauses in the same construct must not share
15735 // original storage.
15736 //
15737 // An expression is a subset of the other.
15738 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000015739 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000015740 if (CI != CE || SI != SE) {
15741 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
15742 // a pointer.
15743 auto Begin =
15744 CI != CE ? CurComponents.begin() : StackComponents.begin();
15745 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
15746 auto It = Begin;
15747 while (It != End && !It->getAssociatedDeclaration())
15748 std::advance(It, 1);
15749 assert(It != End &&
15750 "Expected at least one component with the declaration.");
15751 if (It != Begin && It->getAssociatedDeclaration()
15752 ->getType()
15753 .getCanonicalType()
15754 ->isAnyPointerType()) {
15755 IsEnclosedByDataEnvironmentExpr = false;
15756 EnclosingExpr = nullptr;
15757 return false;
15758 }
15759 }
Samuel Antao661c0902016-05-26 17:39:58 +000015760 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000015761 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000015762 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000015763 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
15764 << ERange;
15765 }
Samuel Antao5de996e2016-01-22 20:21:36 +000015766 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
15767 << RE->getSourceRange();
15768 return true;
15769 }
15770
15771 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000015772 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000015773 if (!CurrentRegionOnly && SI != SE)
15774 EnclosingExpr = RE;
15775
15776 // The current expression is a subset of the expression in the data
15777 // environment.
15778 IsEnclosedByDataEnvironmentExpr |=
15779 (!CurrentRegionOnly && CI != CE && SI == SE);
15780
15781 return false;
15782 });
15783
15784 if (CurrentRegionOnly)
15785 return FoundError;
15786
15787 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
15788 // If any part of the original storage of a list item has corresponding
15789 // storage in the device data environment, all of the original storage must
15790 // have corresponding storage in the device data environment.
15791 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
15792 // If a list item is an element of a structure, and a different element of
15793 // the structure has a corresponding list item in the device data environment
15794 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000015795 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000015796 // data environment prior to the task encountering the construct.
15797 //
15798 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
15799 SemaRef.Diag(ELoc,
15800 diag::err_omp_original_storage_is_shared_and_does_not_contain)
15801 << ERange;
15802 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
15803 << EnclosingExpr->getSourceRange();
15804 return true;
15805 }
15806
15807 return FoundError;
15808}
15809
Michael Kruse4304e9d2019-02-19 16:38:20 +000015810// Look up the user-defined mapper given the mapper name and mapped type, and
15811// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000015812static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
15813 CXXScopeSpec &MapperIdScopeSpec,
15814 const DeclarationNameInfo &MapperId,
15815 QualType Type,
15816 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000015817 if (MapperIdScopeSpec.isInvalid())
15818 return ExprError();
Michael Kruse945249b2019-09-26 22:53:01 +000015819 // Get the actual type for the array type.
15820 if (Type->isArrayType()) {
15821 assert(Type->getAsArrayTypeUnsafe() && "Expect to get a valid array type");
15822 Type = Type->getAsArrayTypeUnsafe()->getElementType().getCanonicalType();
15823 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015824 // Find all user-defined mappers with the given MapperId.
15825 SmallVector<UnresolvedSet<8>, 4> Lookups;
15826 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
15827 Lookup.suppressDiagnostics();
15828 if (S) {
15829 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
15830 NamedDecl *D = Lookup.getRepresentativeDecl();
15831 while (S && !S->isDeclScope(D))
15832 S = S->getParent();
15833 if (S)
15834 S = S->getParent();
15835 Lookups.emplace_back();
15836 Lookups.back().append(Lookup.begin(), Lookup.end());
15837 Lookup.clear();
15838 }
15839 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
15840 // Extract the user-defined mappers with the given MapperId.
15841 Lookups.push_back(UnresolvedSet<8>());
15842 for (NamedDecl *D : ULE->decls()) {
15843 auto *DMD = cast<OMPDeclareMapperDecl>(D);
15844 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
15845 Lookups.back().addDecl(DMD);
15846 }
15847 }
15848 // Defer the lookup for dependent types. The results will be passed through
15849 // UnresolvedMapper on instantiation.
15850 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
15851 Type->isInstantiationDependentType() ||
15852 Type->containsUnexpandedParameterPack() ||
15853 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
15854 return !D->isInvalidDecl() &&
15855 (D->getType()->isDependentType() ||
15856 D->getType()->isInstantiationDependentType() ||
15857 D->getType()->containsUnexpandedParameterPack());
15858 })) {
15859 UnresolvedSet<8> URS;
15860 for (const UnresolvedSet<8> &Set : Lookups) {
15861 if (Set.empty())
15862 continue;
15863 URS.append(Set.begin(), Set.end());
15864 }
15865 return UnresolvedLookupExpr::Create(
15866 SemaRef.Context, /*NamingClass=*/nullptr,
15867 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
15868 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
15869 }
Michael Kruse945249b2019-09-26 22:53:01 +000015870 SourceLocation Loc = MapperId.getLoc();
Michael Kruse4304e9d2019-02-19 16:38:20 +000015871 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
15872 // The type must be of struct, union or class type in C and C++
Michael Kruse945249b2019-09-26 22:53:01 +000015873 if (!Type->isStructureOrClassType() && !Type->isUnionType() &&
15874 (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default")) {
15875 SemaRef.Diag(Loc, diag::err_omp_mapper_wrong_type);
15876 return ExprError();
15877 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015878 // Perform argument dependent lookup.
15879 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
15880 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
15881 // Return the first user-defined mapper with the desired type.
15882 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15883 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
15884 if (!D->isInvalidDecl() &&
15885 SemaRef.Context.hasSameType(D->getType(), Type))
15886 return D;
15887 return nullptr;
15888 }))
15889 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15890 // Find the first user-defined mapper with a type derived from the desired
15891 // type.
15892 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
15893 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
15894 if (!D->isInvalidDecl() &&
15895 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
15896 !Type.isMoreQualifiedThan(D->getType()))
15897 return D;
15898 return nullptr;
15899 })) {
15900 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
15901 /*DetectVirtual=*/false);
15902 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
15903 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
15904 VD->getType().getUnqualifiedType()))) {
15905 if (SemaRef.CheckBaseClassAccess(
15906 Loc, VD->getType(), Type, Paths.front(),
15907 /*DiagID=*/0) != Sema::AR_inaccessible) {
15908 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
15909 }
15910 }
15911 }
15912 }
15913 // Report error if a mapper is specified, but cannot be found.
15914 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
15915 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
15916 << Type << MapperId.getName();
15917 return ExprError();
15918 }
15919 return ExprEmpty();
15920}
15921
Samuel Antao661c0902016-05-26 17:39:58 +000015922namespace {
15923// Utility struct that gathers all the related lists associated with a mappable
15924// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000015925struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000015926 // The list of expressions.
15927 ArrayRef<Expr *> VarList;
15928 // The list of processed expressions.
15929 SmallVector<Expr *, 16> ProcessedVarList;
15930 // The mappble components for each expression.
15931 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
15932 // The base declaration of the variable.
15933 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000015934 // The reference to the user-defined mapper associated with every expression.
15935 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000015936
15937 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
15938 // We have a list of components and base declarations for each entry in the
15939 // variable list.
15940 VarComponents.reserve(VarList.size());
15941 VarBaseDeclarations.reserve(VarList.size());
15942 }
15943};
15944}
15945
15946// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000015947// \a CKind. In the check process the valid expressions, mappable expression
15948// components, variables, and user-defined mappers are extracted and used to
15949// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
15950// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
15951// and \a MapperId are expected to be valid if the clause kind is 'map'.
15952static void checkMappableExpressionList(
15953 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
15954 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000015955 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
15956 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000015957 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000015958 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015959 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
15960 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000015961 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000015962
15963 // If the identifier of user-defined mapper is not specified, it is "default".
15964 // We do not change the actual name in this clause to distinguish whether a
15965 // mapper is specified explicitly, i.e., it is not explicitly specified when
15966 // MapperId.getName() is empty.
15967 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
15968 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
15969 MapperId.setName(DeclNames.getIdentifier(
15970 &SemaRef.getASTContext().Idents.get("default")));
15971 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000015972
15973 // Iterators to find the current unresolved mapper expression.
15974 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
15975 bool UpdateUMIt = false;
15976 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000015977
Samuel Antao90927002016-04-26 14:54:23 +000015978 // Keep track of the mappable components and base declarations in this clause.
15979 // Each entry in the list is going to have a list of components associated. We
15980 // record each set of the components so that we can build the clause later on.
15981 // In the end we should have the same amount of declarations and component
15982 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000015983
Alexey Bataeve3727102018-04-18 15:57:46 +000015984 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000015985 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000015986 SourceLocation ELoc = RE->getExprLoc();
15987
Michael Kruse4304e9d2019-02-19 16:38:20 +000015988 // Find the current unresolved mapper expression.
15989 if (UpdateUMIt && UMIt != UMEnd) {
15990 UMIt++;
15991 assert(
15992 UMIt != UMEnd &&
15993 "Expect the size of UnresolvedMappers to match with that of VarList");
15994 }
15995 UpdateUMIt = true;
15996 if (UMIt != UMEnd)
15997 UnresolvedMapper = *UMIt;
15998
Alexey Bataeve3727102018-04-18 15:57:46 +000015999 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000016000
16001 if (VE->isValueDependent() || VE->isTypeDependent() ||
16002 VE->isInstantiationDependent() ||
16003 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000016004 // Try to find the associated user-defined mapper.
16005 ExprResult ER = buildUserDefinedMapperRef(
16006 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
16007 VE->getType().getCanonicalType(), UnresolvedMapper);
16008 if (ER.isInvalid())
16009 continue;
16010 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000016011 // We can only analyze this information once the missing information is
16012 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000016013 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016014 continue;
16015 }
16016
Alexey Bataeve3727102018-04-18 15:57:46 +000016017 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000016018
Samuel Antao5de996e2016-01-22 20:21:36 +000016019 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000016020 SemaRef.Diag(ELoc,
16021 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000016022 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000016023 continue;
16024 }
16025
Samuel Antao90927002016-04-26 14:54:23 +000016026 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
16027 ValueDecl *CurDeclaration = nullptr;
16028
16029 // Obtain the array or member expression bases if required. Also, fill the
16030 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000016031 const Expr *BE = checkMapClauseExpressionBase(
16032 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000016033 if (!BE)
16034 continue;
16035
Samuel Antao90927002016-04-26 14:54:23 +000016036 assert(!CurComponents.empty() &&
16037 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000016038
Patrick Lystere13b1e32019-01-02 19:28:48 +000016039 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
16040 // Add store "this" pointer to class in DSAStackTy for future checking
16041 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000016042 // Try to find the associated user-defined mapper.
16043 ExprResult ER = buildUserDefinedMapperRef(
16044 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
16045 VE->getType().getCanonicalType(), UnresolvedMapper);
16046 if (ER.isInvalid())
16047 continue;
16048 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000016049 // Skip restriction checking for variable or field declarations
16050 MVLI.ProcessedVarList.push_back(RE);
16051 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16052 MVLI.VarComponents.back().append(CurComponents.begin(),
16053 CurComponents.end());
16054 MVLI.VarBaseDeclarations.push_back(nullptr);
16055 continue;
16056 }
16057
Samuel Antao90927002016-04-26 14:54:23 +000016058 // For the following checks, we rely on the base declaration which is
16059 // expected to be associated with the last component. The declaration is
16060 // expected to be a variable or a field (if 'this' is being mapped).
16061 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
16062 assert(CurDeclaration && "Null decl on map clause.");
16063 assert(
16064 CurDeclaration->isCanonicalDecl() &&
16065 "Expecting components to have associated only canonical declarations.");
16066
16067 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000016068 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000016069
16070 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000016071 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000016072
16073 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000016074 // threadprivate variables cannot appear in a map clause.
16075 // OpenMP 4.5 [2.10.5, target update Construct]
16076 // threadprivate variables cannot appear in a from clause.
16077 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016078 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000016079 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
16080 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000016081 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016082 continue;
16083 }
16084
Samuel Antao5de996e2016-01-22 20:21:36 +000016085 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
16086 // A list item cannot appear in both a map clause and a data-sharing
16087 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000016088
Samuel Antao5de996e2016-01-22 20:21:36 +000016089 // Check conflicts with other map clause expressions. We check the conflicts
16090 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000016091 // environment, because the restrictions are different. We only have to
16092 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000016093 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000016094 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000016095 break;
Samuel Antao661c0902016-05-26 17:39:58 +000016096 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000016097 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000016098 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000016099 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000016100
Samuel Antao661c0902016-05-26 17:39:58 +000016101 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000016102 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
16103 // If the type of a list item is a reference to a type T then the type will
16104 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000016105 auto I = llvm::find_if(
16106 CurComponents,
16107 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
16108 return MC.getAssociatedDeclaration();
16109 });
16110 assert(I != CurComponents.end() && "Null decl on map clause.");
Alexey Bataev48bad082020-01-14 14:13:47 -050016111 QualType Type;
16112 auto *ASE = dyn_cast<ArraySubscriptExpr>(VE->IgnoreParens());
16113 auto *OASE = dyn_cast<OMPArraySectionExpr>(VE->IgnoreParens());
16114 if (ASE) {
16115 Type = ASE->getType().getNonReferenceType();
16116 } else if (OASE) {
16117 QualType BaseType =
16118 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
16119 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
16120 Type = ATy->getElementType();
16121 else
16122 Type = BaseType->getPointeeType();
16123 Type = Type.getNonReferenceType();
16124 } else {
16125 Type = VE->getType();
16126 }
Samuel Antao5de996e2016-01-22 20:21:36 +000016127
Samuel Antao661c0902016-05-26 17:39:58 +000016128 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
16129 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000016130 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000016131 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000016132 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000016133 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000016134 continue;
16135
Alexey Bataev48bad082020-01-14 14:13:47 -050016136 Type = I->getAssociatedDeclaration()->getType().getNonReferenceType();
16137
Samuel Antao661c0902016-05-26 17:39:58 +000016138 if (CKind == OMPC_map) {
16139 // target enter data
16140 // OpenMP [2.10.2, Restrictions, p. 99]
16141 // A map-type must be specified in all map clauses and must be either
16142 // to or alloc.
16143 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
16144 if (DKind == OMPD_target_enter_data &&
16145 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
16146 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
16147 << (IsMapTypeImplicit ? 1 : 0)
16148 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
16149 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000016150 continue;
16151 }
Samuel Antao661c0902016-05-26 17:39:58 +000016152
16153 // target exit_data
16154 // OpenMP [2.10.3, Restrictions, p. 102]
16155 // A map-type must be specified in all map clauses and must be either
16156 // from, release, or delete.
16157 if (DKind == OMPD_target_exit_data &&
16158 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
16159 MapType == OMPC_MAP_delete)) {
16160 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
16161 << (IsMapTypeImplicit ? 1 : 0)
16162 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
16163 << getOpenMPDirectiveName(DKind);
16164 continue;
16165 }
16166
16167 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
16168 // A list item cannot appear in both a map clause and a data-sharing
16169 // attribute clause on the same construct
Joel E. Denny7d5bc552019-08-22 03:34:30 +000016170 //
16171 // OpenMP 5.0 [2.19.7.1, Restrictions, p.7]
16172 // A list item cannot appear in both a map clause and a data-sharing
16173 // attribute clause on the same construct unless the construct is a
16174 // combined construct.
16175 if (VD && ((SemaRef.LangOpts.OpenMP <= 45 &&
16176 isOpenMPTargetExecutionDirective(DKind)) ||
16177 DKind == OMPD_target)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016178 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000016179 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000016180 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000016181 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000016182 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000016183 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000016184 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000016185 continue;
16186 }
16187 }
Michael Kruse01f670d2019-02-22 22:29:42 +000016188 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000016189
Michael Kruse01f670d2019-02-22 22:29:42 +000016190 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000016191 ExprResult ER = buildUserDefinedMapperRef(
16192 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
16193 Type.getCanonicalType(), UnresolvedMapper);
16194 if (ER.isInvalid())
16195 continue;
16196 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000016197
Samuel Antao90927002016-04-26 14:54:23 +000016198 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000016199 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000016200
16201 // Store the components in the stack so that they can be used to check
16202 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000016203 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
16204 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000016205
16206 // Save the components and declaration to create the clause. For purposes of
16207 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000016208 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000016209 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
16210 MVLI.VarComponents.back().append(CurComponents.begin(),
16211 CurComponents.end());
16212 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
16213 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016214 }
Samuel Antao661c0902016-05-26 17:39:58 +000016215}
16216
Michael Kruse4304e9d2019-02-19 16:38:20 +000016217OMPClause *Sema::ActOnOpenMPMapClause(
16218 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
16219 ArrayRef<SourceLocation> MapTypeModifiersLoc,
16220 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
16221 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
16222 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
16223 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
16224 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
16225 OMPC_MAP_MODIFIER_unknown,
16226 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000016227 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
16228
16229 // Process map-type-modifiers, flag errors for duplicate modifiers.
16230 unsigned Count = 0;
16231 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
16232 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
16233 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
16234 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
16235 continue;
16236 }
16237 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000016238 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000016239 Modifiers[Count] = MapTypeModifiers[I];
16240 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
16241 ++Count;
16242 }
16243
Michael Kruse4304e9d2019-02-19 16:38:20 +000016244 MappableVarListInfo MVLI(VarList);
16245 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000016246 MapperIdScopeSpec, MapperId, UnresolvedMappers,
16247 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000016248
Samuel Antao5de996e2016-01-22 20:21:36 +000016249 // We need to produce a map clause even if we don't have variables so that
16250 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000016251 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
16252 MVLI.VarBaseDeclarations, MVLI.VarComponents,
16253 MVLI.UDMapperList, Modifiers, ModifiersLoc,
16254 MapperIdScopeSpec.getWithLocInContext(Context),
16255 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000016256}
Kelvin Li099bb8c2015-11-24 20:50:12 +000016257
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016258QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
16259 TypeResult ParsedType) {
16260 assert(ParsedType.isUsable());
16261
16262 QualType ReductionType = GetTypeFromParser(ParsedType.get());
16263 if (ReductionType.isNull())
16264 return QualType();
16265
16266 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
16267 // A type name in a declare reduction directive cannot be a function type, an
16268 // array type, a reference type, or a type qualified with const, volatile or
16269 // restrict.
16270 if (ReductionType.hasQualifiers()) {
16271 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
16272 return QualType();
16273 }
16274
16275 if (ReductionType->isFunctionType()) {
16276 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
16277 return QualType();
16278 }
16279 if (ReductionType->isReferenceType()) {
16280 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
16281 return QualType();
16282 }
16283 if (ReductionType->isArrayType()) {
16284 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
16285 return QualType();
16286 }
16287 return ReductionType;
16288}
16289
16290Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
16291 Scope *S, DeclContext *DC, DeclarationName Name,
16292 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
16293 AccessSpecifier AS, Decl *PrevDeclInScope) {
16294 SmallVector<Decl *, 8> Decls;
16295 Decls.reserve(ReductionTypes.size());
16296
16297 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000016298 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016299 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
16300 // A reduction-identifier may not be re-declared in the current scope for the
16301 // same type or for a type that is compatible according to the base language
16302 // rules.
16303 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16304 OMPDeclareReductionDecl *PrevDRD = nullptr;
16305 bool InCompoundScope = true;
16306 if (S != nullptr) {
16307 // Find previous declaration with the same name not referenced in other
16308 // declarations.
16309 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16310 InCompoundScope =
16311 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16312 LookupName(Lookup, S);
16313 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16314 /*AllowInlineNamespace=*/false);
16315 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000016316 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016317 while (Filter.hasNext()) {
16318 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
16319 if (InCompoundScope) {
16320 auto I = UsedAsPrevious.find(PrevDecl);
16321 if (I == UsedAsPrevious.end())
16322 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000016323 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016324 UsedAsPrevious[D] = true;
16325 }
16326 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16327 PrevDecl->getLocation();
16328 }
16329 Filter.done();
16330 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016331 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016332 if (!PrevData.second) {
16333 PrevDRD = PrevData.first;
16334 break;
16335 }
16336 }
16337 }
16338 } else if (PrevDeclInScope != nullptr) {
16339 auto *PrevDRDInScope = PrevDRD =
16340 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
16341 do {
16342 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
16343 PrevDRDInScope->getLocation();
16344 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
16345 } while (PrevDRDInScope != nullptr);
16346 }
Alexey Bataeve3727102018-04-18 15:57:46 +000016347 for (const auto &TyData : ReductionTypes) {
16348 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016349 bool Invalid = false;
16350 if (I != PreviousRedeclTypes.end()) {
16351 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
16352 << TyData.first;
16353 Diag(I->second, diag::note_previous_definition);
16354 Invalid = true;
16355 }
16356 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
16357 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
16358 Name, TyData.first, PrevDRD);
16359 DC->addDecl(DRD);
16360 DRD->setAccess(AS);
16361 Decls.push_back(DRD);
16362 if (Invalid)
16363 DRD->setInvalidDecl();
16364 else
16365 PrevDRD = DRD;
16366 }
16367
16368 return DeclGroupPtrTy::make(
16369 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
16370}
16371
16372void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
16373 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16374
16375 // Enter new function scope.
16376 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016377 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016378 getCurFunction()->setHasOMPDeclareReductionCombiner();
16379
16380 if (S != nullptr)
16381 PushDeclContext(S, DRD);
16382 else
16383 CurContext = DRD;
16384
Faisal Valid143a0c2017-04-01 21:30:49 +000016385 PushExpressionEvaluationContext(
16386 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016387
16388 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016389 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
16390 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
16391 // uses semantics of argument handles by value, but it should be passed by
16392 // reference. C lang does not support references, so pass all parameters as
16393 // pointers.
16394 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016395 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016396 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016397 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
16398 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
16399 // uses semantics of argument handles by value, but it should be passed by
16400 // reference. C lang does not support references, so pass all parameters as
16401 // pointers.
16402 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016403 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016404 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
16405 if (S != nullptr) {
16406 PushOnScopeChains(OmpInParm, S);
16407 PushOnScopeChains(OmpOutParm, S);
16408 } else {
16409 DRD->addDecl(OmpInParm);
16410 DRD->addDecl(OmpOutParm);
16411 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016412 Expr *InE =
16413 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
16414 Expr *OutE =
16415 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
16416 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016417}
16418
16419void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
16420 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16421 DiscardCleanupsInEvaluationContext();
16422 PopExpressionEvaluationContext();
16423
16424 PopDeclContext();
16425 PopFunctionScopeInfo();
16426
16427 if (Combiner != nullptr)
16428 DRD->setCombiner(Combiner);
16429 else
16430 DRD->setInvalidDecl();
16431}
16432
Alexey Bataev070f43a2017-09-06 14:49:58 +000016433VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016434 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16435
16436 // Enter new function scope.
16437 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000016438 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016439
16440 if (S != nullptr)
16441 PushDeclContext(S, DRD);
16442 else
16443 CurContext = DRD;
16444
Faisal Valid143a0c2017-04-01 21:30:49 +000016445 PushExpressionEvaluationContext(
16446 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016447
16448 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016449 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
16450 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
16451 // uses semantics of argument handles by value, but it should be passed by
16452 // reference. C lang does not support references, so pass all parameters as
16453 // pointers.
16454 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016455 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016456 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016457 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
16458 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
16459 // uses semantics of argument handles by value, but it should be passed by
16460 // reference. C lang does not support references, so pass all parameters as
16461 // pointers.
16462 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000016463 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000016464 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016465 if (S != nullptr) {
16466 PushOnScopeChains(OmpPrivParm, S);
16467 PushOnScopeChains(OmpOrigParm, S);
16468 } else {
16469 DRD->addDecl(OmpPrivParm);
16470 DRD->addDecl(OmpOrigParm);
16471 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000016472 Expr *OrigE =
16473 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
16474 Expr *PrivE =
16475 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
16476 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000016477 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016478}
16479
Alexey Bataev070f43a2017-09-06 14:49:58 +000016480void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
16481 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016482 auto *DRD = cast<OMPDeclareReductionDecl>(D);
16483 DiscardCleanupsInEvaluationContext();
16484 PopExpressionEvaluationContext();
16485
16486 PopDeclContext();
16487 PopFunctionScopeInfo();
16488
Alexey Bataev070f43a2017-09-06 14:49:58 +000016489 if (Initializer != nullptr) {
16490 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
16491 } else if (OmpPrivParm->hasInit()) {
16492 DRD->setInitializer(OmpPrivParm->getInit(),
16493 OmpPrivParm->isDirectInit()
16494 ? OMPDeclareReductionDecl::DirectInit
16495 : OMPDeclareReductionDecl::CopyInit);
16496 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016497 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000016498 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016499}
16500
16501Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
16502 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016503 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016504 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000016505 if (S)
16506 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
16507 /*AddToContext=*/false);
16508 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016509 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000016510 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000016511 }
16512 return DeclReductions;
16513}
16514
Michael Kruse251e1482019-02-01 20:25:04 +000016515TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
16516 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
16517 QualType T = TInfo->getType();
16518 if (D.isInvalidType())
16519 return true;
16520
16521 if (getLangOpts().CPlusPlus) {
16522 // Check that there are no default arguments (C++ only).
16523 CheckExtraCXXDefaultArguments(D);
16524 }
16525
16526 return CreateParsedType(T, TInfo);
16527}
16528
16529QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
16530 TypeResult ParsedType) {
16531 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
16532
16533 QualType MapperType = GetTypeFromParser(ParsedType.get());
16534 assert(!MapperType.isNull() && "Expect valid mapper type");
16535
16536 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16537 // The type must be of struct, union or class type in C and C++
16538 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
16539 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
16540 return QualType();
16541 }
16542 return MapperType;
16543}
16544
16545OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
16546 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
16547 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
16548 Decl *PrevDeclInScope) {
16549 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
16550 forRedeclarationInCurContext());
16551 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
16552 // A mapper-identifier may not be redeclared in the current scope for the
16553 // same type or for a type that is compatible according to the base language
16554 // rules.
16555 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
16556 OMPDeclareMapperDecl *PrevDMD = nullptr;
16557 bool InCompoundScope = true;
16558 if (S != nullptr) {
16559 // Find previous declaration with the same name not referenced in other
16560 // declarations.
16561 FunctionScopeInfo *ParentFn = getEnclosingFunction();
16562 InCompoundScope =
16563 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
16564 LookupName(Lookup, S);
16565 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
16566 /*AllowInlineNamespace=*/false);
16567 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
16568 LookupResult::Filter Filter = Lookup.makeFilter();
16569 while (Filter.hasNext()) {
16570 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
16571 if (InCompoundScope) {
16572 auto I = UsedAsPrevious.find(PrevDecl);
16573 if (I == UsedAsPrevious.end())
16574 UsedAsPrevious[PrevDecl] = false;
16575 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
16576 UsedAsPrevious[D] = true;
16577 }
16578 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
16579 PrevDecl->getLocation();
16580 }
16581 Filter.done();
16582 if (InCompoundScope) {
16583 for (const auto &PrevData : UsedAsPrevious) {
16584 if (!PrevData.second) {
16585 PrevDMD = PrevData.first;
16586 break;
16587 }
16588 }
16589 }
16590 } else if (PrevDeclInScope) {
16591 auto *PrevDMDInScope = PrevDMD =
16592 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
16593 do {
16594 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
16595 PrevDMDInScope->getLocation();
16596 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
16597 } while (PrevDMDInScope != nullptr);
16598 }
16599 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
16600 bool Invalid = false;
16601 if (I != PreviousRedeclTypes.end()) {
16602 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
16603 << MapperType << Name;
16604 Diag(I->second, diag::note_previous_definition);
16605 Invalid = true;
16606 }
16607 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
16608 MapperType, VN, PrevDMD);
16609 DC->addDecl(DMD);
16610 DMD->setAccess(AS);
16611 if (Invalid)
16612 DMD->setInvalidDecl();
16613
16614 // Enter new function scope.
16615 PushFunctionScope();
16616 setFunctionHasBranchProtectedScope();
16617
16618 CurContext = DMD;
16619
16620 return DMD;
16621}
16622
16623void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
16624 Scope *S,
16625 QualType MapperType,
16626 SourceLocation StartLoc,
16627 DeclarationName VN) {
16628 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
16629 if (S)
16630 PushOnScopeChains(VD, S);
16631 else
16632 DMD->addDecl(VD);
16633 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
16634 DMD->setMapperVarRef(MapperVarRefExpr);
16635}
16636
16637Sema::DeclGroupPtrTy
16638Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
16639 ArrayRef<OMPClause *> ClauseList) {
16640 PopDeclContext();
16641 PopFunctionScopeInfo();
16642
16643 if (D) {
16644 if (S)
16645 PushOnScopeChains(D, S, /*AddToContext=*/false);
16646 D->CreateClauses(Context, ClauseList);
16647 }
16648
16649 return DeclGroupPtrTy::make(DeclGroupRef(D));
16650}
16651
David Majnemer9d168222016-08-05 17:44:54 +000016652OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000016653 SourceLocation StartLoc,
16654 SourceLocation LParenLoc,
16655 SourceLocation EndLoc) {
16656 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016657 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016658
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016659 // OpenMP [teams Constrcut, Restrictions]
16660 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016661 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000016662 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016663 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000016664
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016665 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000016666 OpenMPDirectiveKind CaptureRegion =
Alexey Bataev61205822019-12-04 09:50:21 -050016667 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016668 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016669 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016670 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000016671 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16672 HelperValStmt = buildPreInits(Context, Captures);
16673 }
16674
16675 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
16676 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000016677}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016678
16679OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
16680 SourceLocation StartLoc,
16681 SourceLocation LParenLoc,
16682 SourceLocation EndLoc) {
16683 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016684 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016685
16686 // OpenMP [teams Constrcut, Restrictions]
16687 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000016688 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000016689 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016690 return nullptr;
16691
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016692 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev61205822019-12-04 09:50:21 -050016693 OpenMPDirectiveKind CaptureRegion = getOpenMPCaptureRegionForClause(
16694 DKind, OMPC_thread_limit, LangOpts.OpenMP);
Alexey Bataev2ba67042017-11-28 21:11:44 +000016695 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016696 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016697 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000016698 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16699 HelperValStmt = buildPreInits(Context, Captures);
16700 }
16701
16702 return new (Context) OMPThreadLimitClause(
16703 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000016704}
Alexey Bataeva0569352015-12-01 10:17:31 +000016705
16706OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
16707 SourceLocation StartLoc,
16708 SourceLocation LParenLoc,
16709 SourceLocation EndLoc) {
16710 Expr *ValExpr = Priority;
Alexey Bataev31ba4762019-10-16 18:09:37 +000016711 Stmt *HelperValStmt = nullptr;
16712 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataeva0569352015-12-01 10:17:31 +000016713
16714 // OpenMP [2.9.1, task Constrcut]
16715 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataev31ba4762019-10-16 18:09:37 +000016716 if (!isNonNegativeIntegerValue(
16717 ValExpr, *this, OMPC_priority,
16718 /*StrictlyPositive=*/false, /*BuildCapture=*/true,
16719 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataeva0569352015-12-01 10:17:31 +000016720 return nullptr;
16721
Alexey Bataev31ba4762019-10-16 18:09:37 +000016722 return new (Context) OMPPriorityClause(ValExpr, HelperValStmt, CaptureRegion,
16723 StartLoc, LParenLoc, EndLoc);
Alexey Bataeva0569352015-12-01 10:17:31 +000016724}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016725
16726OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
16727 SourceLocation StartLoc,
16728 SourceLocation LParenLoc,
16729 SourceLocation EndLoc) {
16730 Expr *ValExpr = Grainsize;
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016731 Stmt *HelperValStmt = nullptr;
16732 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016733
16734 // OpenMP [2.9.2, taskloop Constrcut]
16735 // The parameter of the grainsize clause must be a positive integer
16736 // expression.
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016737 if (!isNonNegativeIntegerValue(
16738 ValExpr, *this, OMPC_grainsize,
16739 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16740 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016741 return nullptr;
16742
Alexey Bataevb9c55e22019-10-14 19:29:52 +000016743 return new (Context) OMPGrainsizeClause(ValExpr, HelperValStmt, CaptureRegion,
16744 StartLoc, LParenLoc, EndLoc);
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000016745}
Alexey Bataev382967a2015-12-08 12:06:20 +000016746
16747OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
16748 SourceLocation StartLoc,
16749 SourceLocation LParenLoc,
16750 SourceLocation EndLoc) {
16751 Expr *ValExpr = NumTasks;
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016752 Stmt *HelperValStmt = nullptr;
16753 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataev382967a2015-12-08 12:06:20 +000016754
16755 // OpenMP [2.9.2, taskloop Constrcut]
16756 // The parameter of the num_tasks clause must be a positive integer
16757 // expression.
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016758 if (!isNonNegativeIntegerValue(
16759 ValExpr, *this, OMPC_num_tasks,
16760 /*StrictlyPositive=*/true, /*BuildCapture=*/true,
16761 DSAStack->getCurrentDirective(), &CaptureRegion, &HelperValStmt))
Alexey Bataev382967a2015-12-08 12:06:20 +000016762 return nullptr;
16763
Alexey Bataevd88c7de2019-10-14 20:44:34 +000016764 return new (Context) OMPNumTasksClause(ValExpr, HelperValStmt, CaptureRegion,
16765 StartLoc, LParenLoc, EndLoc);
Alexey Bataev382967a2015-12-08 12:06:20 +000016766}
16767
Alexey Bataev28c75412015-12-15 08:19:24 +000016768OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
16769 SourceLocation LParenLoc,
16770 SourceLocation EndLoc) {
16771 // OpenMP [2.13.2, critical construct, Description]
16772 // ... where hint-expression is an integer constant expression that evaluates
16773 // to a valid lock hint.
16774 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
16775 if (HintExpr.isInvalid())
16776 return nullptr;
16777 return new (Context)
16778 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
16779}
16780
Carlo Bertollib4adf552016-01-15 18:50:31 +000016781OMPClause *Sema::ActOnOpenMPDistScheduleClause(
16782 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
16783 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
16784 SourceLocation EndLoc) {
16785 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
16786 std::string Values;
16787 Values += "'";
16788 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
16789 Values += "'";
16790 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16791 << Values << getOpenMPClauseName(OMPC_dist_schedule);
16792 return nullptr;
16793 }
16794 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000016795 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000016796 if (ChunkSize) {
16797 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
16798 !ChunkSize->isInstantiationDependent() &&
16799 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000016800 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000016801 ExprResult Val =
16802 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
16803 if (Val.isInvalid())
16804 return nullptr;
16805
16806 ValExpr = Val.get();
16807
16808 // OpenMP [2.7.1, Restrictions]
16809 // chunk_size must be a loop invariant integer expression with a positive
16810 // value.
16811 llvm::APSInt Result;
16812 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
16813 if (Result.isSigned() && !Result.isStrictlyPositive()) {
16814 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
16815 << "dist_schedule" << ChunkSize->getSourceRange();
16816 return nullptr;
16817 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000016818 } else if (getOpenMPCaptureRegionForClause(
Alexey Bataev61205822019-12-04 09:50:21 -050016819 DSAStack->getCurrentDirective(), OMPC_dist_schedule,
16820 LangOpts.OpenMP) != OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000016821 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000016822 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000016823 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000016824 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
16825 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016826 }
16827 }
16828 }
16829
16830 return new (Context)
16831 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000016832 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000016833}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016834
16835OMPClause *Sema::ActOnOpenMPDefaultmapClause(
16836 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
16837 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
16838 SourceLocation KindLoc, SourceLocation EndLoc) {
cchene06f3e02019-11-15 13:02:06 -050016839 if (getLangOpts().OpenMP < 50) {
16840 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom ||
16841 Kind != OMPC_DEFAULTMAP_scalar) {
16842 std::string Value;
16843 SourceLocation Loc;
16844 Value += "'";
16845 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
16846 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16847 OMPC_DEFAULTMAP_MODIFIER_tofrom);
16848 Loc = MLoc;
16849 } else {
16850 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
16851 OMPC_DEFAULTMAP_scalar);
16852 Loc = KindLoc;
16853 }
16854 Value += "'";
16855 Diag(Loc, diag::err_omp_unexpected_clause_value)
16856 << Value << getOpenMPClauseName(OMPC_defaultmap);
16857 return nullptr;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016858 }
cchene06f3e02019-11-15 13:02:06 -050016859 } else {
16860 bool isDefaultmapModifier = (M != OMPC_DEFAULTMAP_MODIFIER_unknown);
16861 bool isDefaultmapKind = (Kind != OMPC_DEFAULTMAP_unknown);
16862 if (!isDefaultmapKind || !isDefaultmapModifier) {
16863 std::string ModifierValue = "'alloc', 'from', 'to', 'tofrom', "
16864 "'firstprivate', 'none', 'default'";
16865 std::string KindValue = "'scalar', 'aggregate', 'pointer'";
16866 if (!isDefaultmapKind && isDefaultmapModifier) {
16867 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16868 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16869 } else if (isDefaultmapKind && !isDefaultmapModifier) {
16870 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16871 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16872 } else {
16873 Diag(MLoc, diag::err_omp_unexpected_clause_value)
16874 << ModifierValue << getOpenMPClauseName(OMPC_defaultmap);
16875 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
16876 << KindValue << getOpenMPClauseName(OMPC_defaultmap);
16877 }
16878 return nullptr;
16879 }
16880
16881 // OpenMP [5.0, 2.12.5, Restrictions, p. 174]
16882 // At most one defaultmap clause for each category can appear on the
16883 // directive.
16884 if (DSAStack->checkDefaultmapCategory(Kind)) {
16885 Diag(StartLoc, diag::err_omp_one_defaultmap_each_category);
16886 return nullptr;
16887 }
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016888 }
cchene06f3e02019-11-15 13:02:06 -050016889 DSAStack->setDefaultDMAAttr(M, Kind, StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000016890
16891 return new (Context)
16892 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
16893}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016894
16895bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
16896 DeclContext *CurLexicalContext = getCurLexicalContext();
16897 if (!CurLexicalContext->isFileContext() &&
16898 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000016899 !CurLexicalContext->isExternCXXContext() &&
16900 !isa<CXXRecordDecl>(CurLexicalContext) &&
16901 !isa<ClassTemplateDecl>(CurLexicalContext) &&
16902 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
16903 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016904 Diag(Loc, diag::err_omp_region_not_file_context);
16905 return false;
16906 }
Kelvin Libc38e632018-09-10 02:07:09 +000016907 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016908 return true;
16909}
16910
16911void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000016912 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016913 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000016914 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016915}
16916
Alexey Bataev729e2422019-08-23 16:11:14 +000016917NamedDecl *
16918Sema::lookupOpenMPDeclareTargetName(Scope *CurScope, CXXScopeSpec &ScopeSpec,
16919 const DeclarationNameInfo &Id,
16920 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016921 LookupResult Lookup(*this, Id, LookupOrdinaryName);
16922 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
16923
16924 if (Lookup.isAmbiguous())
Alexey Bataev729e2422019-08-23 16:11:14 +000016925 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016926 Lookup.suppressDiagnostics();
16927
16928 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000016929 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016930 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000016931 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016932 CTK_ErrorRecovery)) {
16933 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
16934 << Id.getName());
16935 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
Alexey Bataev729e2422019-08-23 16:11:14 +000016936 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016937 }
16938
16939 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016940 return nullptr;
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016941 }
16942
16943 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev729e2422019-08-23 16:11:14 +000016944 if (!isa<VarDecl>(ND) && !isa<FunctionDecl>(ND) &&
16945 !isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016946 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataev729e2422019-08-23 16:11:14 +000016947 return nullptr;
16948 }
16949 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
16950 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
16951 return ND;
16952}
16953
16954void Sema::ActOnOpenMPDeclareTargetName(
16955 NamedDecl *ND, SourceLocation Loc, OMPDeclareTargetDeclAttr::MapTypeTy MT,
16956 OMPDeclareTargetDeclAttr::DevTypeTy DT) {
16957 assert((isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
16958 isa<FunctionTemplateDecl>(ND)) &&
16959 "Expected variable, function or function template.");
16960
16961 // Diagnose marking after use as it may lead to incorrect diagnosis and
16962 // codegen.
16963 if (LangOpts.OpenMP >= 50 &&
16964 (ND->isUsed(/*CheckUsedAttr=*/false) || ND->isReferenced()))
16965 Diag(Loc, diag::warn_omp_declare_target_after_first_use);
16966
16967 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
16968 OMPDeclareTargetDeclAttr::getDeviceType(cast<ValueDecl>(ND));
16969 if (DevTy.hasValue() && *DevTy != DT) {
16970 Diag(Loc, diag::err_omp_device_type_mismatch)
16971 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(DT)
16972 << OMPDeclareTargetDeclAttr::ConvertDevTypeTyToStr(*DevTy);
16973 return;
16974 }
16975 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
16976 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(cast<ValueDecl>(ND));
16977 if (!Res) {
16978 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT, DT,
16979 SourceRange(Loc, Loc));
16980 ND->addAttr(A);
16981 if (ASTMutationListener *ML = Context.getASTMutationListener())
16982 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
16983 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Loc);
16984 } else if (*Res != MT) {
16985 Diag(Loc, diag::err_omp_declare_target_to_and_link) << ND;
Alexey Bataeve3727102018-04-18 15:57:46 +000016986 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000016987}
16988
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016989static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
16990 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000016991 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000016992 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000016993 auto *VD = cast<VarDecl>(D);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000016994 Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
16995 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
16996 if (SemaRef.LangOpts.OpenMP >= 50 &&
16997 (SemaRef.getCurLambda(/*IgnoreNonLambdaCapturingScope=*/true) ||
16998 SemaRef.getCurBlock() || SemaRef.getCurCapturedRegion()) &&
16999 VD->hasGlobalStorage()) {
17000 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> MapTy =
17001 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
17002 if (!MapTy || *MapTy != OMPDeclareTargetDeclAttr::MT_To) {
17003 // OpenMP 5.0, 2.12.7 declare target Directive, Restrictions
17004 // If a lambda declaration and definition appears between a
17005 // declare target directive and the matching end declare target
17006 // directive, all variables that are captured by the lambda
17007 // expression must also appear in a to clause.
17008 SemaRef.Diag(VD->getLocation(),
Alexey Bataevc4299552019-08-20 17:50:13 +000017009 diag::err_omp_lambda_capture_in_declare_target_not_to);
Alexey Bataev217ff1e2019-08-16 20:15:02 +000017010 SemaRef.Diag(SL, diag::note_var_explicitly_captured_here)
17011 << VD << 0 << SR;
17012 return;
17013 }
17014 }
17015 if (MapTy.hasValue())
Alexey Bataev30a78212018-09-11 13:59:10 +000017016 return;
17017 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
17018 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017019}
17020
17021static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
17022 Sema &SemaRef, DSAStackTy *Stack,
17023 ValueDecl *VD) {
Alexey Bataevebcfc9e2019-08-22 16:48:26 +000017024 return OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) ||
Alexey Bataeve3727102018-04-18 15:57:46 +000017025 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
17026 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017027}
17028
Kelvin Li1ce87c72017-12-12 20:08:12 +000017029void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
17030 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017031 if (!D || D->isInvalidDecl())
17032 return;
17033 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000017034 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000017035 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000017036 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000017037 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
17038 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000017039 return;
17040 // 2.10.6: threadprivate variable cannot appear in a declare target
17041 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017042 if (DSAStack->isThreadPrivate(VD)) {
17043 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000017044 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017045 return;
17046 }
17047 }
Alexey Bataev97b72212018-08-14 18:31:20 +000017048 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
17049 D = FTD->getTemplatedDecl();
Alexey Bataev9fd495b2019-08-20 19:50:13 +000017050 if (auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000017051 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
17052 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
Alexey Bataev9fd495b2019-08-20 19:50:13 +000017053 if (IdLoc.isValid() && Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000017054 Diag(IdLoc, diag::err_omp_function_in_link_clause);
17055 Diag(FD->getLocation(), diag::note_defined_here) << FD;
17056 return;
17057 }
Alexey Bataev9fd495b2019-08-20 19:50:13 +000017058 // Mark the function as must be emitted for the device.
Alexey Bataev729e2422019-08-23 16:11:14 +000017059 Optional<OMPDeclareTargetDeclAttr::DevTypeTy> DevTy =
17060 OMPDeclareTargetDeclAttr::getDeviceType(FD);
17061 if (LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
17062 *DevTy != OMPDeclareTargetDeclAttr::DT_Host)
Alexey Bataev9fd495b2019-08-20 19:50:13 +000017063 checkOpenMPDeviceFunction(IdLoc, FD, /*CheckForDelayedContext=*/false);
Alexey Bataev729e2422019-08-23 16:11:14 +000017064 if (!LangOpts.OpenMPIsDevice && Res.hasValue() && IdLoc.isValid() &&
17065 *DevTy != OMPDeclareTargetDeclAttr::DT_NoHost)
17066 checkOpenMPHostFunction(IdLoc, FD, /*CheckCaller=*/false);
Kelvin Li1ce87c72017-12-12 20:08:12 +000017067 }
Alexey Bataev30a78212018-09-11 13:59:10 +000017068 if (auto *VD = dyn_cast<ValueDecl>(D)) {
17069 // Problem if any with var declared with incomplete type will be reported
17070 // as normal, so no need to check it here.
17071 if ((E || !VD->getType()->isIncompleteType()) &&
17072 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
17073 return;
17074 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
17075 // Checking declaration inside declare target region.
17076 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
17077 isa<FunctionTemplateDecl>(D)) {
17078 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
Alexey Bataev729e2422019-08-23 16:11:14 +000017079 Context, OMPDeclareTargetDeclAttr::MT_To,
17080 OMPDeclareTargetDeclAttr::DT_Any, SourceRange(IdLoc, IdLoc));
Alexey Bataev30a78212018-09-11 13:59:10 +000017081 D->addAttr(A);
17082 if (ASTMutationListener *ML = Context.getASTMutationListener())
17083 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
17084 }
17085 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017086 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017087 }
Alexey Bataev30a78212018-09-11 13:59:10 +000017088 if (!E)
17089 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000017090 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
17091}
Samuel Antao661c0902016-05-26 17:39:58 +000017092
17093OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000017094 CXXScopeSpec &MapperIdScopeSpec,
17095 DeclarationNameInfo &MapperId,
17096 const OMPVarListLocTy &Locs,
17097 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000017098 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000017099 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
17100 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000017101 if (MVLI.ProcessedVarList.empty())
17102 return nullptr;
17103
Michael Kruse01f670d2019-02-22 22:29:42 +000017104 return OMPToClause::Create(
17105 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
17106 MVLI.VarComponents, MVLI.UDMapperList,
17107 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000017108}
Samuel Antaoec172c62016-05-26 17:49:04 +000017109
17110OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000017111 CXXScopeSpec &MapperIdScopeSpec,
17112 DeclarationNameInfo &MapperId,
17113 const OMPVarListLocTy &Locs,
17114 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000017115 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000017116 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
17117 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000017118 if (MVLI.ProcessedVarList.empty())
17119 return nullptr;
17120
Michael Kruse0336c752019-02-25 20:34:15 +000017121 return OMPFromClause::Create(
17122 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
17123 MVLI.VarComponents, MVLI.UDMapperList,
17124 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000017125}
Carlo Bertolli2404b172016-07-13 15:37:16 +000017126
17127OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000017128 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000017129 MappableVarListInfo MVLI(VarList);
17130 SmallVector<Expr *, 8> PrivateCopies;
17131 SmallVector<Expr *, 8> Inits;
17132
Alexey Bataeve3727102018-04-18 15:57:46 +000017133 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000017134 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
17135 SourceLocation ELoc;
17136 SourceRange ERange;
17137 Expr *SimpleRefExpr = RefExpr;
17138 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17139 if (Res.second) {
17140 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000017141 MVLI.ProcessedVarList.push_back(RefExpr);
17142 PrivateCopies.push_back(nullptr);
17143 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000017144 }
17145 ValueDecl *D = Res.first;
17146 if (!D)
17147 continue;
17148
17149 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000017150 Type = Type.getNonReferenceType().getUnqualifiedType();
17151
17152 auto *VD = dyn_cast<VarDecl>(D);
17153
17154 // Item should be a pointer or reference to pointer.
17155 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000017156 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
17157 << 0 << RefExpr->getSourceRange();
17158 continue;
17159 }
Samuel Antaocc10b852016-07-28 14:23:26 +000017160
17161 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000017162 auto VDPrivate =
17163 buildVarDecl(*this, ELoc, Type, D->getName(),
17164 D->hasAttrs() ? &D->getAttrs() : nullptr,
17165 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000017166 if (VDPrivate->isInvalidDecl())
17167 continue;
17168
17169 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000017170 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000017171 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
17172
17173 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000017174 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000017175 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000017176 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
17177 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000017178 AddInitializerToDecl(VDPrivate,
17179 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000017180 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000017181
17182 // If required, build a capture to implement the privatization initialized
17183 // with the current list item value.
17184 DeclRefExpr *Ref = nullptr;
17185 if (!VD)
17186 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
17187 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
17188 PrivateCopies.push_back(VDPrivateRefExpr);
17189 Inits.push_back(VDInitRefExpr);
17190
17191 // We need to add a data sharing attribute for this variable to make sure it
17192 // is correctly captured. A variable that shows up in a use_device_ptr has
17193 // similar properties of a first private variable.
17194 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
17195
17196 // Create a mappable component for the list item. List items in this clause
17197 // only need a component.
17198 MVLI.VarBaseDeclarations.push_back(D);
17199 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17200 MVLI.VarComponents.back().push_back(
17201 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000017202 }
17203
Samuel Antaocc10b852016-07-28 14:23:26 +000017204 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000017205 return nullptr;
17206
Samuel Antaocc10b852016-07-28 14:23:26 +000017207 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000017208 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
17209 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000017210}
Carlo Bertolli70594e92016-07-13 17:16:49 +000017211
17212OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000017213 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000017214 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000017215 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000017216 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000017217 SourceLocation ELoc;
17218 SourceRange ERange;
17219 Expr *SimpleRefExpr = RefExpr;
17220 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17221 if (Res.second) {
17222 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000017223 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017224 }
17225 ValueDecl *D = Res.first;
17226 if (!D)
17227 continue;
17228
17229 QualType Type = D->getType();
17230 // item should be a pointer or array or reference to pointer or array
17231 if (!Type.getNonReferenceType()->isPointerType() &&
17232 !Type.getNonReferenceType()->isArrayType()) {
17233 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
17234 << 0 << RefExpr->getSourceRange();
17235 continue;
17236 }
Samuel Antao6890b092016-07-28 14:25:09 +000017237
17238 // Check if the declaration in the clause does not show up in any data
17239 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000017240 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000017241 if (isOpenMPPrivate(DVar.CKind)) {
17242 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
17243 << getOpenMPClauseName(DVar.CKind)
17244 << getOpenMPClauseName(OMPC_is_device_ptr)
17245 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000017246 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000017247 continue;
17248 }
17249
Alexey Bataeve3727102018-04-18 15:57:46 +000017250 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000017251 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000017252 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000017253 [&ConflictExpr](
17254 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
17255 OpenMPClauseKind) -> bool {
17256 ConflictExpr = R.front().getAssociatedExpression();
17257 return true;
17258 })) {
17259 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
17260 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
17261 << ConflictExpr->getSourceRange();
17262 continue;
17263 }
17264
17265 // Store the components in the stack so that they can be used to check
17266 // against other clauses later on.
17267 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
17268 DSAStack->addMappableExpressionComponents(
17269 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
17270
17271 // Record the expression we've just processed.
17272 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
17273
17274 // Create a mappable component for the list item. List items in this clause
17275 // only need a component. We use a null declaration to signal fields in
17276 // 'this'.
17277 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
17278 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
17279 "Unexpected device pointer expression!");
17280 MVLI.VarBaseDeclarations.push_back(
17281 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
17282 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
17283 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017284 }
17285
Samuel Antao6890b092016-07-28 14:25:09 +000017286 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000017287 return nullptr;
17288
Michael Kruse4304e9d2019-02-19 16:38:20 +000017289 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
17290 MVLI.VarBaseDeclarations,
17291 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000017292}
Alexey Bataeve04483e2019-03-27 14:14:31 +000017293
17294OMPClause *Sema::ActOnOpenMPAllocateClause(
17295 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
17296 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
17297 if (Allocator) {
17298 // OpenMP [2.11.4 allocate Clause, Description]
17299 // allocator is an expression of omp_allocator_handle_t type.
17300 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
17301 return nullptr;
17302
17303 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
17304 if (AllocatorRes.isInvalid())
17305 return nullptr;
17306 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
17307 DSAStack->getOMPAllocatorHandleT(),
17308 Sema::AA_Initializing,
17309 /*AllowExplicit=*/true);
17310 if (AllocatorRes.isInvalid())
17311 return nullptr;
17312 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000017313 } else {
17314 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
17315 // allocate clauses that appear on a target construct or on constructs in a
17316 // target region must specify an allocator expression unless a requires
17317 // directive with the dynamic_allocators clause is present in the same
17318 // compilation unit.
17319 if (LangOpts.OpenMPIsDevice &&
17320 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
17321 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000017322 }
17323 // Analyze and build list of variables.
17324 SmallVector<Expr *, 8> Vars;
17325 for (Expr *RefExpr : VarList) {
17326 assert(RefExpr && "NULL expr in OpenMP private clause.");
17327 SourceLocation ELoc;
17328 SourceRange ERange;
17329 Expr *SimpleRefExpr = RefExpr;
17330 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17331 if (Res.second) {
17332 // It will be analyzed later.
17333 Vars.push_back(RefExpr);
17334 }
17335 ValueDecl *D = Res.first;
17336 if (!D)
17337 continue;
17338
17339 auto *VD = dyn_cast<VarDecl>(D);
17340 DeclRefExpr *Ref = nullptr;
17341 if (!VD && !CurContext->isDependentContext())
17342 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
17343 Vars.push_back((VD || CurContext->isDependentContext())
17344 ? RefExpr->IgnoreParens()
17345 : Ref);
17346 }
17347
17348 if (Vars.empty())
17349 return nullptr;
17350
Alexey Bataevf3c508f2020-01-23 10:47:16 -050017351 if (Allocator)
17352 DSAStack->addInnerAllocatorExpr(Allocator);
Alexey Bataeve04483e2019-03-27 14:14:31 +000017353 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
17354 ColonLoc, EndLoc, Vars);
17355}
Alexey Bataevb6e70842019-12-16 15:54:17 -050017356
17357OMPClause *Sema::ActOnOpenMPNontemporalClause(ArrayRef<Expr *> VarList,
17358 SourceLocation StartLoc,
17359 SourceLocation LParenLoc,
17360 SourceLocation EndLoc) {
17361 SmallVector<Expr *, 8> Vars;
17362 for (Expr *RefExpr : VarList) {
17363 assert(RefExpr && "NULL expr in OpenMP nontemporal clause.");
17364 SourceLocation ELoc;
17365 SourceRange ERange;
17366 Expr *SimpleRefExpr = RefExpr;
17367 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
17368 if (Res.second)
17369 // It will be analyzed later.
17370 Vars.push_back(RefExpr);
17371 ValueDecl *D = Res.first;
17372 if (!D)
17373 continue;
17374
Alexey Bataevb6e70842019-12-16 15:54:17 -050017375 // OpenMP 5.0, 2.9.3.1 simd Construct, Restrictions.
17376 // A list-item cannot appear in more than one nontemporal clause.
17377 if (const Expr *PrevRef =
17378 DSAStack->addUniqueNontemporal(D, SimpleRefExpr)) {
17379 Diag(ELoc, diag::err_omp_used_in_clause_twice)
17380 << 0 << getOpenMPClauseName(OMPC_nontemporal) << ERange;
17381 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
17382 << getOpenMPClauseName(OMPC_nontemporal);
17383 continue;
17384 }
17385
Alexey Bataev0860db92019-12-19 10:01:10 -050017386 Vars.push_back(RefExpr);
Alexey Bataevb6e70842019-12-16 15:54:17 -050017387 }
17388
17389 if (Vars.empty())
17390 return nullptr;
17391
17392 return OMPNontemporalClause::Create(Context, StartLoc, LParenLoc, EndLoc,
17393 Vars);
17394}