blob: e54652650ede6f59539b28d72bf07d73e062b1a9 [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 Bataev9959db52014-05-06 10:08:46 +000025#include "clang/Basic/OpenMPKinds.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000026#include "clang/Sema/Initialization.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000027#include "clang/Sema/Lookup.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000028#include "clang/Sema/Scope.h"
29#include "clang/Sema/ScopeInfo.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000030#include "clang/Sema/SemaInternal.h"
Alexey Bataevfa312f32017-07-21 18:48:21 +000031#include "llvm/ADT/PointerEmbeddedInt.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000032using namespace clang;
33
Alexey Bataev758e55e2013-09-06 18:03:48 +000034//===----------------------------------------------------------------------===//
35// Stack of data-sharing attributes for variables
36//===----------------------------------------------------------------------===//
37
Alexey Bataeve3727102018-04-18 15:57:46 +000038static const Expr *checkMapClauseExpressionBase(
Alexey Bataevf47c4b42017-09-26 13:47:31 +000039 Sema &SemaRef, Expr *E,
40 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000041 OpenMPClauseKind CKind, bool NoDiagnose);
Alexey Bataevf47c4b42017-09-26 13:47:31 +000042
Alexey Bataev758e55e2013-09-06 18:03:48 +000043namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000044/// Default data sharing attributes, which can be applied to directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +000045enum DefaultDataSharingAttributes {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000046 DSA_unspecified = 0, /// Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// Default data sharing attribute 'none'.
48 DSA_shared = 1 << 1, /// Default data sharing attribute 'shared'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000049};
50
51/// Attributes of the defaultmap clause.
52enum DefaultMapAttributes {
53 DMA_unspecified, /// Default mapping is not specified.
54 DMA_tofrom_scalar, /// Default mapping is 'tofrom:scalar'.
Alexey Bataev758e55e2013-09-06 18:03:48 +000055};
Alexey Bataev7ff55242014-06-19 09:13:45 +000056
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>;
88 using AlignedMapTy = llvm::SmallDenseMap<const ValueDecl *, const Expr *, 8>;
89 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>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000118
Alexey Bataeve3727102018-04-18 15:57:46 +0000119 struct SharingMapTy {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000120 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000121 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000122 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000123 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000124 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000125 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000126 SourceLocation DefaultAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000127 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
128 SourceLocation DefaultMapAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000129 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000130 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000131 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000132 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000133 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
134 /// get the data (loop counters etc.) about enclosing loop-based construct.
135 /// This data is required during codegen.
136 DoacrossDependMapTy DoacrossDepends;
Patrick Lyster16471942019-02-06 18:18:02 +0000137 /// First argument (Expr *) contains optional argument of the
Alexey Bataev346265e2015-09-25 10:37:12 +0000138 /// 'ordered' clause, the second one is true if the regions has 'ordered'
139 /// clause, false otherwise.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000140 llvm::Optional<std::pair<const Expr *, OMPOrderedClause *>> OrderedRegion;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000141 unsigned AssociatedLoops = 1;
142 const Decl *PossiblyLoopCounter = nullptr;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000143 bool NowaitRegion = false;
144 bool CancelRegion = false;
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000145 bool LoopStart = false;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000146 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000147 /// Reference to the taskgroup task_reduction reference expression.
148 Expr *TaskgroupReductionRef = nullptr;
Patrick Lystere13b1e32019-01-02 19:28:48 +0000149 llvm::DenseSet<QualType> MappedClassesQualTypes;
Alexey Bataeva495c642019-03-11 19:51:42 +0000150 /// List of globals marked as declare target link in this target region
151 /// (isOpenMPTargetExecutionDirective(Directive) == true).
152 llvm::SmallVector<DeclRefExpr *, 4> DeclareTargetLinkVarDecls;
Alexey Bataeved09d242014-05-28 05:53:51 +0000153 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000154 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000155 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
156 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000157 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000158 };
159
Alexey Bataeve3727102018-04-18 15:57:46 +0000160 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000161
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000162 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000163 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000164 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
165 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000166 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000167 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000168 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000169 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000170 bool ForceCapturing = false;
Alexey Bataev60705422018-10-30 15:50:12 +0000171 /// true if all the vaiables in the target executable directives must be
172 /// captured by reference.
173 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000174 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000175
Alexey Bataeve3727102018-04-18 15:57:46 +0000176 using iterator = StackTy::const_reverse_iterator;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000177
Alexey Bataeve3727102018-04-18 15:57:46 +0000178 DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
Alexey Bataevec3da872014-01-31 05:15:34 +0000179
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000180 /// Checks if the variable is a local for OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000181 bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
Alexey Bataeved09d242014-05-28 05:53:51 +0000182
Alexey Bataev4b465392017-04-26 15:06:24 +0000183 bool isStackEmpty() const {
184 return Stack.empty() ||
185 Stack.back().second != CurrentNonCapturingFunctionScope ||
186 Stack.back().first.empty();
187 }
188
Kelvin Li1408f912018-09-26 04:28:39 +0000189 /// Vector of previously declared requires directives
190 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
Alexey Bataev27ef9512019-03-20 20:14:22 +0000191 /// omp_allocator_handle_t type.
192 QualType OMPAllocatorHandleT;
193 /// Expression for the predefined allocators.
194 Expr *OMPPredefinedAllocators[OMPAllocateDeclAttr::OMPUserDefinedMemAlloc] = {
195 nullptr};
Kelvin Li1408f912018-09-26 04:28:39 +0000196
Alexey Bataev758e55e2013-09-06 18:03:48 +0000197public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000198 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000199
Alexey Bataev27ef9512019-03-20 20:14:22 +0000200 /// Sets omp_allocator_handle_t type.
201 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
202 /// Gets omp_allocator_handle_t type.
203 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
204 /// Sets the given default allocator.
205 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
206 Expr *Allocator) {
207 OMPPredefinedAllocators[AllocatorKind] = Allocator;
208 }
209 /// Returns the specified default allocator.
210 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
211 return OMPPredefinedAllocators[AllocatorKind];
212 }
213
Alexey Bataevaac108a2015-06-23 04:51:00 +0000214 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000215 OpenMPClauseKind getClauseParsingMode() const {
216 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
217 return ClauseKindMode;
218 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000219 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000220
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000221 bool isForceVarCapturing() const { return ForceCapturing; }
222 void setForceVarCapturing(bool V) { ForceCapturing = V; }
223
Alexey Bataev60705422018-10-30 15:50:12 +0000224 void setForceCaptureByReferenceInTargetExecutable(bool V) {
225 ForceCaptureByReferenceInTargetExecutable = V;
226 }
227 bool isForceCaptureByReferenceInTargetExecutable() const {
228 return ForceCaptureByReferenceInTargetExecutable;
229 }
230
Alexey Bataev758e55e2013-09-06 18:03:48 +0000231 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000232 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000233 if (Stack.empty() ||
234 Stack.back().second != CurrentNonCapturingFunctionScope)
235 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
236 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
237 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000238 }
239
240 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000241 assert(!Stack.back().first.empty() &&
242 "Data-sharing attributes stack is empty!");
243 Stack.back().first.pop_back();
244 }
245
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000246 /// Marks that we're started loop parsing.
247 void loopInit() {
248 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
249 "Expected loop-based directive.");
250 Stack.back().first.back().LoopStart = true;
251 }
252 /// Start capturing of the variables in the loop context.
253 void loopStart() {
254 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
255 "Expected loop-based directive.");
256 Stack.back().first.back().LoopStart = false;
257 }
258 /// true, if variables are captured, false otherwise.
259 bool isLoopStarted() const {
260 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
261 "Expected loop-based directive.");
262 return !Stack.back().first.back().LoopStart;
263 }
264 /// Marks (or clears) declaration as possibly loop counter.
265 void resetPossibleLoopCounter(const Decl *D = nullptr) {
266 Stack.back().first.back().PossiblyLoopCounter =
267 D ? D->getCanonicalDecl() : D;
268 }
269 /// Gets the possible loop counter decl.
270 const Decl *getPossiblyLoopCunter() const {
271 return Stack.back().first.back().PossiblyLoopCounter;
272 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000273 /// Start new OpenMP region stack in new non-capturing function.
274 void pushFunction() {
275 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
276 assert(!isa<CapturingScopeInfo>(CurFnScope));
277 CurrentNonCapturingFunctionScope = CurFnScope;
278 }
279 /// Pop region stack for non-capturing function.
280 void popFunction(const FunctionScopeInfo *OldFSI) {
281 if (!Stack.empty() && Stack.back().second == OldFSI) {
282 assert(Stack.back().first.empty());
283 Stack.pop_back();
284 }
285 CurrentNonCapturingFunctionScope = nullptr;
286 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
287 if (!isa<CapturingScopeInfo>(FSI)) {
288 CurrentNonCapturingFunctionScope = FSI;
289 break;
290 }
291 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000292 }
293
Alexey Bataeve3727102018-04-18 15:57:46 +0000294 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000295 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000296 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000297 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000298 getCriticalWithHint(const DeclarationNameInfo &Name) const {
299 auto I = Criticals.find(Name.getAsString());
300 if (I != Criticals.end())
301 return I->second;
302 return std::make_pair(nullptr, llvm::APSInt());
303 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000304 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000305 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000306 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000307 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000308
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000309 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000310 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000311 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000312 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000313 /// \return The index of the loop control variable in the list of associated
314 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000315 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000316 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000317 /// parent region.
318 /// \return The index of the loop control variable in the list of associated
319 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000320 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000321 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000322 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000323 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000324
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000325 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000326 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000327 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000328
Alexey Bataevfa312f32017-07-21 18:48:21 +0000329 /// Adds additional information for the reduction items with the reduction id
330 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000331 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000332 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000333 /// Adds additional information for the reduction items with the reduction id
334 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000335 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000336 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000337 /// Returns the location and reduction operation from the innermost parent
338 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000339 const DSAVarData
340 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
341 BinaryOperatorKind &BOK,
342 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000343 /// Returns the location and reduction operation from the innermost parent
344 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000345 const DSAVarData
346 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
347 const Expr *&ReductionRef,
348 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000349 /// Return reduction reference expression for the current taskgroup.
350 Expr *getTaskgroupReductionRef() const {
351 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
352 "taskgroup reference expression requested for non taskgroup "
353 "directive.");
354 return Stack.back().first.back().TaskgroupReductionRef;
355 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000356 /// Checks if the given \p VD declaration is actually a taskgroup reduction
357 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000358 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Alexey Bataev88202be2017-07-27 13:20:36 +0000359 return Stack.back().first[Level].TaskgroupReductionRef &&
360 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
361 ->getDecl() == VD;
362 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000363
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000364 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000365 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000366 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000367 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000368 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000369 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000370 /// match specified \a CPred predicate in any directive which matches \a DPred
371 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000372 const DSAVarData
373 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
374 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
375 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000376 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000377 /// match specified \a CPred predicate in any innermost directive which
378 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000379 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000380 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000381 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
382 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000383 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000384 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000385 /// attributes which match specified \a CPred predicate at the specified
386 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000387 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000388 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000389 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000390
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000391 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000392 /// specified \a DPred predicate.
393 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000394 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000395 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000396
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000397 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000398 bool hasDirective(
399 const llvm::function_ref<bool(
400 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
401 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000402 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000403
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000404 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000405 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000406 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000407 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000408 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000409 OpenMPDirectiveKind getDirective(unsigned Level) const {
410 assert(!isStackEmpty() && "No directive at specified level.");
411 return Stack.back().first[Level].Directive;
412 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000413 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000414 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000415 if (isStackEmpty() || Stack.back().first.size() == 1)
416 return OMPD_unknown;
417 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000418 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000419
Kelvin Li1408f912018-09-26 04:28:39 +0000420 /// Add requires decl to internal vector
421 void addRequiresDecl(OMPRequiresDecl *RD) {
422 RequiresDecls.push_back(RD);
423 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000424
Kelvin Li1408f912018-09-26 04:28:39 +0000425 /// Checks for a duplicate clause amongst previously declared requires
426 /// directives
427 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
428 bool IsDuplicate = false;
429 for (OMPClause *CNew : ClauseList) {
430 for (const OMPRequiresDecl *D : RequiresDecls) {
431 for (const OMPClause *CPrev : D->clauselists()) {
432 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
433 SemaRef.Diag(CNew->getBeginLoc(),
434 diag::err_omp_requires_clause_redeclaration)
435 << getOpenMPClauseName(CNew->getClauseKind());
436 SemaRef.Diag(CPrev->getBeginLoc(),
437 diag::note_omp_requires_previous_clause)
438 << getOpenMPClauseName(CPrev->getClauseKind());
439 IsDuplicate = true;
440 }
441 }
442 }
443 }
444 return IsDuplicate;
445 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000446
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000447 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000448 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000449 assert(!isStackEmpty());
450 Stack.back().first.back().DefaultAttr = DSA_none;
451 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000452 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000453 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000454 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000455 assert(!isStackEmpty());
456 Stack.back().first.back().DefaultAttr = DSA_shared;
457 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000458 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000459 /// Set default data mapping attribute to 'tofrom:scalar'.
460 void setDefaultDMAToFromScalar(SourceLocation Loc) {
461 assert(!isStackEmpty());
462 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
463 Stack.back().first.back().DefaultMapAttrLoc = Loc;
464 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000465
466 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000467 return isStackEmpty() ? DSA_unspecified
468 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000469 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000470 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000471 return isStackEmpty() ? SourceLocation()
472 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000473 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000474 DefaultMapAttributes getDefaultDMA() const {
475 return isStackEmpty() ? DMA_unspecified
476 : Stack.back().first.back().DefaultMapAttr;
477 }
478 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
479 return Stack.back().first[Level].DefaultMapAttr;
480 }
481 SourceLocation getDefaultDMALocation() const {
482 return isStackEmpty() ? SourceLocation()
483 : Stack.back().first.back().DefaultMapAttrLoc;
484 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000485
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000486 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000487 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000488 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000489 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000490 }
491
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000492 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000493 void setOrderedRegion(bool IsOrdered, const Expr *Param,
494 OMPOrderedClause *Clause) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000495 assert(!isStackEmpty());
Alexey Bataevf138fda2018-08-13 19:04:24 +0000496 if (IsOrdered)
497 Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
498 else
499 Stack.back().first.back().OrderedRegion.reset();
500 }
501 /// Returns true, if region is ordered (has associated 'ordered' clause),
502 /// false - otherwise.
503 bool isOrderedRegion() const {
504 if (isStackEmpty())
505 return false;
506 return Stack.back().first.rbegin()->OrderedRegion.hasValue();
507 }
508 /// Returns optional parameter for the ordered region.
509 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
510 if (isStackEmpty() ||
511 !Stack.back().first.rbegin()->OrderedRegion.hasValue())
512 return std::make_pair(nullptr, nullptr);
513 return Stack.back().first.rbegin()->OrderedRegion.getValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000514 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000515 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000516 /// 'ordered' clause), false - otherwise.
517 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000518 if (isStackEmpty() || Stack.back().first.size() == 1)
519 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000520 return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000521 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000522 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000523 std::pair<const Expr *, OMPOrderedClause *>
524 getParentOrderedRegionParam() const {
525 if (isStackEmpty() || Stack.back().first.size() == 1 ||
526 !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
527 return std::make_pair(nullptr, nullptr);
528 return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
Alexey Bataev346265e2015-09-25 10:37:12 +0000529 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000530 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000531 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000532 assert(!isStackEmpty());
533 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000534 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000535 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000536 /// 'nowait' clause), false - otherwise.
537 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000538 if (isStackEmpty() || Stack.back().first.size() == 1)
539 return false;
540 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000541 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000542 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000543 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000544 if (!isStackEmpty() && Stack.back().first.size() > 1) {
545 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
546 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
547 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000548 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000549 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000550 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000551 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000552 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000553
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000554 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000555 void setAssociatedLoops(unsigned Val) {
556 assert(!isStackEmpty());
557 Stack.back().first.back().AssociatedLoops = Val;
558 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000559 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000560 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000561 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000562 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000563
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000564 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000565 /// region.
566 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000567 if (!isStackEmpty() && Stack.back().first.size() > 1) {
568 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
569 TeamsRegionLoc;
570 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000571 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000572 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000573 bool hasInnerTeamsRegion() const {
574 return getInnerTeamsRegionLoc().isValid();
575 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000576 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000577 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000578 return isStackEmpty() ? SourceLocation()
579 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000580 }
581
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000582 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000583 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000584 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000585 SourceLocation getConstructLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000586 return isStackEmpty() ? SourceLocation()
587 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000588 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000589
Samuel Antao4c8035b2016-12-12 18:00:20 +0000590 /// Do the check specified in \a Check to all component lists and return true
591 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000592 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000593 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000594 const llvm::function_ref<
595 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000596 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000597 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000598 if (isStackEmpty())
599 return false;
600 auto SI = Stack.back().first.rbegin();
601 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000602
603 if (SI == SE)
604 return false;
605
Alexey Bataeve3727102018-04-18 15:57:46 +0000606 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000607 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000608 else
609 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000610
611 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000612 auto MI = SI->MappedExprComponents.find(VD);
613 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000614 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
615 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000616 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000617 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000618 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000619 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000620 }
621
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000622 /// Do the check specified in \a Check to all component lists at a given level
623 /// and return true if any issue is found.
624 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000625 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000626 const llvm::function_ref<
627 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000628 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000629 Check) const {
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000630 if (isStackEmpty())
631 return false;
632
633 auto StartI = Stack.back().first.begin();
634 auto EndI = Stack.back().first.end();
635 if (std::distance(StartI, EndI) <= (int)Level)
636 return false;
637 std::advance(StartI, Level);
638
639 auto MI = StartI->MappedExprComponents.find(VD);
640 if (MI != StartI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000641 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
642 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000643 if (Check(L, MI->second.Kind))
644 return true;
645 return false;
646 }
647
Samuel Antao4c8035b2016-12-12 18:00:20 +0000648 /// Create a new mappable expression component list associated with a given
649 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000650 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000651 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000652 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
653 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000654 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000655 "Not expecting to retrieve components from a empty stack!");
Alexey Bataeve3727102018-04-18 15:57:46 +0000656 MappedExprComponentTy &MEC =
657 Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000658 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000659 MEC.Components.resize(MEC.Components.size() + 1);
660 MEC.Components.back().append(Components.begin(), Components.end());
661 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000662 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000663
664 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000665 assert(!isStackEmpty());
666 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000667 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000668 void addDoacrossDependClause(OMPDependClause *C,
669 const OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000670 assert(!isStackEmpty() && Stack.back().first.size() > 1);
Alexey Bataeve3727102018-04-18 15:57:46 +0000671 SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000672 assert(isOpenMPWorksharingDirective(StackElem.Directive));
Alexey Bataeve3727102018-04-18 15:57:46 +0000673 StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000674 }
675 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
676 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000677 assert(!isStackEmpty());
Alexey Bataeve3727102018-04-18 15:57:46 +0000678 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000679 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000680 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000681 return llvm::make_range(Ref.begin(), Ref.end());
682 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000683 return llvm::make_range(StackElem.DoacrossDepends.end(),
684 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000685 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000686
687 // Store types of classes which have been explicitly mapped
688 void addMappedClassesQualTypes(QualType QT) {
689 SharingMapTy &StackElem = Stack.back().first.back();
690 StackElem.MappedClassesQualTypes.insert(QT);
691 }
692
693 // Return set of mapped classes types
694 bool isClassPreviouslyMapped(QualType QT) const {
695 const SharingMapTy &StackElem = Stack.back().first.back();
696 return StackElem.MappedClassesQualTypes.count(QT) != 0;
697 }
698
Alexey Bataeva495c642019-03-11 19:51:42 +0000699 /// Adds global declare target to the parent target region.
700 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
701 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
702 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
703 "Expected declare target link global.");
704 if (isStackEmpty())
705 return;
706 auto It = Stack.back().first.rbegin();
707 while (It != Stack.back().first.rend() &&
708 !isOpenMPTargetExecutionDirective(It->Directive))
709 ++It;
710 if (It != Stack.back().first.rend()) {
711 assert(isOpenMPTargetExecutionDirective(It->Directive) &&
712 "Expected target executable directive.");
713 It->DeclareTargetLinkVarDecls.push_back(E);
714 }
715 }
716
717 /// Returns the list of globals with declare target link if current directive
718 /// is target.
719 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
720 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
721 "Expected target executable directive.");
722 return Stack.back().first.back().DeclareTargetLinkVarDecls;
723 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000724};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000725
726bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
727 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
728}
729
730bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
731 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000732}
Alexey Bataeve3727102018-04-18 15:57:46 +0000733
Alexey Bataeved09d242014-05-28 05:53:51 +0000734} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000735
Alexey Bataeve3727102018-04-18 15:57:46 +0000736static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000737 if (const auto *FE = dyn_cast<FullExpr>(E))
738 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000739
Alexey Bataeve3727102018-04-18 15:57:46 +0000740 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000741 E = MTE->GetTemporaryExpr();
742
Alexey Bataeve3727102018-04-18 15:57:46 +0000743 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000744 E = Binder->getSubExpr();
745
Alexey Bataeve3727102018-04-18 15:57:46 +0000746 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000747 E = ICE->getSubExprAsWritten();
748 return E->IgnoreParens();
749}
750
Alexey Bataeve3727102018-04-18 15:57:46 +0000751static Expr *getExprAsWritten(Expr *E) {
752 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
753}
754
755static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
756 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
757 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000758 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000759 const auto *VD = dyn_cast<VarDecl>(D);
760 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000761 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000762 VD = VD->getCanonicalDecl();
763 D = VD;
764 } else {
765 assert(FD);
766 FD = FD->getCanonicalDecl();
767 D = FD;
768 }
769 return D;
770}
771
Alexey Bataeve3727102018-04-18 15:57:46 +0000772static ValueDecl *getCanonicalDecl(ValueDecl *D) {
773 return const_cast<ValueDecl *>(
774 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
775}
776
777DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
778 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000779 D = getCanonicalDecl(D);
780 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000781 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000782 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000783 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000784 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
785 // in a region but not in construct]
786 // File-scope or namespace-scope variables referenced in called routines
787 // in the region are shared unless they appear in a threadprivate
788 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000789 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000790 DVar.CKind = OMPC_shared;
791
792 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
793 // in a region but not in construct]
794 // Variables with static storage duration that are declared in called
795 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000796 if (VD && VD->hasGlobalStorage())
797 DVar.CKind = OMPC_shared;
798
799 // Non-static data members are shared by default.
800 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000801 DVar.CKind = OMPC_shared;
802
Alexey Bataev758e55e2013-09-06 18:03:48 +0000803 return DVar;
804 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000805
Alexey Bataevec3da872014-01-31 05:15:34 +0000806 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
807 // in a Construct, C/C++, predetermined, p.1]
808 // Variables with automatic storage duration that are declared in a scope
809 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000810 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
811 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000812 DVar.CKind = OMPC_private;
813 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000814 }
815
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000816 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000817 // Explicitly specified attributes and local variables with predetermined
818 // attributes.
819 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000820 const DSAInfo &Data = Iter->SharingMap.lookup(D);
821 DVar.RefExpr = Data.RefExpr.getPointer();
822 DVar.PrivateCopy = Data.PrivateCopy;
823 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000824 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000825 return DVar;
826 }
827
828 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
829 // in a Construct, C/C++, implicitly determined, p.1]
830 // In a parallel or task construct, the data-sharing attributes of these
831 // variables are determined by the default clause, if present.
832 switch (Iter->DefaultAttr) {
833 case DSA_shared:
834 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000835 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000836 return DVar;
837 case DSA_none:
838 return DVar;
839 case DSA_unspecified:
840 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
841 // in a Construct, implicitly determined, p.2]
842 // In a parallel construct, if no default clause is present, these
843 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000844 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000845 if (isOpenMPParallelDirective(DVar.DKind) ||
846 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000847 DVar.CKind = OMPC_shared;
848 return DVar;
849 }
850
851 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
852 // in a Construct, implicitly determined, p.4]
853 // In a task construct, if no default clause is present, a variable that in
854 // the enclosing context is determined to be shared by all implicit tasks
855 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000856 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000857 DSAVarData DVarTemp;
Alexey Bataeve3727102018-04-18 15:57:46 +0000858 iterator I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000859 do {
860 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000861 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000862 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000863 // In a task construct, if no default clause is present, a variable
864 // whose data-sharing attribute is not determined by the rules above is
865 // firstprivate.
866 DVarTemp = getDSA(I, D);
867 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000868 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000869 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000870 return DVar;
871 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000872 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000873 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000874 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000875 return DVar;
876 }
877 }
878 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
879 // in a Construct, implicitly determined, p.3]
880 // For constructs other than task, if no default clause is present, these
881 // variables inherit their data-sharing attributes from the enclosing
882 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000883 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000884}
885
Alexey Bataeve3727102018-04-18 15:57:46 +0000886const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
887 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000888 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000889 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000890 SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000891 auto It = StackElem.AlignedMap.find(D);
892 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000893 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000894 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000895 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000896 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000897 assert(It->second && "Unexpected nullptr expr in the aligned map");
898 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000899}
900
Alexey Bataeve3727102018-04-18 15:57:46 +0000901void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000902 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000903 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000904 SharingMapTy &StackElem = Stack.back().first.back();
905 StackElem.LCVMap.try_emplace(
906 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +0000907}
908
Alexey Bataeve3727102018-04-18 15:57:46 +0000909const DSAStackTy::LCDeclInfo
910DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000911 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000912 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000913 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000914 auto It = StackElem.LCVMap.find(D);
915 if (It != StackElem.LCVMap.end())
916 return It->second;
917 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000918}
919
Alexey Bataeve3727102018-04-18 15:57:46 +0000920const DSAStackTy::LCDeclInfo
921DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000922 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
923 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000924 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000925 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000926 auto It = StackElem.LCVMap.find(D);
927 if (It != StackElem.LCVMap.end())
928 return It->second;
929 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000930}
931
Alexey Bataeve3727102018-04-18 15:57:46 +0000932const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000933 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
934 "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000935 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000936 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000937 return nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +0000938 for (const auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000939 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000940 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000941 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000942}
943
Alexey Bataeve3727102018-04-18 15:57:46 +0000944void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000945 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000946 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000947 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000948 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000949 Data.Attributes = A;
950 Data.RefExpr.setPointer(E);
951 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000952 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000953 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000954 DSAInfo &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000955 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
956 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
957 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
958 (isLoopControlVariable(D).first && A == OMPC_private));
959 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
960 Data.RefExpr.setInt(/*IntVal=*/true);
961 return;
962 }
963 const bool IsLastprivate =
964 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
965 Data.Attributes = A;
966 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
967 Data.PrivateCopy = PrivateCopy;
968 if (PrivateCopy) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000969 DSAInfo &Data =
970 Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000971 Data.Attributes = A;
972 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
973 Data.PrivateCopy = nullptr;
974 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000975 }
976}
977
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000978/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000979static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000980 StringRef Name, const AttrVec *Attrs = nullptr,
981 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000982 DeclContext *DC = SemaRef.CurContext;
983 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
984 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +0000985 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000986 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
987 if (Attrs) {
988 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
989 I != E; ++I)
990 Decl->addAttr(*I);
991 }
992 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000993 if (OrigRef) {
994 Decl->addAttr(
995 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
996 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000997 return Decl;
998}
999
1000static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1001 SourceLocation Loc,
1002 bool RefersToCapture = false) {
1003 D->setReferenced();
1004 D->markUsed(S.Context);
1005 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1006 SourceLocation(), D, RefersToCapture, Loc, Ty,
1007 VK_LValue);
1008}
1009
Alexey Bataeve3727102018-04-18 15:57:46 +00001010void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001011 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001012 D = getCanonicalDecl(D);
1013 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001014 assert(
Richard Trieu09f14112017-07-21 21:29:35 +00001015 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001016 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +00001017 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001018 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001019 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001020 "Additional reduction info may be specified only once for reduction "
1021 "items.");
1022 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001023 Expr *&TaskgroupReductionRef =
1024 Stack.back().first.back().TaskgroupReductionRef;
1025 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001026 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1027 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001028 TaskgroupReductionRef =
1029 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001030 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001031}
1032
Alexey Bataeve3727102018-04-18 15:57:46 +00001033void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001034 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001035 D = getCanonicalDecl(D);
1036 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001037 assert(
Richard Trieu09f14112017-07-21 21:29:35 +00001038 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001039 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +00001040 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001041 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001042 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001043 "Additional reduction info may be specified only once for reduction "
1044 "items.");
1045 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001046 Expr *&TaskgroupReductionRef =
1047 Stack.back().first.back().TaskgroupReductionRef;
1048 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001049 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1050 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001051 TaskgroupReductionRef =
1052 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001053 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001054}
1055
Alexey Bataeve3727102018-04-18 15:57:46 +00001056const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1057 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1058 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001059 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001060 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1061 if (Stack.back().first.empty())
1062 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001063 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1064 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001065 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001066 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001067 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001068 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001069 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001070 if (!ReductionData.ReductionOp ||
1071 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001072 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001073 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001074 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001075 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1076 "expression for the descriptor is not "
1077 "set.");
1078 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001079 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1080 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001081 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001082 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001083}
1084
Alexey Bataeve3727102018-04-18 15:57:46 +00001085const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1086 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1087 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001088 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001089 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1090 if (Stack.back().first.empty())
1091 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001092 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1093 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001094 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001095 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001096 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001097 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001098 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001099 if (!ReductionData.ReductionOp ||
1100 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001101 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001102 SR = ReductionData.ReductionRange;
1103 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001104 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1105 "expression for the descriptor is not "
1106 "set.");
1107 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001108 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1109 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001110 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001111 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001112}
1113
Alexey Bataeve3727102018-04-18 15:57:46 +00001114bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001115 D = D->getCanonicalDecl();
Alexey Bataev852525d2018-03-02 17:17:12 +00001116 if (!isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001117 iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001118 Scope *TopScope = nullptr;
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001119 while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) &&
Alexey Bataev852525d2018-03-02 17:17:12 +00001120 !isOpenMPTargetExecutionDirective(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +00001121 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +00001122 if (I == E)
1123 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001124 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001125 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001126 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +00001127 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +00001128 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001129 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001130 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001131}
1132
Joel E. Dennyd2649292019-01-04 22:11:56 +00001133static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1134 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001135 bool *IsClassType = nullptr) {
1136 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001137 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001138 bool IsConstant = Type.isConstant(Context);
1139 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001140 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1141 ? Type->getAsCXXRecordDecl()
1142 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001143 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1144 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1145 RD = CTD->getTemplatedDecl();
1146 if (IsClassType)
1147 *IsClassType = RD;
1148 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1149 RD->hasDefinition() && RD->hasMutableFields());
1150}
1151
Joel E. Dennyd2649292019-01-04 22:11:56 +00001152static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1153 QualType Type, OpenMPClauseKind CKind,
1154 SourceLocation ELoc,
1155 bool AcceptIfMutable = true,
1156 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001157 ASTContext &Context = SemaRef.getASTContext();
1158 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001159 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1160 unsigned Diag = ListItemNotVar
1161 ? diag::err_omp_const_list_item
1162 : IsClassType ? diag::err_omp_const_not_mutable_variable
1163 : diag::err_omp_const_variable;
1164 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1165 if (!ListItemNotVar && D) {
1166 const VarDecl *VD = dyn_cast<VarDecl>(D);
1167 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1168 VarDecl::DeclarationOnly;
1169 SemaRef.Diag(D->getLocation(),
1170 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1171 << D;
1172 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001173 return true;
1174 }
1175 return false;
1176}
1177
Alexey Bataeve3727102018-04-18 15:57:46 +00001178const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1179 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001180 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001181 DSAVarData DVar;
1182
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001183 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001184 auto TI = Threadprivates.find(D);
1185 if (TI != Threadprivates.end()) {
1186 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001187 DVar.CKind = OMPC_threadprivate;
1188 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001189 }
1190 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001191 DVar.RefExpr = buildDeclRefExpr(
1192 SemaRef, VD, D->getType().getNonReferenceType(),
1193 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1194 DVar.CKind = OMPC_threadprivate;
1195 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001196 return DVar;
1197 }
1198 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1199 // in a Construct, C/C++, predetermined, p.1]
1200 // Variables appearing in threadprivate directives are threadprivate.
1201 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1202 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1203 SemaRef.getLangOpts().OpenMPUseTLS &&
1204 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1205 (VD && VD->getStorageClass() == SC_Register &&
1206 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1207 DVar.RefExpr = buildDeclRefExpr(
1208 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1209 DVar.CKind = OMPC_threadprivate;
1210 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1211 return DVar;
1212 }
1213 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1214 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1215 !isLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001216 iterator IterTarget =
Alexey Bataev852525d2018-03-02 17:17:12 +00001217 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
1218 [](const SharingMapTy &Data) {
1219 return isOpenMPTargetExecutionDirective(Data.Directive);
1220 });
1221 if (IterTarget != Stack.back().first.rend()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001222 iterator ParentIterTarget = std::next(IterTarget, 1);
1223 for (iterator Iter = Stack.back().first.rbegin();
1224 Iter != ParentIterTarget; std::advance(Iter, 1)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001225 if (isOpenMPLocal(VD, Iter)) {
1226 DVar.RefExpr =
1227 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1228 D->getLocation());
1229 DVar.CKind = OMPC_threadprivate;
1230 return DVar;
1231 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001232 }
1233 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1234 auto DSAIter = IterTarget->SharingMap.find(D);
1235 if (DSAIter != IterTarget->SharingMap.end() &&
1236 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1237 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1238 DVar.CKind = OMPC_threadprivate;
1239 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001240 }
1241 iterator End = Stack.back().first.rend();
1242 if (!SemaRef.isOpenMPCapturedByRef(
1243 D, std::distance(ParentIterTarget, End))) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001244 DVar.RefExpr =
1245 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1246 IterTarget->ConstructLoc);
1247 DVar.CKind = OMPC_threadprivate;
1248 return DVar;
1249 }
1250 }
1251 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001252 }
1253
Alexey Bataev4b465392017-04-26 15:06:24 +00001254 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001255 // Not in OpenMP execution region and top scope was already checked.
1256 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001257
Alexey Bataev758e55e2013-09-06 18:03:48 +00001258 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001259 // in a Construct, C/C++, predetermined, p.4]
1260 // Static data members are shared.
1261 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1262 // in a Construct, C/C++, predetermined, p.7]
1263 // Variables with static storage duration that are declared in a scope
1264 // inside the construct are shared.
Alexey Bataeve3727102018-04-18 15:57:46 +00001265 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001266 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001267 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001268 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +00001269 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001270
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001271 DVar.CKind = OMPC_shared;
1272 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001273 }
1274
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001275 // The predetermined shared attribute for const-qualified types having no
1276 // mutable members was removed after OpenMP 3.1.
1277 if (SemaRef.LangOpts.OpenMP <= 31) {
1278 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1279 // in a Construct, C/C++, predetermined, p.6]
1280 // Variables with const qualified type having no mutable member are
1281 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001282 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001283 // Variables with const-qualified type having no mutable member may be
1284 // listed in a firstprivate clause, even if they are static data members.
1285 DSAVarData DVarTemp = hasInnermostDSA(
1286 D,
1287 [](OpenMPClauseKind C) {
1288 return C == OMPC_firstprivate || C == OMPC_shared;
1289 },
1290 MatchesAlways, FromParent);
1291 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1292 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001293
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001294 DVar.CKind = OMPC_shared;
1295 return DVar;
1296 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001297 }
1298
Alexey Bataev758e55e2013-09-06 18:03:48 +00001299 // Explicitly specified attributes and local variables with predetermined
1300 // attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +00001301 iterator I = Stack.back().first.rbegin();
1302 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001303 if (FromParent && I != EndI)
1304 std::advance(I, 1);
Alexey Bataeve3727102018-04-18 15:57:46 +00001305 auto It = I->SharingMap.find(D);
1306 if (It != I->SharingMap.end()) {
1307 const DSAInfo &Data = It->getSecond();
1308 DVar.RefExpr = Data.RefExpr.getPointer();
1309 DVar.PrivateCopy = Data.PrivateCopy;
1310 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001311 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001312 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001313 }
1314
1315 return DVar;
1316}
1317
Alexey Bataeve3727102018-04-18 15:57:46 +00001318const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1319 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001320 if (isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001321 iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001322 return getDSA(I, D);
1323 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001324 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001325 iterator StartI = Stack.back().first.rbegin();
1326 iterator EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001327 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001328 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001329 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001330}
1331
Alexey Bataeve3727102018-04-18 15:57:46 +00001332const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001333DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001334 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1335 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001336 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001337 if (isStackEmpty())
1338 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001339 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001340 iterator I = Stack.back().first.rbegin();
1341 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001342 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001343 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001344 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001345 if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001346 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001347 iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001348 DSAVarData DVar = getDSA(NewI, D);
1349 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001350 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001351 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001352 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001353}
1354
Alexey Bataeve3727102018-04-18 15:57:46 +00001355const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001356 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1357 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001358 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001359 if (isStackEmpty())
1360 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001361 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001362 iterator StartI = Stack.back().first.rbegin();
1363 iterator EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001364 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001365 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001366 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001367 return {};
Alexey Bataeve3727102018-04-18 15:57:46 +00001368 iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001369 DSAVarData DVar = getDSA(NewI, D);
1370 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001371}
1372
Alexey Bataevaac108a2015-06-23 04:51:00 +00001373bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001374 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1375 unsigned Level, bool NotLastprivate) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001376 if (isStackEmpty())
1377 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001378 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001379 auto StartI = Stack.back().first.begin();
1380 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001381 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001382 return false;
1383 std::advance(StartI, Level);
Alexey Bataeve3727102018-04-18 15:57:46 +00001384 auto I = StartI->SharingMap.find(D);
Alexey Bataev92b33652018-11-21 19:41:10 +00001385 if ((I != StartI->SharingMap.end()) &&
Alexey Bataeve3727102018-04-18 15:57:46 +00001386 I->getSecond().RefExpr.getPointer() &&
1387 CPred(I->getSecond().Attributes) &&
Alexey Bataev92b33652018-11-21 19:41:10 +00001388 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1389 return true;
1390 // Check predetermined rules for the loop control variables.
1391 auto LI = StartI->LCVMap.find(D);
1392 if (LI != StartI->LCVMap.end())
1393 return CPred(OMPC_private);
1394 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001395}
1396
Samuel Antao4be30e92015-10-02 17:14:03 +00001397bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001398 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1399 unsigned Level) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001400 if (isStackEmpty())
1401 return false;
1402 auto StartI = Stack.back().first.begin();
1403 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001404 if (std::distance(StartI, EndI) <= (int)Level)
1405 return false;
1406 std::advance(StartI, Level);
1407 return DPred(StartI->Directive);
1408}
1409
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001410bool DSAStackTy::hasDirective(
1411 const llvm::function_ref<bool(OpenMPDirectiveKind,
1412 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001413 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001414 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001415 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001416 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001417 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001418 auto StartI = std::next(Stack.back().first.rbegin());
1419 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001420 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001421 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001422 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1423 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1424 return true;
1425 }
1426 return false;
1427}
1428
Alexey Bataev758e55e2013-09-06 18:03:48 +00001429void Sema::InitDataSharingAttributesStack() {
1430 VarDataSharingAttributesStack = new DSAStackTy(*this);
1431}
1432
1433#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1434
Alexey Bataev4b465392017-04-26 15:06:24 +00001435void Sema::pushOpenMPFunctionRegion() {
1436 DSAStack->pushFunction();
1437}
1438
1439void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1440 DSAStack->popFunction(OldFSI);
1441}
1442
Alexey Bataevc416e642019-02-08 18:02:25 +00001443static bool isOpenMPDeviceDelayedContext(Sema &S) {
1444 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1445 "Expected OpenMP device compilation.");
1446 return !S.isInOpenMPTargetExecutionDirective() &&
1447 !S.isInOpenMPDeclareTargetContext();
1448}
1449
1450/// Do we know that we will eventually codegen the given function?
1451static bool isKnownEmitted(Sema &S, FunctionDecl *FD) {
1452 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1453 "Expected OpenMP device compilation.");
1454 // Templates are emitted when they're instantiated.
1455 if (FD->isDependentContext())
1456 return false;
1457
1458 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1459 FD->getCanonicalDecl()))
1460 return true;
1461
1462 // Otherwise, the function is known-emitted if it's in our set of
1463 // known-emitted functions.
1464 return S.DeviceKnownEmittedFns.count(FD) > 0;
1465}
1466
1467Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1468 unsigned DiagID) {
1469 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1470 "Expected OpenMP device compilation.");
1471 return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) &&
1472 !isKnownEmitted(*this, getCurFunctionDecl()))
1473 ? DeviceDiagBuilder::K_Deferred
1474 : DeviceDiagBuilder::K_Immediate,
1475 Loc, DiagID, getCurFunctionDecl(), *this);
1476}
1477
1478void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) {
1479 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1480 "Expected OpenMP device compilation.");
1481 assert(Callee && "Callee may not be null.");
1482 FunctionDecl *Caller = getCurFunctionDecl();
1483
1484 // If the caller is known-emitted, mark the callee as known-emitted.
1485 // Otherwise, mark the call in our call graph so we can traverse it later.
1486 if (!isOpenMPDeviceDelayedContext(*this) ||
1487 (Caller && isKnownEmitted(*this, Caller)))
1488 markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted);
1489 else if (Caller)
1490 DeviceCallGraph[Caller].insert({Callee, Loc});
1491}
1492
Alexey Bataev123ad192019-02-27 20:29:45 +00001493void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1494 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1495 "OpenMP device compilation mode is expected.");
1496 QualType Ty = E->getType();
1497 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
1498 (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
1499 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1500 !Context.getTargetInfo().hasInt128Type()))
1501 targetDiag(E->getExprLoc(), diag::err_type_unsupported)
1502 << Ty << E->getSourceRange();
1503}
1504
Alexey Bataeve3727102018-04-18 15:57:46 +00001505bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001506 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1507
Alexey Bataeve3727102018-04-18 15:57:46 +00001508 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001509 bool IsByRef = true;
1510
1511 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001512 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001513 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001514
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001515 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001516 // This table summarizes how a given variable should be passed to the device
1517 // given its type and the clauses where it appears. This table is based on
1518 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1519 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1520 //
1521 // =========================================================================
1522 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1523 // | |(tofrom:scalar)| | pvt | | | |
1524 // =========================================================================
1525 // | scl | | | | - | | bycopy|
1526 // | scl | | - | x | - | - | bycopy|
1527 // | scl | | x | - | - | - | null |
1528 // | scl | x | | | - | | byref |
1529 // | scl | x | - | x | - | - | bycopy|
1530 // | scl | x | x | - | - | - | null |
1531 // | scl | | - | - | - | x | byref |
1532 // | scl | x | - | - | - | x | byref |
1533 //
1534 // | agg | n.a. | | | - | | byref |
1535 // | agg | n.a. | - | x | - | - | byref |
1536 // | agg | n.a. | x | - | - | - | null |
1537 // | agg | n.a. | - | - | - | x | byref |
1538 // | agg | n.a. | - | - | - | x[] | byref |
1539 //
1540 // | ptr | n.a. | | | - | | bycopy|
1541 // | ptr | n.a. | - | x | - | - | bycopy|
1542 // | ptr | n.a. | x | - | - | - | null |
1543 // | ptr | n.a. | - | - | - | x | byref |
1544 // | ptr | n.a. | - | - | - | x[] | bycopy|
1545 // | ptr | n.a. | - | - | x | | bycopy|
1546 // | ptr | n.a. | - | - | x | x | bycopy|
1547 // | ptr | n.a. | - | - | x | x[] | bycopy|
1548 // =========================================================================
1549 // Legend:
1550 // scl - scalar
1551 // ptr - pointer
1552 // agg - aggregate
1553 // x - applies
1554 // - - invalid in this combination
1555 // [] - mapped with an array section
1556 // byref - should be mapped by reference
1557 // byval - should be mapped by value
1558 // null - initialize a local variable to null on the device
1559 //
1560 // Observations:
1561 // - All scalar declarations that show up in a map clause have to be passed
1562 // by reference, because they may have been mapped in the enclosing data
1563 // environment.
1564 // - If the scalar value does not fit the size of uintptr, it has to be
1565 // passed by reference, regardless the result in the table above.
1566 // - For pointers mapped by value that have either an implicit map or an
1567 // array section, the runtime library may pass the NULL value to the
1568 // device instead of the value passed to it by the compiler.
1569
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001570 if (Ty->isReferenceType())
1571 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001572
1573 // Locate map clauses and see if the variable being captured is referred to
1574 // in any of those clauses. Here we only care about variables, not fields,
1575 // because fields are part of aggregates.
1576 bool IsVariableUsedInMapClause = false;
1577 bool IsVariableAssociatedWithSection = false;
1578
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001579 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001580 D, Level,
1581 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1582 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001583 MapExprComponents,
1584 OpenMPClauseKind WhereFoundClauseKind) {
1585 // Only the map clause information influences how a variable is
1586 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001587 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001588 if (WhereFoundClauseKind != OMPC_map)
1589 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001590
1591 auto EI = MapExprComponents.rbegin();
1592 auto EE = MapExprComponents.rend();
1593
1594 assert(EI != EE && "Invalid map expression!");
1595
1596 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1597 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1598
1599 ++EI;
1600 if (EI == EE)
1601 return false;
1602
1603 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1604 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1605 isa<MemberExpr>(EI->getAssociatedExpression())) {
1606 IsVariableAssociatedWithSection = true;
1607 // There is nothing more we need to know about this variable.
1608 return true;
1609 }
1610
1611 // Keep looking for more map info.
1612 return false;
1613 });
1614
1615 if (IsVariableUsedInMapClause) {
1616 // If variable is identified in a map clause it is always captured by
1617 // reference except if it is a pointer that is dereferenced somehow.
1618 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1619 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001620 // By default, all the data that has a scalar type is mapped by copy
1621 // (except for reduction variables).
1622 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001623 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1624 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001625 !Ty->isScalarType() ||
1626 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1627 DSAStack->hasExplicitDSA(
1628 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001629 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001630 }
1631
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001632 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001633 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001634 ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1635 !Ty->isAnyPointerType()) ||
1636 !DSAStack->hasExplicitDSA(
1637 D,
1638 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1639 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001640 // If the variable is artificial and must be captured by value - try to
1641 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001642 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1643 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001644 }
1645
Samuel Antao86ace552016-04-27 22:40:57 +00001646 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001647 // and alignment, because the runtime library only deals with uintptr types.
1648 // If it does not fit the uintptr size, we need to pass the data by reference
1649 // instead.
1650 if (!IsByRef &&
1651 (Ctx.getTypeSizeInChars(Ty) >
1652 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001653 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001654 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001655 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001656
1657 return IsByRef;
1658}
1659
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001660unsigned Sema::getOpenMPNestingLevel() const {
1661 assert(getLangOpts().OpenMP);
1662 return DSAStack->getNestingLevel();
1663}
1664
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001665bool Sema::isInOpenMPTargetExecutionDirective() const {
1666 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1667 !DSAStack->isClauseParsingMode()) ||
1668 DSAStack->hasDirective(
1669 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1670 SourceLocation) -> bool {
1671 return isOpenMPTargetExecutionDirective(K);
1672 },
1673 false);
1674}
1675
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001676VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001677 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001678 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001679
1680 // If we are attempting to capture a global variable in a directive with
1681 // 'target' we return true so that this global is also mapped to the device.
1682 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001683 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001684 if (VD && !VD->hasLocalStorage()) {
1685 if (isInOpenMPDeclareTargetContext() &&
1686 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1687 // Try to mark variable as declare target if it is used in capturing
1688 // regions.
Alexey Bataev97b72212018-08-14 18:31:20 +00001689 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001690 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001691 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001692 } else if (isInOpenMPTargetExecutionDirective()) {
1693 // If the declaration is enclosed in a 'declare target' directive,
1694 // then it should not be captured.
1695 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001696 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001697 return nullptr;
1698 return VD;
1699 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001700 }
Alexey Bataev60705422018-10-30 15:50:12 +00001701 // Capture variables captured by reference in lambdas for target-based
1702 // directives.
1703 if (VD && !DSAStack->isClauseParsingMode()) {
1704 if (const auto *RD = VD->getType()
1705 .getCanonicalType()
1706 .getNonReferenceType()
1707 ->getAsCXXRecordDecl()) {
1708 bool SavedForceCaptureByReferenceInTargetExecutable =
1709 DSAStack->isForceCaptureByReferenceInTargetExecutable();
1710 DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
Alexey Bataevd1840e52018-11-16 21:13:33 +00001711 if (RD->isLambda()) {
1712 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
1713 FieldDecl *ThisCapture;
1714 RD->getCaptureFields(Captures, ThisCapture);
Alexey Bataev60705422018-10-30 15:50:12 +00001715 for (const LambdaCapture &LC : RD->captures()) {
1716 if (LC.getCaptureKind() == LCK_ByRef) {
1717 VarDecl *VD = LC.getCapturedVar();
1718 DeclContext *VDC = VD->getDeclContext();
1719 if (!VDC->Encloses(CurContext))
1720 continue;
1721 DSAStackTy::DSAVarData DVarPrivate =
1722 DSAStack->getTopDSA(VD, /*FromParent=*/false);
1723 // Do not capture already captured variables.
1724 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
1725 DVarPrivate.CKind == OMPC_unknown &&
1726 !DSAStack->checkMappableExprComponentListsForDecl(
1727 D, /*CurrentRegionOnly=*/true,
1728 [](OMPClauseMappableExprCommon::
1729 MappableExprComponentListRef,
1730 OpenMPClauseKind) { return true; }))
1731 MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
1732 } else if (LC.getCaptureKind() == LCK_This) {
Alexey Bataevd1840e52018-11-16 21:13:33 +00001733 QualType ThisTy = getCurrentThisType();
1734 if (!ThisTy.isNull() &&
1735 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
1736 CheckCXXThisCapture(LC.getLocation());
Alexey Bataev60705422018-10-30 15:50:12 +00001737 }
1738 }
Alexey Bataevd1840e52018-11-16 21:13:33 +00001739 }
Alexey Bataev60705422018-10-30 15:50:12 +00001740 DSAStack->setForceCaptureByReferenceInTargetExecutable(
1741 SavedForceCaptureByReferenceInTargetExecutable);
1742 }
1743 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001744
Alexey Bataev48977c32015-08-04 08:10:48 +00001745 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1746 (!DSAStack->isClauseParsingMode() ||
1747 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001748 auto &&Info = DSAStack->isLoopControlVariable(D);
1749 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001750 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001751 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001752 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001753 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001754 DSAStackTy::DSAVarData DVarPrivate =
1755 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001756 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001757 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001758 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1759 [](OpenMPDirectiveKind) { return true; },
1760 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001761 if (DVarPrivate.CKind != OMPC_unknown)
1762 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001763 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001764 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001765}
1766
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001767void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1768 unsigned Level) const {
1769 SmallVector<OpenMPDirectiveKind, 4> Regions;
1770 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1771 FunctionScopesIndex -= Regions.size();
1772}
1773
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001774void Sema::startOpenMPLoop() {
1775 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1776 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1777 DSAStack->loopInit();
1778}
1779
Alexey Bataeve3727102018-04-18 15:57:46 +00001780bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001781 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001782 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1783 if (DSAStack->getAssociatedLoops() > 0 &&
1784 !DSAStack->isLoopStarted()) {
1785 DSAStack->resetPossibleLoopCounter(D);
1786 DSAStack->loopStart();
1787 return true;
1788 }
1789 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1790 DSAStack->isLoopControlVariable(D).first) &&
1791 !DSAStack->hasExplicitDSA(
1792 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1793 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
1794 return true;
1795 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00001796 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001797 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001798 (DSAStack->isClauseParsingMode() &&
1799 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001800 // Consider taskgroup reduction descriptor variable a private to avoid
1801 // possible capture in the region.
1802 (DSAStack->hasExplicitDirective(
1803 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1804 Level) &&
1805 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001806}
1807
Alexey Bataeve3727102018-04-18 15:57:46 +00001808void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1809 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001810 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1811 D = getCanonicalDecl(D);
1812 OpenMPClauseKind OMPC = OMPC_unknown;
1813 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1814 const unsigned NewLevel = I - 1;
1815 if (DSAStack->hasExplicitDSA(D,
1816 [&OMPC](const OpenMPClauseKind K) {
1817 if (isOpenMPPrivate(K)) {
1818 OMPC = K;
1819 return true;
1820 }
1821 return false;
1822 },
1823 NewLevel))
1824 break;
1825 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1826 D, NewLevel,
1827 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1828 OpenMPClauseKind) { return true; })) {
1829 OMPC = OMPC_map;
1830 break;
1831 }
1832 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1833 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001834 OMPC = OMPC_map;
1835 if (D->getType()->isScalarType() &&
1836 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1837 DefaultMapAttributes::DMA_tofrom_scalar)
1838 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001839 break;
1840 }
1841 }
1842 if (OMPC != OMPC_unknown)
1843 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1844}
1845
Alexey Bataeve3727102018-04-18 15:57:46 +00001846bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1847 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00001848 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1849 // Return true if the current level is no longer enclosed in a target region.
1850
Alexey Bataeve3727102018-04-18 15:57:46 +00001851 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001852 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001853 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1854 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001855}
1856
Alexey Bataeved09d242014-05-28 05:53:51 +00001857void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001858
1859void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1860 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001861 Scope *CurScope, SourceLocation Loc) {
1862 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001863 PushExpressionEvaluationContext(
1864 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001865}
1866
Alexey Bataevaac108a2015-06-23 04:51:00 +00001867void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1868 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001869}
1870
Alexey Bataevaac108a2015-06-23 04:51:00 +00001871void Sema::EndOpenMPClause() {
1872 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001873}
1874
Alexey Bataev758e55e2013-09-06 18:03:48 +00001875void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001876 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1877 // A variable of class type (or array thereof) that appears in a lastprivate
1878 // clause requires an accessible, unambiguous default constructor for the
1879 // class type, unless the list item is also specified in a firstprivate
1880 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001881 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1882 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001883 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1884 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00001885 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001886 if (DE->isValueDependent() || DE->isTypeDependent()) {
1887 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001888 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001889 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001890 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00001891 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00001892 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00001893 const DSAStackTy::DSAVarData DVar =
1894 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001895 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001896 // Generate helper private variable and initialize it with the
1897 // default value. The address of the original variable is replaced
1898 // by the address of the new private variable in CodeGen. This new
1899 // variable is not added to IdResolver, so the code in the OpenMP
1900 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00001901 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001902 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001903 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00001904 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001905 if (VDPrivate->isInvalidDecl())
1906 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001907 PrivateCopies.push_back(buildDeclRefExpr(
1908 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001909 } else {
1910 // The variable is also a firstprivate, so initialization sequence
1911 // for private copy is generated already.
1912 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001913 }
1914 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001915 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001916 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001917 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001918 }
1919 }
1920 }
1921
Alexey Bataev758e55e2013-09-06 18:03:48 +00001922 DSAStack->pop();
1923 DiscardCleanupsInEvaluationContext();
1924 PopExpressionEvaluationContext();
1925}
1926
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001927static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1928 Expr *NumIterations, Sema &SemaRef,
1929 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001930
Alexey Bataeva769e072013-03-22 06:34:35 +00001931namespace {
1932
Alexey Bataeve3727102018-04-18 15:57:46 +00001933class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001934private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001935 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001936
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001937public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001938 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001939 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001940 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00001941 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001942 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001943 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1944 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001945 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001946 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001947 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001948};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001949
Alexey Bataeve3727102018-04-18 15:57:46 +00001950class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001951private:
1952 Sema &SemaRef;
1953
1954public:
1955 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1956 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1957 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001958 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
1959 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001960 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1961 SemaRef.getCurScope());
1962 }
1963 return false;
1964 }
1965};
1966
Alexey Bataeved09d242014-05-28 05:53:51 +00001967} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001968
1969ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1970 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001971 const DeclarationNameInfo &Id,
1972 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001973 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1974 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1975
1976 if (Lookup.isAmbiguous())
1977 return ExprError();
1978
1979 VarDecl *VD;
1980 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001981 if (TypoCorrection Corrected = CorrectTypo(
1982 Id, LookupOrdinaryName, CurScope, nullptr,
1983 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001984 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001985 PDiag(Lookup.empty()
1986 ? diag::err_undeclared_var_use_suggest
1987 : diag::err_omp_expected_var_arg_suggest)
1988 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001989 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001990 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001991 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1992 : diag::err_omp_expected_var_arg)
1993 << Id.getName();
1994 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001995 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001996 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1997 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1998 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1999 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002000 }
2001 Lookup.suppressDiagnostics();
2002
2003 // OpenMP [2.9.2, Syntax, C/C++]
2004 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002005 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002006 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002007 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002008 bool IsDecl =
2009 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002010 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002011 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2012 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002013 return ExprError();
2014 }
2015
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002016 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002017 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002018 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2019 // A threadprivate directive for file-scope variables must appear outside
2020 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002021 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2022 !getCurLexicalContext()->isTranslationUnit()) {
2023 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002024 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002025 bool IsDecl =
2026 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2027 Diag(VD->getLocation(),
2028 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2029 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002030 return ExprError();
2031 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002032 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2033 // A threadprivate directive for static class member variables must appear
2034 // in the class definition, in the same scope in which the member
2035 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002036 if (CanonicalVD->isStaticDataMember() &&
2037 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2038 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002039 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002040 bool IsDecl =
2041 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2042 Diag(VD->getLocation(),
2043 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2044 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002045 return ExprError();
2046 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002047 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2048 // A threadprivate directive for namespace-scope variables must appear
2049 // outside any definition or declaration other than the namespace
2050 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002051 if (CanonicalVD->getDeclContext()->isNamespace() &&
2052 (!getCurLexicalContext()->isFileContext() ||
2053 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2054 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002055 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002056 bool IsDecl =
2057 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2058 Diag(VD->getLocation(),
2059 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2060 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002061 return ExprError();
2062 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002063 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2064 // A threadprivate directive for static block-scope variables must appear
2065 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002066 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002067 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002068 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002069 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002070 bool IsDecl =
2071 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2072 Diag(VD->getLocation(),
2073 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2074 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002075 return ExprError();
2076 }
2077
2078 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2079 // A threadprivate directive must lexically precede all references to any
2080 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002081 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2082 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002083 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002084 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002085 return ExprError();
2086 }
2087
2088 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002089 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2090 SourceLocation(), VD,
2091 /*RefersToEnclosingVariableOrCapture=*/false,
2092 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002093}
2094
Alexey Bataeved09d242014-05-28 05:53:51 +00002095Sema::DeclGroupPtrTy
2096Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2097 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002098 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002099 CurContext->addDecl(D);
2100 return DeclGroupPtrTy::make(DeclGroupRef(D));
2101 }
David Blaikie0403cb12016-01-15 23:43:25 +00002102 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002103}
2104
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002105namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002106class LocalVarRefChecker final
2107 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002108 Sema &SemaRef;
2109
2110public:
2111 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002112 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002113 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002114 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002115 diag::err_omp_local_var_in_threadprivate_init)
2116 << E->getSourceRange();
2117 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2118 << VD << VD->getSourceRange();
2119 return true;
2120 }
2121 }
2122 return false;
2123 }
2124 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002125 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002126 if (Child && Visit(Child))
2127 return true;
2128 }
2129 return false;
2130 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002131 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002132};
2133} // namespace
2134
Alexey Bataeved09d242014-05-28 05:53:51 +00002135OMPThreadPrivateDecl *
2136Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002137 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002138 for (Expr *RefExpr : VarList) {
2139 auto *DE = cast<DeclRefExpr>(RefExpr);
2140 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002141 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002142
Alexey Bataev376b4a42016-02-09 09:41:09 +00002143 // Mark variable as used.
2144 VD->setReferenced();
2145 VD->markUsed(Context);
2146
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002147 QualType QType = VD->getType();
2148 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2149 // It will be analyzed later.
2150 Vars.push_back(DE);
2151 continue;
2152 }
2153
Alexey Bataeva769e072013-03-22 06:34:35 +00002154 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2155 // A threadprivate variable must not have an incomplete type.
2156 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002157 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002158 continue;
2159 }
2160
2161 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2162 // A threadprivate variable must not have a reference type.
2163 if (VD->getType()->isReferenceType()) {
2164 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002165 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2166 bool IsDecl =
2167 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2168 Diag(VD->getLocation(),
2169 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2170 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002171 continue;
2172 }
2173
Samuel Antaof8b50122015-07-13 22:54:53 +00002174 // Check if this is a TLS variable. If TLS is not being supported, produce
2175 // the corresponding diagnostic.
2176 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2177 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2178 getLangOpts().OpenMPUseTLS &&
2179 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002180 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2181 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002182 Diag(ILoc, diag::err_omp_var_thread_local)
2183 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002184 bool IsDecl =
2185 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2186 Diag(VD->getLocation(),
2187 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2188 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002189 continue;
2190 }
2191
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002192 // Check if initial value of threadprivate variable reference variable with
2193 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002194 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002195 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002196 if (Checker.Visit(Init))
2197 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002198 }
2199
Alexey Bataeved09d242014-05-28 05:53:51 +00002200 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002201 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002202 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2203 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002204 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002205 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002206 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002207 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002208 if (!Vars.empty()) {
2209 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2210 Vars);
2211 D->setAccess(AS_public);
2212 }
2213 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002214}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002215
Alexey Bataev27ef9512019-03-20 20:14:22 +00002216static OMPAllocateDeclAttr::AllocatorTypeTy
2217getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2218 if (!Allocator)
2219 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2220 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2221 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002222 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002223 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002224 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2225 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2226 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2227 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
2228 Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002229 const Expr *AE = Allocator->IgnoreParenImpCasts();
2230 llvm::FoldingSetNodeID AEId, DAEId;
2231 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2232 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2233 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002234 AllocatorKindRes = AllocatorKind;
2235 break;
2236 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002237 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002238 return AllocatorKindRes;
2239}
2240
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002241Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2242 SourceLocation Loc, ArrayRef<Expr *> VarList,
2243 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2244 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2245 Expr *Allocator = nullptr;
2246 if (!Clauses.empty())
2247 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002248 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2249 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002250 SmallVector<Expr *, 8> Vars;
2251 for (Expr *RefExpr : VarList) {
2252 auto *DE = cast<DeclRefExpr>(RefExpr);
2253 auto *VD = cast<VarDecl>(DE->getDecl());
2254
2255 // Check if this is a TLS variable or global register.
2256 if (VD->getTLSKind() != VarDecl::TLS_None ||
2257 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2258 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2259 !VD->isLocalVarDecl()))
2260 continue;
2261 // Do not apply for parameters.
2262 if (isa<ParmVarDecl>(VD))
2263 continue;
2264
Alexey Bataev282555a2019-03-19 20:33:44 +00002265 // If the used several times in the allocate directive, the same allocator
2266 // must be used.
2267 if (VD->hasAttr<OMPAllocateDeclAttr>()) {
2268 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002269 Expr *PrevAllocator = A->getAllocator();
2270 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2271 getAllocatorKind(*this, DSAStack, PrevAllocator);
2272 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2273 if (AllocatorsMatch && Allocator && PrevAllocator) {
Alexey Bataev282555a2019-03-19 20:33:44 +00002274 const Expr *AE = Allocator->IgnoreParenImpCasts();
2275 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2276 llvm::FoldingSetNodeID AEId, PAEId;
2277 AE->Profile(AEId, Context, /*Canonical=*/true);
2278 PAE->Profile(PAEId, Context, /*Canonical=*/true);
2279 AllocatorsMatch = AEId == PAEId;
Alexey Bataev282555a2019-03-19 20:33:44 +00002280 }
2281 if (!AllocatorsMatch) {
2282 SmallString<256> AllocatorBuffer;
2283 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2284 if (Allocator)
2285 Allocator->printPretty(AllocatorStream, nullptr, getPrintingPolicy());
2286 SmallString<256> PrevAllocatorBuffer;
2287 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2288 if (PrevAllocator)
2289 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2290 getPrintingPolicy());
2291
2292 SourceLocation AllocatorLoc =
2293 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2294 SourceRange AllocatorRange =
2295 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2296 SourceLocation PrevAllocatorLoc =
2297 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2298 SourceRange PrevAllocatorRange =
2299 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2300 Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2301 << (Allocator ? 1 : 0) << AllocatorStream.str()
2302 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2303 << AllocatorRange;
2304 Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2305 << PrevAllocatorRange;
2306 continue;
2307 }
2308 }
2309
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002310 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2311 // If a list item has a static storage type, the allocator expression in the
2312 // allocator clause must be a constant expression that evaluates to one of
2313 // the predefined memory allocator values.
2314 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002315 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002316 Diag(Allocator->getExprLoc(),
2317 diag::err_omp_expected_predefined_allocator)
2318 << Allocator->getSourceRange();
2319 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2320 VarDecl::DeclarationOnly;
2321 Diag(VD->getLocation(),
2322 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2323 << VD;
2324 continue;
2325 }
2326 }
2327
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002328 Vars.push_back(RefExpr);
Alexey Bataev282555a2019-03-19 20:33:44 +00002329 if ((!Allocator || (Allocator && !Allocator->isTypeDependent() &&
2330 !Allocator->isValueDependent() &&
2331 !Allocator->isInstantiationDependent() &&
2332 !Allocator->containsUnexpandedParameterPack())) &&
2333 !VD->hasAttr<OMPAllocateDeclAttr>()) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002334 Attr *A = OMPAllocateDeclAttr::CreateImplicit(
2335 Context, AllocatorKind, Allocator, DE->getSourceRange());
Alexey Bataev282555a2019-03-19 20:33:44 +00002336 VD->addAttr(A);
2337 if (ASTMutationListener *ML = Context.getASTMutationListener())
2338 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2339 }
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002340 }
2341 if (Vars.empty())
2342 return nullptr;
2343 if (!Owner)
2344 Owner = getCurLexicalContext();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002345 OMPAllocateDecl *D =
2346 OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002347 D->setAccess(AS_public);
2348 Owner->addDecl(D);
2349 return DeclGroupPtrTy::make(DeclGroupRef(D));
2350}
2351
2352Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002353Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2354 ArrayRef<OMPClause *> ClauseList) {
2355 OMPRequiresDecl *D = nullptr;
2356 if (!CurContext->isFileContext()) {
2357 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2358 } else {
2359 D = CheckOMPRequiresDecl(Loc, ClauseList);
2360 if (D) {
2361 CurContext->addDecl(D);
2362 DSAStack->addRequiresDecl(D);
2363 }
2364 }
2365 return DeclGroupPtrTy::make(DeclGroupRef(D));
2366}
2367
2368OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2369 ArrayRef<OMPClause *> ClauseList) {
2370 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2371 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2372 ClauseList);
2373 return nullptr;
2374}
2375
Alexey Bataeve3727102018-04-18 15:57:46 +00002376static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2377 const ValueDecl *D,
2378 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002379 bool IsLoopIterVar = false) {
2380 if (DVar.RefExpr) {
2381 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2382 << getOpenMPClauseName(DVar.CKind);
2383 return;
2384 }
2385 enum {
2386 PDSA_StaticMemberShared,
2387 PDSA_StaticLocalVarShared,
2388 PDSA_LoopIterVarPrivate,
2389 PDSA_LoopIterVarLinear,
2390 PDSA_LoopIterVarLastprivate,
2391 PDSA_ConstVarShared,
2392 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002393 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002394 PDSA_LocalVarPrivate,
2395 PDSA_Implicit
2396 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002397 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002398 auto ReportLoc = D->getLocation();
2399 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002400 if (IsLoopIterVar) {
2401 if (DVar.CKind == OMPC_private)
2402 Reason = PDSA_LoopIterVarPrivate;
2403 else if (DVar.CKind == OMPC_lastprivate)
2404 Reason = PDSA_LoopIterVarLastprivate;
2405 else
2406 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002407 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2408 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002409 Reason = PDSA_TaskVarFirstprivate;
2410 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002411 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002412 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002413 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002414 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002415 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002416 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002417 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002418 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002419 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002420 ReportHint = true;
2421 Reason = PDSA_LocalVarPrivate;
2422 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002423 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002424 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002425 << Reason << ReportHint
2426 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2427 } else if (DVar.ImplicitDSALoc.isValid()) {
2428 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2429 << getOpenMPClauseName(DVar.CKind);
2430 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002431}
2432
Alexey Bataev758e55e2013-09-06 18:03:48 +00002433namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002434class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002435 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002436 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002437 bool ErrorFound = false;
2438 CapturedStmt *CS = nullptr;
2439 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2440 llvm::SmallVector<Expr *, 4> ImplicitMap;
2441 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2442 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002443
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002444 void VisitSubCaptures(OMPExecutableDirective *S) {
2445 // Check implicitly captured variables.
2446 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2447 return;
2448 for (const CapturedStmt::Capture &Cap :
2449 S->getInnermostCapturedStmt()->captures()) {
2450 if (!Cap.capturesVariable())
2451 continue;
2452 VarDecl *VD = Cap.getCapturedVar();
2453 // Do not try to map the variable if it or its sub-component was mapped
2454 // already.
2455 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2456 Stack->checkMappableExprComponentListsForDecl(
2457 VD, /*CurrentRegionOnly=*/true,
2458 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2459 OpenMPClauseKind) { return true; }))
2460 continue;
2461 DeclRefExpr *DRE = buildDeclRefExpr(
2462 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2463 Cap.getLocation(), /*RefersToCapture=*/true);
2464 Visit(DRE);
2465 }
2466 }
2467
Alexey Bataev758e55e2013-09-06 18:03:48 +00002468public:
2469 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002470 if (E->isTypeDependent() || E->isValueDependent() ||
2471 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2472 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002473 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002474 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002475 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002476 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002477 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002478
Alexey Bataeve3727102018-04-18 15:57:46 +00002479 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002480 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002481 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002482 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002483
Alexey Bataevafe50572017-10-06 17:00:28 +00002484 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002485 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002486 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002487 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2488 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002489 return;
2490
Alexey Bataeve3727102018-04-18 15:57:46 +00002491 SourceLocation ELoc = E->getExprLoc();
2492 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002493 // The default(none) clause requires that each variable that is referenced
2494 // in the construct, and does not have a predetermined data-sharing
2495 // attribute, must have its data-sharing attribute explicitly determined
2496 // by being listed in a data-sharing attribute clause.
2497 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002498 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002499 VarsWithInheritedDSA.count(VD) == 0) {
2500 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002501 return;
2502 }
2503
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002504 if (isOpenMPTargetExecutionDirective(DKind) &&
2505 !Stack->isLoopControlVariable(VD).first) {
2506 if (!Stack->checkMappableExprComponentListsForDecl(
2507 VD, /*CurrentRegionOnly=*/true,
2508 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2509 StackComponents,
2510 OpenMPClauseKind) {
2511 // Variable is used if it has been marked as an array, array
2512 // section or the variable iself.
2513 return StackComponents.size() == 1 ||
2514 std::all_of(
2515 std::next(StackComponents.rbegin()),
2516 StackComponents.rend(),
2517 [](const OMPClauseMappableExprCommon::
2518 MappableComponent &MC) {
2519 return MC.getAssociatedDeclaration() ==
2520 nullptr &&
2521 (isa<OMPArraySectionExpr>(
2522 MC.getAssociatedExpression()) ||
2523 isa<ArraySubscriptExpr>(
2524 MC.getAssociatedExpression()));
2525 });
2526 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002527 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002528 // By default lambdas are captured as firstprivates.
2529 if (const auto *RD =
2530 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002531 IsFirstprivate = RD->isLambda();
2532 IsFirstprivate =
2533 IsFirstprivate ||
2534 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002535 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002536 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002537 ImplicitFirstprivate.emplace_back(E);
2538 else
2539 ImplicitMap.emplace_back(E);
2540 return;
2541 }
2542 }
2543
Alexey Bataev758e55e2013-09-06 18:03:48 +00002544 // OpenMP [2.9.3.6, Restrictions, p.2]
2545 // A list item that appears in a reduction clause of the innermost
2546 // enclosing worksharing or parallel construct may not be accessed in an
2547 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002548 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002549 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2550 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002551 return isOpenMPParallelDirective(K) ||
2552 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2553 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002554 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002555 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002556 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002557 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002558 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002559 return;
2560 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002561
2562 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002563 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002564 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00002565 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002566 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00002567 return;
2568 }
2569
2570 // Store implicitly used globals with declare target link for parent
2571 // target.
2572 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2573 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2574 Stack->addToParentTargetRegionLinkGlobals(E);
2575 return;
2576 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002577 }
2578 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002579 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002580 if (E->isTypeDependent() || E->isValueDependent() ||
2581 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2582 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002583 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002584 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002585 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002586 if (!FD)
2587 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002588 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002589 // Check if the variable has explicit DSA set and stop analysis if it
2590 // so.
2591 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2592 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002593
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002594 if (isOpenMPTargetExecutionDirective(DKind) &&
2595 !Stack->isLoopControlVariable(FD).first &&
2596 !Stack->checkMappableExprComponentListsForDecl(
2597 FD, /*CurrentRegionOnly=*/true,
2598 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2599 StackComponents,
2600 OpenMPClauseKind) {
2601 return isa<CXXThisExpr>(
2602 cast<MemberExpr>(
2603 StackComponents.back().getAssociatedExpression())
2604 ->getBase()
2605 ->IgnoreParens());
2606 })) {
2607 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2608 // A bit-field cannot appear in a map clause.
2609 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002610 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002611 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002612
2613 // Check to see if the member expression is referencing a class that
2614 // has already been explicitly mapped
2615 if (Stack->isClassPreviouslyMapped(TE->getType()))
2616 return;
2617
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002618 ImplicitMap.emplace_back(E);
2619 return;
2620 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002621
Alexey Bataeve3727102018-04-18 15:57:46 +00002622 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002623 // OpenMP [2.9.3.6, Restrictions, p.2]
2624 // A list item that appears in a reduction clause of the innermost
2625 // enclosing worksharing or parallel construct may not be accessed in
2626 // an explicit task.
2627 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002628 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2629 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002630 return isOpenMPParallelDirective(K) ||
2631 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2632 },
2633 /*FromParent=*/true);
2634 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2635 ErrorFound = true;
2636 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002637 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002638 return;
2639 }
2640
2641 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002642 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002643 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002644 !Stack->isLoopControlVariable(FD).first) {
2645 // Check if there is a captured expression for the current field in the
2646 // region. Do not mark it as firstprivate unless there is no captured
2647 // expression.
2648 // TODO: try to make it firstprivate.
2649 if (DVar.CKind != OMPC_unknown)
2650 ImplicitFirstprivate.push_back(E);
2651 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002652 return;
2653 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002654 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002655 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002656 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002657 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002658 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002659 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002660 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2661 if (!Stack->checkMappableExprComponentListsForDecl(
2662 VD, /*CurrentRegionOnly=*/true,
2663 [&CurComponents](
2664 OMPClauseMappableExprCommon::MappableExprComponentListRef
2665 StackComponents,
2666 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002667 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002668 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002669 for (const auto &SC : llvm::reverse(StackComponents)) {
2670 // Do both expressions have the same kind?
2671 if (CCI->getAssociatedExpression()->getStmtClass() !=
2672 SC.getAssociatedExpression()->getStmtClass())
2673 if (!(isa<OMPArraySectionExpr>(
2674 SC.getAssociatedExpression()) &&
2675 isa<ArraySubscriptExpr>(
2676 CCI->getAssociatedExpression())))
2677 return false;
2678
Alexey Bataeve3727102018-04-18 15:57:46 +00002679 const Decl *CCD = CCI->getAssociatedDeclaration();
2680 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002681 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2682 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2683 if (SCD != CCD)
2684 return false;
2685 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002686 if (CCI == CCE)
2687 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002688 }
2689 return true;
2690 })) {
2691 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002692 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002693 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002694 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00002695 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002696 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002697 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002698 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002699 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002700 // for task|target directives.
2701 // Skip analysis of arguments of implicitly defined map clause for target
2702 // directives.
2703 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2704 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002705 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002706 if (CC)
2707 Visit(CC);
2708 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002709 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002710 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00002711 // Check implicitly captured variables.
2712 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002713 }
2714 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002715 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002716 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00002717 // Check implicitly captured variables in the task-based directives to
2718 // check if they must be firstprivatized.
2719 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002720 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002721 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002722 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002723
Alexey Bataeve3727102018-04-18 15:57:46 +00002724 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002725 ArrayRef<Expr *> getImplicitFirstprivate() const {
2726 return ImplicitFirstprivate;
2727 }
2728 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00002729 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002730 return VarsWithInheritedDSA;
2731 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002732
Alexey Bataev7ff55242014-06-19 09:13:45 +00002733 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00002734 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
2735 // Process declare target link variables for the target directives.
2736 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
2737 for (DeclRefExpr *E : Stack->getLinkGlobals())
2738 Visit(E);
2739 }
2740 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002741};
Alexey Bataeved09d242014-05-28 05:53:51 +00002742} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002743
Alexey Bataevbae9a792014-06-27 10:37:06 +00002744void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002745 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002746 case OMPD_parallel:
2747 case OMPD_parallel_for:
2748 case OMPD_parallel_for_simd:
2749 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002750 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002751 case OMPD_teams_distribute:
2752 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002753 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002754 QualType KmpInt32PtrTy =
2755 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002756 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002757 std::make_pair(".global_tid.", KmpInt32PtrTy),
2758 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2759 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002760 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002761 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2762 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002763 break;
2764 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002765 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002766 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002767 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002768 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002769 case OMPD_target_teams_distribute:
2770 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002771 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2772 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2773 QualType KmpInt32PtrTy =
2774 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2775 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002776 FunctionProtoType::ExtProtoInfo EPI;
2777 EPI.Variadic = true;
2778 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2779 Sema::CapturedParamNameType Params[] = {
2780 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002781 std::make_pair(".part_id.", KmpInt32PtrTy),
2782 std::make_pair(".privates.", VoidPtrTy),
2783 std::make_pair(
2784 ".copy_fn.",
2785 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002786 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2787 std::make_pair(StringRef(), QualType()) // __context with shared vars
2788 };
2789 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2790 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002791 // Mark this captured region as inlined, because we don't use outlined
2792 // function directly.
2793 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2794 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002795 Context, AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002796 Sema::CapturedParamNameType ParamsTarget[] = {
2797 std::make_pair(StringRef(), QualType()) // __context with shared vars
2798 };
2799 // Start a captured region for 'target' with no implicit parameters.
2800 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2801 ParamsTarget);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002802 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002803 std::make_pair(".global_tid.", KmpInt32PtrTy),
2804 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2805 std::make_pair(StringRef(), QualType()) // __context with shared vars
2806 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002807 // Start a captured region for 'teams' or 'parallel'. Both regions have
2808 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002809 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002810 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002811 break;
2812 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002813 case OMPD_target:
2814 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002815 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2816 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2817 QualType KmpInt32PtrTy =
2818 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2819 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002820 FunctionProtoType::ExtProtoInfo EPI;
2821 EPI.Variadic = true;
2822 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2823 Sema::CapturedParamNameType Params[] = {
2824 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002825 std::make_pair(".part_id.", KmpInt32PtrTy),
2826 std::make_pair(".privates.", VoidPtrTy),
2827 std::make_pair(
2828 ".copy_fn.",
2829 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002830 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2831 std::make_pair(StringRef(), QualType()) // __context with shared vars
2832 };
2833 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2834 Params);
2835 // Mark this captured region as inlined, because we don't use outlined
2836 // function directly.
2837 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2838 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002839 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00002840 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2841 std::make_pair(StringRef(), QualType()));
2842 break;
2843 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002844 case OMPD_simd:
2845 case OMPD_for:
2846 case OMPD_for_simd:
2847 case OMPD_sections:
2848 case OMPD_section:
2849 case OMPD_single:
2850 case OMPD_master:
2851 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002852 case OMPD_taskgroup:
2853 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002854 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002855 case OMPD_ordered:
2856 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002857 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002858 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002859 std::make_pair(StringRef(), QualType()) // __context with shared vars
2860 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002861 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2862 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002863 break;
2864 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002865 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002866 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2867 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2868 QualType KmpInt32PtrTy =
2869 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2870 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002871 FunctionProtoType::ExtProtoInfo EPI;
2872 EPI.Variadic = true;
2873 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002874 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002875 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002876 std::make_pair(".part_id.", KmpInt32PtrTy),
2877 std::make_pair(".privates.", VoidPtrTy),
2878 std::make_pair(
2879 ".copy_fn.",
2880 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002881 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002882 std::make_pair(StringRef(), QualType()) // __context with shared vars
2883 };
2884 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2885 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002886 // Mark this captured region as inlined, because we don't use outlined
2887 // function directly.
2888 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2889 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002890 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002891 break;
2892 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002893 case OMPD_taskloop:
2894 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002895 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002896 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2897 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002898 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002899 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2900 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002901 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002902 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2903 .withConst();
2904 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2905 QualType KmpInt32PtrTy =
2906 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2907 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00002908 FunctionProtoType::ExtProtoInfo EPI;
2909 EPI.Variadic = true;
2910 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002911 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002912 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002913 std::make_pair(".part_id.", KmpInt32PtrTy),
2914 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00002915 std::make_pair(
2916 ".copy_fn.",
2917 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2918 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2919 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002920 std::make_pair(".ub.", KmpUInt64Ty),
2921 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00002922 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002923 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002924 std::make_pair(StringRef(), QualType()) // __context with shared vars
2925 };
2926 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2927 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002928 // Mark this captured region as inlined, because we don't use outlined
2929 // function directly.
2930 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2931 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002932 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002933 break;
2934 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002935 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002936 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002937 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00002938 QualType KmpInt32PtrTy =
2939 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2940 Sema::CapturedParamNameType Params[] = {
2941 std::make_pair(".global_tid.", KmpInt32PtrTy),
2942 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002943 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2944 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00002945 std::make_pair(StringRef(), QualType()) // __context with shared vars
2946 };
2947 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2948 Params);
2949 break;
2950 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002951 case OMPD_target_teams_distribute_parallel_for:
2952 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002953 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002954 QualType KmpInt32PtrTy =
2955 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002956 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002957
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002958 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002959 FunctionProtoType::ExtProtoInfo EPI;
2960 EPI.Variadic = true;
2961 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2962 Sema::CapturedParamNameType Params[] = {
2963 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002964 std::make_pair(".part_id.", KmpInt32PtrTy),
2965 std::make_pair(".privates.", VoidPtrTy),
2966 std::make_pair(
2967 ".copy_fn.",
2968 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002969 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2970 std::make_pair(StringRef(), QualType()) // __context with shared vars
2971 };
2972 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2973 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00002974 // Mark this captured region as inlined, because we don't use outlined
2975 // function directly.
2976 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2977 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002978 Context, AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00002979 Sema::CapturedParamNameType ParamsTarget[] = {
2980 std::make_pair(StringRef(), QualType()) // __context with shared vars
2981 };
2982 // Start a captured region for 'target' with no implicit parameters.
2983 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2984 ParamsTarget);
2985
2986 Sema::CapturedParamNameType ParamsTeams[] = {
2987 std::make_pair(".global_tid.", KmpInt32PtrTy),
2988 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2989 std::make_pair(StringRef(), QualType()) // __context with shared vars
2990 };
2991 // Start a captured region for 'target' with no implicit parameters.
2992 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2993 ParamsTeams);
2994
2995 Sema::CapturedParamNameType ParamsParallel[] = {
2996 std::make_pair(".global_tid.", KmpInt32PtrTy),
2997 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002998 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2999 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003000 std::make_pair(StringRef(), QualType()) // __context with shared vars
3001 };
3002 // Start a captured region for 'teams' or 'parallel'. Both regions have
3003 // the same implicit parameters.
3004 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3005 ParamsParallel);
3006 break;
3007 }
3008
Alexey Bataev46506272017-12-05 17:41:34 +00003009 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003010 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003011 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003012 QualType KmpInt32PtrTy =
3013 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3014
3015 Sema::CapturedParamNameType ParamsTeams[] = {
3016 std::make_pair(".global_tid.", KmpInt32PtrTy),
3017 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3018 std::make_pair(StringRef(), QualType()) // __context with shared vars
3019 };
3020 // Start a captured region for 'target' with no implicit parameters.
3021 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3022 ParamsTeams);
3023
3024 Sema::CapturedParamNameType ParamsParallel[] = {
3025 std::make_pair(".global_tid.", KmpInt32PtrTy),
3026 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003027 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3028 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003029 std::make_pair(StringRef(), QualType()) // __context with shared vars
3030 };
3031 // Start a captured region for 'teams' or 'parallel'. Both regions have
3032 // the same implicit parameters.
3033 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3034 ParamsParallel);
3035 break;
3036 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003037 case OMPD_target_update:
3038 case OMPD_target_enter_data:
3039 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003040 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3041 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3042 QualType KmpInt32PtrTy =
3043 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3044 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003045 FunctionProtoType::ExtProtoInfo EPI;
3046 EPI.Variadic = true;
3047 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3048 Sema::CapturedParamNameType Params[] = {
3049 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003050 std::make_pair(".part_id.", KmpInt32PtrTy),
3051 std::make_pair(".privates.", VoidPtrTy),
3052 std::make_pair(
3053 ".copy_fn.",
3054 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003055 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3056 std::make_pair(StringRef(), QualType()) // __context with shared vars
3057 };
3058 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3059 Params);
3060 // Mark this captured region as inlined, because we don't use outlined
3061 // function directly.
3062 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3063 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003064 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003065 break;
3066 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003067 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003068 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003069 case OMPD_taskyield:
3070 case OMPD_barrier:
3071 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003072 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003073 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003074 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003075 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003076 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003077 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003078 case OMPD_declare_target:
3079 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003080 case OMPD_requires:
Alexey Bataev9959db52014-05-06 10:08:46 +00003081 llvm_unreachable("OpenMP Directive is not allowed");
3082 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003083 llvm_unreachable("Unknown OpenMP directive");
3084 }
3085}
3086
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003087int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3088 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3089 getOpenMPCaptureRegions(CaptureRegions, DKind);
3090 return CaptureRegions.size();
3091}
3092
Alexey Bataev3392d762016-02-16 11:18:12 +00003093static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003094 Expr *CaptureExpr, bool WithInit,
3095 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003096 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003097 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003098 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003099 QualType Ty = Init->getType();
3100 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003101 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003102 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003103 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003104 Ty = C.getPointerType(Ty);
3105 ExprResult Res =
3106 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3107 if (!Res.isUsable())
3108 return nullptr;
3109 Init = Res.get();
3110 }
Alexey Bataev61205072016-03-02 04:57:40 +00003111 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003112 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003113 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003114 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003115 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003116 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003117 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003118 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003119 return CED;
3120}
3121
Alexey Bataev61205072016-03-02 04:57:40 +00003122static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3123 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003124 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003125 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003126 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003127 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003128 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3129 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003130 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003131 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003132}
3133
Alexey Bataev5a3af132016-03-29 08:58:54 +00003134static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003135 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003136 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003137 OMPCapturedExprDecl *CD = buildCaptureDecl(
3138 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3139 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003140 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3141 CaptureExpr->getExprLoc());
3142 }
3143 ExprResult Res = Ref;
3144 if (!S.getLangOpts().CPlusPlus &&
3145 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003146 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003147 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003148 if (!Res.isUsable())
3149 return ExprError();
3150 }
3151 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003152}
3153
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003154namespace {
3155// OpenMP directives parsed in this section are represented as a
3156// CapturedStatement with an associated statement. If a syntax error
3157// is detected during the parsing of the associated statement, the
3158// compiler must abort processing and close the CapturedStatement.
3159//
3160// Combined directives such as 'target parallel' have more than one
3161// nested CapturedStatements. This RAII ensures that we unwind out
3162// of all the nested CapturedStatements when an error is found.
3163class CaptureRegionUnwinderRAII {
3164private:
3165 Sema &S;
3166 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003167 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003168
3169public:
3170 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3171 OpenMPDirectiveKind DKind)
3172 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3173 ~CaptureRegionUnwinderRAII() {
3174 if (ErrorFound) {
3175 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3176 while (--ThisCaptureLevel >= 0)
3177 S.ActOnCapturedRegionError();
3178 }
3179 }
3180};
3181} // namespace
3182
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003183StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3184 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003185 bool ErrorFound = false;
3186 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3187 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003188 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003189 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003190 return StmtError();
3191 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003192
Alexey Bataev2ba67042017-11-28 21:11:44 +00003193 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3194 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003195 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003196 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003197 SmallVector<const OMPLinearClause *, 4> LCs;
3198 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003199 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003200 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003201 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3202 Clause->getClauseKind() == OMPC_in_reduction) {
3203 // Capture taskgroup task_reduction descriptors inside the tasking regions
3204 // with the corresponding in_reduction items.
3205 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003206 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003207 if (E)
3208 MarkDeclarationsReferencedInExpr(E);
3209 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003210 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003211 Clause->getClauseKind() == OMPC_copyprivate ||
3212 (getLangOpts().OpenMPUseTLS &&
3213 getASTContext().getTargetInfo().isTLSSupported() &&
3214 Clause->getClauseKind() == OMPC_copyin)) {
3215 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003216 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003217 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003218 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003219 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003220 }
3221 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003222 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003223 } else if (CaptureRegions.size() > 1 ||
3224 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003225 if (auto *C = OMPClauseWithPreInit::get(Clause))
3226 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003227 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003228 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003229 MarkDeclarationsReferencedInExpr(E);
3230 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003231 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003232 if (Clause->getClauseKind() == OMPC_schedule)
3233 SC = cast<OMPScheduleClause>(Clause);
3234 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003235 OC = cast<OMPOrderedClause>(Clause);
3236 else if (Clause->getClauseKind() == OMPC_linear)
3237 LCs.push_back(cast<OMPLinearClause>(Clause));
3238 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003239 // OpenMP, 2.7.1 Loop Construct, Restrictions
3240 // The nonmonotonic modifier cannot be specified if an ordered clause is
3241 // specified.
3242 if (SC &&
3243 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3244 SC->getSecondScheduleModifier() ==
3245 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3246 OC) {
3247 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3248 ? SC->getFirstScheduleModifierLoc()
3249 : SC->getSecondScheduleModifierLoc(),
3250 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003251 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003252 ErrorFound = true;
3253 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003254 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003255 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003256 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003257 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003258 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003259 ErrorFound = true;
3260 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003261 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3262 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3263 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003264 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003265 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3266 ErrorFound = true;
3267 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003268 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003269 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003270 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003271 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003272 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003273 // Mark all variables in private list clauses as used in inner region.
3274 // Required for proper codegen of combined directives.
3275 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003276 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003277 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003278 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3279 // Find the particular capture region for the clause if the
3280 // directive is a combined one with multiple capture regions.
3281 // If the directive is not a combined one, the capture region
3282 // associated with the clause is OMPD_unknown and is generated
3283 // only once.
3284 if (CaptureRegion == ThisCaptureRegion ||
3285 CaptureRegion == OMPD_unknown) {
3286 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003287 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003288 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3289 }
3290 }
3291 }
3292 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003293 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003294 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003295 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003296}
3297
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003298static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3299 OpenMPDirectiveKind CancelRegion,
3300 SourceLocation StartLoc) {
3301 // CancelRegion is only needed for cancel and cancellation_point.
3302 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3303 return false;
3304
3305 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3306 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3307 return false;
3308
3309 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3310 << getOpenMPDirectiveName(CancelRegion);
3311 return true;
3312}
3313
Alexey Bataeve3727102018-04-18 15:57:46 +00003314static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003315 OpenMPDirectiveKind CurrentRegion,
3316 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003317 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003318 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003319 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003320 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3321 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003322 bool NestingProhibited = false;
3323 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003324 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003325 enum {
3326 NoRecommend,
3327 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003328 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003329 ShouldBeInTargetRegion,
3330 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003331 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003332 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003333 // OpenMP [2.16, Nesting of Regions]
3334 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003335 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003336 // An ordered construct with the simd clause is the only OpenMP
3337 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003338 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003339 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3340 // message.
3341 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3342 ? diag::err_omp_prohibited_region_simd
3343 : diag::warn_omp_nesting_simd);
3344 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003345 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003346 if (ParentRegion == OMPD_atomic) {
3347 // OpenMP [2.16, Nesting of Regions]
3348 // OpenMP constructs may not be nested inside an atomic region.
3349 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3350 return true;
3351 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003352 if (CurrentRegion == OMPD_section) {
3353 // OpenMP [2.7.2, sections Construct, Restrictions]
3354 // Orphaned section directives are prohibited. That is, the section
3355 // directives must appear within the sections construct and must not be
3356 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003357 if (ParentRegion != OMPD_sections &&
3358 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003359 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3360 << (ParentRegion != OMPD_unknown)
3361 << getOpenMPDirectiveName(ParentRegion);
3362 return true;
3363 }
3364 return false;
3365 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003366 // Allow some constructs (except teams and cancellation constructs) to be
3367 // orphaned (they could be used in functions, called from OpenMP regions
3368 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003369 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003370 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3371 CurrentRegion != OMPD_cancellation_point &&
3372 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003373 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003374 if (CurrentRegion == OMPD_cancellation_point ||
3375 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003376 // OpenMP [2.16, Nesting of Regions]
3377 // A cancellation point construct for which construct-type-clause is
3378 // taskgroup must be nested inside a task construct. A cancellation
3379 // point construct for which construct-type-clause is not taskgroup must
3380 // be closely nested inside an OpenMP construct that matches the type
3381 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003382 // A cancel construct for which construct-type-clause is taskgroup must be
3383 // nested inside a task construct. A cancel construct for which
3384 // construct-type-clause is not taskgroup must be closely nested inside an
3385 // OpenMP construct that matches the type specified in
3386 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003387 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003388 !((CancelRegion == OMPD_parallel &&
3389 (ParentRegion == OMPD_parallel ||
3390 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003391 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003392 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003393 ParentRegion == OMPD_target_parallel_for ||
3394 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003395 ParentRegion == OMPD_teams_distribute_parallel_for ||
3396 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003397 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3398 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003399 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3400 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003401 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003402 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003403 // OpenMP [2.16, Nesting of Regions]
3404 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003405 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003406 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003407 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003408 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3409 // OpenMP [2.16, Nesting of Regions]
3410 // A critical region may not be nested (closely or otherwise) inside a
3411 // critical region with the same name. Note that this restriction is not
3412 // sufficient to prevent deadlock.
3413 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003414 bool DeadLock = Stack->hasDirective(
3415 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3416 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003417 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003418 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3419 PreviousCriticalLoc = Loc;
3420 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003421 }
3422 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003423 },
3424 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003425 if (DeadLock) {
3426 SemaRef.Diag(StartLoc,
3427 diag::err_omp_prohibited_region_critical_same_name)
3428 << CurrentName.getName();
3429 if (PreviousCriticalLoc.isValid())
3430 SemaRef.Diag(PreviousCriticalLoc,
3431 diag::note_omp_previous_critical_region);
3432 return true;
3433 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003434 } else if (CurrentRegion == OMPD_barrier) {
3435 // OpenMP [2.16, Nesting of Regions]
3436 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003437 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003438 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3439 isOpenMPTaskingDirective(ParentRegion) ||
3440 ParentRegion == OMPD_master ||
3441 ParentRegion == OMPD_critical ||
3442 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003443 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003444 !isOpenMPParallelDirective(CurrentRegion) &&
3445 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003446 // OpenMP [2.16, Nesting of Regions]
3447 // A worksharing region may not be closely nested inside a worksharing,
3448 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003449 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3450 isOpenMPTaskingDirective(ParentRegion) ||
3451 ParentRegion == OMPD_master ||
3452 ParentRegion == OMPD_critical ||
3453 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003454 Recommend = ShouldBeInParallelRegion;
3455 } else if (CurrentRegion == OMPD_ordered) {
3456 // OpenMP [2.16, Nesting of Regions]
3457 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003458 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003459 // An ordered region must be closely nested inside a loop region (or
3460 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003461 // OpenMP [2.8.1,simd Construct, Restrictions]
3462 // An ordered construct with the simd clause is the only OpenMP construct
3463 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003464 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003465 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003466 !(isOpenMPSimdDirective(ParentRegion) ||
3467 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003468 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003469 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003470 // OpenMP [2.16, Nesting of Regions]
3471 // If specified, a teams construct must be contained within a target
3472 // construct.
3473 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00003474 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003475 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003476 }
Kelvin Libf594a52016-12-17 05:48:59 +00003477 if (!NestingProhibited &&
3478 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3479 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3480 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003481 // OpenMP [2.16, Nesting of Regions]
3482 // distribute, parallel, parallel sections, parallel workshare, and the
3483 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3484 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003485 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3486 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003487 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003488 }
David Majnemer9d168222016-08-05 17:44:54 +00003489 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003490 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003491 // OpenMP 4.5 [2.17 Nesting of Regions]
3492 // The region associated with the distribute construct must be strictly
3493 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003494 NestingProhibited =
3495 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003496 Recommend = ShouldBeInTeamsRegion;
3497 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003498 if (!NestingProhibited &&
3499 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3500 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3501 // OpenMP 4.5 [2.17 Nesting of Regions]
3502 // If a target, target update, target data, target enter data, or
3503 // target exit data construct is encountered during execution of a
3504 // target region, the behavior is unspecified.
3505 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003506 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003507 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003508 if (isOpenMPTargetExecutionDirective(K)) {
3509 OffendingRegion = K;
3510 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003511 }
3512 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003513 },
3514 false /* don't skip top directive */);
3515 CloseNesting = false;
3516 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003517 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003518 if (OrphanSeen) {
3519 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3520 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3521 } else {
3522 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3523 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3524 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3525 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003526 return true;
3527 }
3528 }
3529 return false;
3530}
3531
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003532static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3533 ArrayRef<OMPClause *> Clauses,
3534 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3535 bool ErrorFound = false;
3536 unsigned NamedModifiersNumber = 0;
3537 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3538 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003539 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003540 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003541 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3542 // At most one if clause without a directive-name-modifier can appear on
3543 // the directive.
3544 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3545 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003546 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003547 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3548 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3549 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003550 } else if (CurNM != OMPD_unknown) {
3551 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003552 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003553 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003554 FoundNameModifiers[CurNM] = IC;
3555 if (CurNM == OMPD_unknown)
3556 continue;
3557 // Check if the specified name modifier is allowed for the current
3558 // directive.
3559 // At most one if clause with the particular directive-name-modifier can
3560 // appear on the directive.
3561 bool MatchFound = false;
3562 for (auto NM : AllowedNameModifiers) {
3563 if (CurNM == NM) {
3564 MatchFound = true;
3565 break;
3566 }
3567 }
3568 if (!MatchFound) {
3569 S.Diag(IC->getNameModifierLoc(),
3570 diag::err_omp_wrong_if_directive_name_modifier)
3571 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3572 ErrorFound = true;
3573 }
3574 }
3575 }
3576 // If any if clause on the directive includes a directive-name-modifier then
3577 // all if clauses on the directive must include a directive-name-modifier.
3578 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3579 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003580 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003581 diag::err_omp_no_more_if_clause);
3582 } else {
3583 std::string Values;
3584 std::string Sep(", ");
3585 unsigned AllowedCnt = 0;
3586 unsigned TotalAllowedNum =
3587 AllowedNameModifiers.size() - NamedModifiersNumber;
3588 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3589 ++Cnt) {
3590 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3591 if (!FoundNameModifiers[NM]) {
3592 Values += "'";
3593 Values += getOpenMPDirectiveName(NM);
3594 Values += "'";
3595 if (AllowedCnt + 2 == TotalAllowedNum)
3596 Values += " or ";
3597 else if (AllowedCnt + 1 != TotalAllowedNum)
3598 Values += Sep;
3599 ++AllowedCnt;
3600 }
3601 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003602 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003603 diag::err_omp_unnamed_if_clause)
3604 << (TotalAllowedNum > 1) << Values;
3605 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003606 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00003607 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3608 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003609 ErrorFound = true;
3610 }
3611 return ErrorFound;
3612}
3613
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003614StmtResult Sema::ActOnOpenMPExecutableDirective(
3615 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3616 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3617 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003618 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003619 // First check CancelRegion which is then used in checkNestingOfRegions.
3620 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3621 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003622 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00003623 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003624
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003625 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00003626 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003627 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003628 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003629 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003630 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3631
3632 // Check default data sharing attributes for referenced variables.
3633 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003634 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3635 Stmt *S = AStmt;
3636 while (--ThisCaptureLevel >= 0)
3637 S = cast<CapturedStmt>(S)->getCapturedStmt();
3638 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003639 if (DSAChecker.isErrorFound())
3640 return StmtError();
3641 // Generate list of implicitly defined firstprivate variables.
3642 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003643
Alexey Bataev88202be2017-07-27 13:20:36 +00003644 SmallVector<Expr *, 4> ImplicitFirstprivates(
3645 DSAChecker.getImplicitFirstprivate().begin(),
3646 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003647 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3648 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003649 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00003650 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003651 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003652 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003653 if (E)
3654 ImplicitFirstprivates.emplace_back(E);
3655 }
3656 }
3657 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003658 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00003659 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3660 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003661 ClausesWithImplicit.push_back(Implicit);
3662 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00003663 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003664 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00003665 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003666 }
Alexey Bataev68446b72014-07-18 07:47:19 +00003667 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003668 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00003669 CXXScopeSpec MapperIdScopeSpec;
3670 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003671 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00003672 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
3673 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
3674 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003675 ClausesWithImplicit.emplace_back(Implicit);
3676 ErrorFound |=
3677 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003678 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003679 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003680 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003681 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003682 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003683
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003684 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003685 switch (Kind) {
3686 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003687 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3688 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003689 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003690 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003691 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003692 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3693 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003694 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003695 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003696 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3697 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003698 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003699 case OMPD_for_simd:
3700 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3701 EndLoc, VarsWithInheritedDSA);
3702 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003703 case OMPD_sections:
3704 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3705 EndLoc);
3706 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003707 case OMPD_section:
3708 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003709 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003710 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3711 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003712 case OMPD_single:
3713 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3714 EndLoc);
3715 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003716 case OMPD_master:
3717 assert(ClausesWithImplicit.empty() &&
3718 "No clauses are allowed for 'omp master' directive");
3719 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3720 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003721 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003722 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3723 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003724 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003725 case OMPD_parallel_for:
3726 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3727 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003728 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003729 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003730 case OMPD_parallel_for_simd:
3731 Res = ActOnOpenMPParallelForSimdDirective(
3732 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003733 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003734 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003735 case OMPD_parallel_sections:
3736 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3737 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003738 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003739 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003740 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003741 Res =
3742 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003743 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003744 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003745 case OMPD_taskyield:
3746 assert(ClausesWithImplicit.empty() &&
3747 "No clauses are allowed for 'omp taskyield' directive");
3748 assert(AStmt == nullptr &&
3749 "No associated statement allowed for 'omp taskyield' directive");
3750 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3751 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003752 case OMPD_barrier:
3753 assert(ClausesWithImplicit.empty() &&
3754 "No clauses are allowed for 'omp barrier' directive");
3755 assert(AStmt == nullptr &&
3756 "No associated statement allowed for 'omp barrier' directive");
3757 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3758 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003759 case OMPD_taskwait:
3760 assert(ClausesWithImplicit.empty() &&
3761 "No clauses are allowed for 'omp taskwait' directive");
3762 assert(AStmt == nullptr &&
3763 "No associated statement allowed for 'omp taskwait' directive");
3764 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3765 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003766 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003767 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3768 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003769 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003770 case OMPD_flush:
3771 assert(AStmt == nullptr &&
3772 "No associated statement allowed for 'omp flush' directive");
3773 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3774 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003775 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003776 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3777 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003778 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003779 case OMPD_atomic:
3780 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3781 EndLoc);
3782 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003783 case OMPD_teams:
3784 Res =
3785 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3786 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003787 case OMPD_target:
3788 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3789 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003790 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003791 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003792 case OMPD_target_parallel:
3793 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3794 StartLoc, EndLoc);
3795 AllowedNameModifiers.push_back(OMPD_target);
3796 AllowedNameModifiers.push_back(OMPD_parallel);
3797 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003798 case OMPD_target_parallel_for:
3799 Res = ActOnOpenMPTargetParallelForDirective(
3800 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3801 AllowedNameModifiers.push_back(OMPD_target);
3802 AllowedNameModifiers.push_back(OMPD_parallel);
3803 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003804 case OMPD_cancellation_point:
3805 assert(ClausesWithImplicit.empty() &&
3806 "No clauses are allowed for 'omp cancellation point' directive");
3807 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3808 "cancellation point' directive");
3809 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3810 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003811 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003812 assert(AStmt == nullptr &&
3813 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003814 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3815 CancelRegion);
3816 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003817 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003818 case OMPD_target_data:
3819 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3820 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003821 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003822 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003823 case OMPD_target_enter_data:
3824 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003825 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003826 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3827 break;
Samuel Antao72590762016-01-19 20:04:50 +00003828 case OMPD_target_exit_data:
3829 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003830 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003831 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3832 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003833 case OMPD_taskloop:
3834 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3835 EndLoc, VarsWithInheritedDSA);
3836 AllowedNameModifiers.push_back(OMPD_taskloop);
3837 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003838 case OMPD_taskloop_simd:
3839 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3840 EndLoc, VarsWithInheritedDSA);
3841 AllowedNameModifiers.push_back(OMPD_taskloop);
3842 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003843 case OMPD_distribute:
3844 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3845 EndLoc, VarsWithInheritedDSA);
3846 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003847 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003848 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3849 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003850 AllowedNameModifiers.push_back(OMPD_target_update);
3851 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003852 case OMPD_distribute_parallel_for:
3853 Res = ActOnOpenMPDistributeParallelForDirective(
3854 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3855 AllowedNameModifiers.push_back(OMPD_parallel);
3856 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003857 case OMPD_distribute_parallel_for_simd:
3858 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3859 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3860 AllowedNameModifiers.push_back(OMPD_parallel);
3861 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003862 case OMPD_distribute_simd:
3863 Res = ActOnOpenMPDistributeSimdDirective(
3864 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3865 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003866 case OMPD_target_parallel_for_simd:
3867 Res = ActOnOpenMPTargetParallelForSimdDirective(
3868 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3869 AllowedNameModifiers.push_back(OMPD_target);
3870 AllowedNameModifiers.push_back(OMPD_parallel);
3871 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003872 case OMPD_target_simd:
3873 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3874 EndLoc, VarsWithInheritedDSA);
3875 AllowedNameModifiers.push_back(OMPD_target);
3876 break;
Kelvin Li02532872016-08-05 14:37:37 +00003877 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003878 Res = ActOnOpenMPTeamsDistributeDirective(
3879 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003880 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003881 case OMPD_teams_distribute_simd:
3882 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3883 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3884 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003885 case OMPD_teams_distribute_parallel_for_simd:
3886 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3887 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3888 AllowedNameModifiers.push_back(OMPD_parallel);
3889 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003890 case OMPD_teams_distribute_parallel_for:
3891 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3892 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3893 AllowedNameModifiers.push_back(OMPD_parallel);
3894 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003895 case OMPD_target_teams:
3896 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3897 EndLoc);
3898 AllowedNameModifiers.push_back(OMPD_target);
3899 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003900 case OMPD_target_teams_distribute:
3901 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3902 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3903 AllowedNameModifiers.push_back(OMPD_target);
3904 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003905 case OMPD_target_teams_distribute_parallel_for:
3906 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3907 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3908 AllowedNameModifiers.push_back(OMPD_target);
3909 AllowedNameModifiers.push_back(OMPD_parallel);
3910 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003911 case OMPD_target_teams_distribute_parallel_for_simd:
3912 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3913 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3914 AllowedNameModifiers.push_back(OMPD_target);
3915 AllowedNameModifiers.push_back(OMPD_parallel);
3916 break;
Kelvin Lida681182017-01-10 18:08:18 +00003917 case OMPD_target_teams_distribute_simd:
3918 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3919 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3920 AllowedNameModifiers.push_back(OMPD_target);
3921 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003922 case OMPD_declare_target:
3923 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003924 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003925 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003926 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003927 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003928 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00003929 case OMPD_requires:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003930 llvm_unreachable("OpenMP Directive is not allowed");
3931 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003932 llvm_unreachable("Unknown OpenMP directive");
3933 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003934
Roman Lebedevb5700602019-03-20 16:32:36 +00003935 ErrorFound = Res.isInvalid() || ErrorFound;
3936
Alexey Bataeve3727102018-04-18 15:57:46 +00003937 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003938 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3939 << P.first << P.second->getSourceRange();
3940 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003941 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3942
3943 if (!AllowedNameModifiers.empty())
3944 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3945 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003946
Alexey Bataeved09d242014-05-28 05:53:51 +00003947 if (ErrorFound)
3948 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00003949
3950 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
3951 Res.getAs<OMPExecutableDirective>()
3952 ->getStructuredBlock()
3953 ->setIsOMPStructuredBlock(true);
3954 }
3955
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003956 return Res;
3957}
3958
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003959Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3960 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003961 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003962 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3963 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003964 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003965 assert(Linears.size() == LinModifiers.size());
3966 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003967 if (!DG || DG.get().isNull())
3968 return DeclGroupPtrTy();
3969
3970 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003971 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003972 return DG;
3973 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003974 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00003975 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3976 ADecl = FTD->getTemplatedDecl();
3977
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003978 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3979 if (!FD) {
3980 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003981 return DeclGroupPtrTy();
3982 }
3983
Alexey Bataev2af33e32016-04-07 12:45:37 +00003984 // OpenMP [2.8.2, declare simd construct, Description]
3985 // The parameter of the simdlen clause must be a constant positive integer
3986 // expression.
3987 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003988 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003989 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003990 // OpenMP [2.8.2, declare simd construct, Description]
3991 // The special this pointer can be used as if was one of the arguments to the
3992 // function in any of the linear, aligned, or uniform clauses.
3993 // The uniform clause declares one or more arguments to have an invariant
3994 // value for all concurrent invocations of the function in the execution of a
3995 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00003996 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
3997 const Expr *UniformedLinearThis = nullptr;
3998 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003999 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004000 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4001 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004002 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4003 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004004 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004005 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004006 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004007 }
4008 if (isa<CXXThisExpr>(E)) {
4009 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004010 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004011 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004012 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4013 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004014 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004015 // OpenMP [2.8.2, declare simd construct, Description]
4016 // The aligned clause declares that the object to which each list item points
4017 // is aligned to the number of bytes expressed in the optional parameter of
4018 // the aligned clause.
4019 // The special this pointer can be used as if was one of the arguments to the
4020 // function in any of the linear, aligned, or uniform clauses.
4021 // The type of list items appearing in the aligned clause must be array,
4022 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004023 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4024 const Expr *AlignedThis = nullptr;
4025 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004026 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004027 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4028 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4029 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004030 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4031 FD->getParamDecl(PVD->getFunctionScopeIndex())
4032 ->getCanonicalDecl() == CanonPVD) {
4033 // OpenMP [2.8.1, simd construct, Restrictions]
4034 // A list-item cannot appear in more than one aligned clause.
4035 if (AlignedArgs.count(CanonPVD) > 0) {
4036 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4037 << 1 << E->getSourceRange();
4038 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4039 diag::note_omp_explicit_dsa)
4040 << getOpenMPClauseName(OMPC_aligned);
4041 continue;
4042 }
4043 AlignedArgs[CanonPVD] = E;
4044 QualType QTy = PVD->getType()
4045 .getNonReferenceType()
4046 .getUnqualifiedType()
4047 .getCanonicalType();
4048 const Type *Ty = QTy.getTypePtrOrNull();
4049 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4050 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4051 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4052 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4053 }
4054 continue;
4055 }
4056 }
4057 if (isa<CXXThisExpr>(E)) {
4058 if (AlignedThis) {
4059 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4060 << 2 << E->getSourceRange();
4061 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4062 << getOpenMPClauseName(OMPC_aligned);
4063 }
4064 AlignedThis = E;
4065 continue;
4066 }
4067 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4068 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4069 }
4070 // The optional parameter of the aligned clause, alignment, must be a constant
4071 // positive integer expression. If no optional parameter is specified,
4072 // implementation-defined default alignments for SIMD instructions on the
4073 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00004074 SmallVector<const Expr *, 4> NewAligns;
4075 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004076 ExprResult Align;
4077 if (E)
4078 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4079 NewAligns.push_back(Align.get());
4080 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00004081 // OpenMP [2.8.2, declare simd construct, Description]
4082 // The linear clause declares one or more list items to be private to a SIMD
4083 // lane and to have a linear relationship with respect to the iteration space
4084 // of a loop.
4085 // The special this pointer can be used as if was one of the arguments to the
4086 // function in any of the linear, aligned, or uniform clauses.
4087 // When a linear-step expression is specified in a linear clause it must be
4088 // either a constant integer expression or an integer-typed parameter that is
4089 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00004090 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004091 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4092 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00004093 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004094 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4095 ++MI;
4096 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004097 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4098 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4099 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004100 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4101 FD->getParamDecl(PVD->getFunctionScopeIndex())
4102 ->getCanonicalDecl() == CanonPVD) {
4103 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4104 // A list-item cannot appear in more than one linear clause.
4105 if (LinearArgs.count(CanonPVD) > 0) {
4106 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4107 << getOpenMPClauseName(OMPC_linear)
4108 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4109 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4110 diag::note_omp_explicit_dsa)
4111 << getOpenMPClauseName(OMPC_linear);
4112 continue;
4113 }
4114 // Each argument can appear in at most one uniform or linear clause.
4115 if (UniformedArgs.count(CanonPVD) > 0) {
4116 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4117 << getOpenMPClauseName(OMPC_linear)
4118 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4119 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4120 diag::note_omp_explicit_dsa)
4121 << getOpenMPClauseName(OMPC_uniform);
4122 continue;
4123 }
4124 LinearArgs[CanonPVD] = E;
4125 if (E->isValueDependent() || E->isTypeDependent() ||
4126 E->isInstantiationDependent() ||
4127 E->containsUnexpandedParameterPack())
4128 continue;
4129 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4130 PVD->getOriginalType());
4131 continue;
4132 }
4133 }
4134 if (isa<CXXThisExpr>(E)) {
4135 if (UniformedLinearThis) {
4136 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4137 << getOpenMPClauseName(OMPC_linear)
4138 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4139 << E->getSourceRange();
4140 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4141 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4142 : OMPC_linear);
4143 continue;
4144 }
4145 UniformedLinearThis = E;
4146 if (E->isValueDependent() || E->isTypeDependent() ||
4147 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4148 continue;
4149 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4150 E->getType());
4151 continue;
4152 }
4153 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4154 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4155 }
4156 Expr *Step = nullptr;
4157 Expr *NewStep = nullptr;
4158 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00004159 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004160 // Skip the same step expression, it was checked already.
4161 if (Step == E || !E) {
4162 NewSteps.push_back(E ? NewStep : nullptr);
4163 continue;
4164 }
4165 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00004166 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4167 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4168 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004169 if (UniformedArgs.count(CanonPVD) == 0) {
4170 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4171 << Step->getSourceRange();
4172 } else if (E->isValueDependent() || E->isTypeDependent() ||
4173 E->isInstantiationDependent() ||
4174 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00004175 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004176 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00004177 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004178 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4179 << Step->getSourceRange();
4180 }
4181 continue;
4182 }
4183 NewStep = Step;
4184 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4185 !Step->isInstantiationDependent() &&
4186 !Step->containsUnexpandedParameterPack()) {
4187 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4188 .get();
4189 if (NewStep)
4190 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4191 }
4192 NewSteps.push_back(NewStep);
4193 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004194 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4195 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00004196 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00004197 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4198 const_cast<Expr **>(Linears.data()), Linears.size(),
4199 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4200 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004201 ADecl->addAttr(NewAttr);
4202 return ConvertDeclToDeclGroup(ADecl);
4203}
4204
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004205StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
4206 Stmt *AStmt,
4207 SourceLocation StartLoc,
4208 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004209 if (!AStmt)
4210 return StmtError();
4211
Alexey Bataeve3727102018-04-18 15:57:46 +00004212 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00004213 // 1.2.2 OpenMP Language Terminology
4214 // Structured block - An executable statement with a single entry at the
4215 // top and a single exit at the bottom.
4216 // The point of exit cannot be a branch out of the structured block.
4217 // longjmp() and throw() must not violate the entry/exit criteria.
4218 CS->getCapturedDecl()->setNothrow();
4219
Reid Kleckner87a31802018-03-12 21:43:02 +00004220 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004221
Alexey Bataev25e5b442015-09-15 12:52:43 +00004222 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4223 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004224}
4225
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004226namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004227/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004228/// extracting iteration space of each loop in the loop nest, that will be used
4229/// for IR generation.
4230class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004231 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004232 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004233 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004234 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004235 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004236 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004237 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004238 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004239 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004240 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004241 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004242 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004243 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004244 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004245 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004246 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004247 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004248 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004249 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004250 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004251 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004252 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004253 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004254 /// Var < UB
4255 /// Var <= UB
4256 /// UB > Var
4257 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00004258 /// This will have no value when the condition is !=
4259 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004260 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004261 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004262 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004263 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004264
4265public:
4266 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004267 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004268 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004269 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00004270 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004271 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004272 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00004273 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004274 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004275 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00004276 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004277 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004278 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004279 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004280 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004281 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004282 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004283 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00004284 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004285 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004286 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004287 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00004288 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00004289 /// True, if the compare operator is strict (<, > or !=).
4290 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004291 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004292 Expr *buildNumIterations(
4293 Scope *S, const bool LimitedType,
4294 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004295 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00004296 Expr *
4297 buildPreCond(Scope *S, Expr *Cond,
4298 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004299 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004300 DeclRefExpr *
4301 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4302 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004303 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00004304 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004305 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004306 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004307 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004308 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004309 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004310 /// Build loop data with counter value for depend clauses in ordered
4311 /// directives.
4312 Expr *
4313 buildOrderedLoopData(Scope *S, Expr *Counter,
4314 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4315 SourceLocation Loc, Expr *Inc = nullptr,
4316 OverloadedOperatorKind OOK = OO_Amp);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004317 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00004318 bool dependent() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004319
4320private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004321 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004322 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00004323 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004324 /// Helper to set loop counter variable and its initializer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004325 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004326 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00004327 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4328 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004329 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004330 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004331};
4332
Alexey Bataeve3727102018-04-18 15:57:46 +00004333bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004334 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004335 assert(!LB && !UB && !Step);
4336 return false;
4337 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004338 return LCDecl->getType()->isDependentType() ||
4339 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4340 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004341}
4342
Alexey Bataeve3727102018-04-18 15:57:46 +00004343bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004344 Expr *NewLCRefExpr,
4345 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004346 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004347 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00004348 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004349 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004350 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004351 LCDecl = getCanonicalDecl(NewLCDecl);
4352 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004353 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4354 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004355 if ((Ctor->isCopyOrMoveConstructor() ||
4356 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4357 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004358 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004359 LB = NewLB;
4360 return false;
4361}
4362
Alexey Bataev316ccf62019-01-29 18:51:58 +00004363bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4364 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00004365 bool StrictOp, SourceRange SR,
4366 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004367 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004368 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4369 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004370 if (!NewUB)
4371 return true;
4372 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00004373 if (LessOp)
4374 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004375 TestIsStrictOp = StrictOp;
4376 ConditionSrcRange = SR;
4377 ConditionLoc = SL;
4378 return false;
4379}
4380
Alexey Bataeve3727102018-04-18 15:57:46 +00004381bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004382 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004383 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004384 if (!NewStep)
4385 return true;
4386 if (!NewStep->isValueDependent()) {
4387 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004388 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00004389 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4390 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004391 if (Val.isInvalid())
4392 return true;
4393 NewStep = Val.get();
4394
4395 // OpenMP [2.6, Canonical Loop Form, Restrictions]
4396 // If test-expr is of form var relational-op b and relational-op is < or
4397 // <= then incr-expr must cause var to increase on each iteration of the
4398 // loop. If test-expr is of form var relational-op b and relational-op is
4399 // > or >= then incr-expr must cause var to decrease on each iteration of
4400 // the loop.
4401 // If test-expr is of form b relational-op var and relational-op is < or
4402 // <= then incr-expr must cause var to decrease on each iteration of the
4403 // loop. If test-expr is of form b relational-op var and relational-op is
4404 // > or >= then incr-expr must cause var to increase on each iteration of
4405 // the loop.
4406 llvm::APSInt Result;
4407 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4408 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4409 bool IsConstNeg =
4410 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004411 bool IsConstPos =
4412 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004413 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00004414
4415 // != with increment is treated as <; != with decrement is treated as >
4416 if (!TestIsLessOp.hasValue())
4417 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004418 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004419 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004420 (IsConstNeg || (IsUnsigned && Subtract)) :
4421 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004422 SemaRef.Diag(NewStep->getExprLoc(),
4423 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004424 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004425 SemaRef.Diag(ConditionLoc,
4426 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004427 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004428 return true;
4429 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00004430 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00004431 NewStep =
4432 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4433 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004434 Subtract = !Subtract;
4435 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004436 }
4437
4438 Step = NewStep;
4439 SubtractStep = Subtract;
4440 return false;
4441}
4442
Alexey Bataeve3727102018-04-18 15:57:46 +00004443bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004444 // Check init-expr for canonical loop form and save loop counter
4445 // variable - #Var and its initialization value - #LB.
4446 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4447 // var = lb
4448 // integer-type var = lb
4449 // random-access-iterator-type var = lb
4450 // pointer-type var = lb
4451 //
4452 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00004453 if (EmitDiags) {
4454 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4455 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004456 return true;
4457 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004458 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4459 if (!ExprTemp->cleanupsHaveSideEffects())
4460 S = ExprTemp->getSubExpr();
4461
Alexander Musmana5f070a2014-10-01 06:03:56 +00004462 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004463 if (Expr *E = dyn_cast<Expr>(S))
4464 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004465 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004466 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004467 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004468 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4469 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4470 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004471 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4472 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004473 }
4474 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4475 if (ME->isArrow() &&
4476 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004477 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004478 }
4479 }
David Majnemer9d168222016-08-05 17:44:54 +00004480 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004481 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00004482 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00004483 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004484 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00004485 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004486 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004487 diag::ext_omp_loop_not_canonical_init)
4488 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00004489 return setLCDeclAndLB(
4490 Var,
4491 buildDeclRefExpr(SemaRef, Var,
4492 Var->getType().getNonReferenceType(),
4493 DS->getBeginLoc()),
4494 Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004495 }
4496 }
4497 }
David Majnemer9d168222016-08-05 17:44:54 +00004498 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004499 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004500 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00004501 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004502 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4503 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004504 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4505 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004506 }
4507 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4508 if (ME->isArrow() &&
4509 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004510 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004511 }
4512 }
4513 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004514
Alexey Bataeve3727102018-04-18 15:57:46 +00004515 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004516 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00004517 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004518 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00004519 << S->getSourceRange();
4520 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004521 return true;
4522}
4523
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004524/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004525/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00004526static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004527 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00004528 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004529 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00004530 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004531 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004532 if ((Ctor->isCopyOrMoveConstructor() ||
4533 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4534 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004535 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004536 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4537 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004538 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004539 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004540 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004541 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4542 return getCanonicalDecl(ME->getMemberDecl());
4543 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004544}
4545
Alexey Bataeve3727102018-04-18 15:57:46 +00004546bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004547 // Check test-expr for canonical form, save upper-bound UB, flags for
4548 // less/greater and for strict/non-strict comparison.
4549 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4550 // var relational-op b
4551 // b relational-op var
4552 //
4553 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004554 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004555 return true;
4556 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004557 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004558 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00004559 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004560 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004561 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4562 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004563 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4564 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4565 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004566 if (getInitLCDecl(BO->getRHS()) == LCDecl)
4567 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004568 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4569 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4570 BO->getSourceRange(), BO->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00004571 } else if (BO->getOpcode() == BO_NE)
4572 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
4573 BO->getRHS() : BO->getLHS(),
4574 /*LessOp=*/llvm::None,
4575 /*StrictOp=*/true,
4576 BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00004577 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004578 if (CE->getNumArgs() == 2) {
4579 auto Op = CE->getOperator();
4580 switch (Op) {
4581 case OO_Greater:
4582 case OO_GreaterEqual:
4583 case OO_Less:
4584 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004585 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4586 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004587 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4588 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004589 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4590 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004591 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4592 CE->getOperatorLoc());
4593 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004594 case OO_ExclaimEqual:
Kelvin Liefbe4af2018-11-21 19:10:48 +00004595 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
4596 CE->getArg(1) : CE->getArg(0),
4597 /*LessOp=*/llvm::None,
4598 /*StrictOp=*/true,
4599 CE->getSourceRange(),
4600 CE->getOperatorLoc());
4601 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004602 default:
4603 break;
4604 }
4605 }
4606 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004607 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004608 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004609 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004610 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004611 return true;
4612}
4613
Alexey Bataeve3727102018-04-18 15:57:46 +00004614bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004615 // RHS of canonical loop form increment can be:
4616 // var + incr
4617 // incr + var
4618 // var - incr
4619 //
4620 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00004621 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004622 if (BO->isAdditiveOp()) {
4623 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00004624 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4625 return setStep(BO->getRHS(), !IsAdd);
4626 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4627 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004628 }
David Majnemer9d168222016-08-05 17:44:54 +00004629 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004630 bool IsAdd = CE->getOperator() == OO_Plus;
4631 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004632 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4633 return setStep(CE->getArg(1), !IsAdd);
4634 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4635 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004636 }
4637 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004638 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004639 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004640 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004641 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004642 return true;
4643}
4644
Alexey Bataeve3727102018-04-18 15:57:46 +00004645bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004646 // Check incr-expr for canonical loop form and return true if it
4647 // does not conform.
4648 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4649 // ++var
4650 // var++
4651 // --var
4652 // var--
4653 // var += incr
4654 // var -= incr
4655 // var = var + incr
4656 // var = incr + var
4657 // var = var - incr
4658 //
4659 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004660 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004661 return true;
4662 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004663 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4664 if (!ExprTemp->cleanupsHaveSideEffects())
4665 S = ExprTemp->getSubExpr();
4666
Alexander Musmana5f070a2014-10-01 06:03:56 +00004667 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004668 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004669 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004670 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00004671 getInitLCDecl(UO->getSubExpr()) == LCDecl)
4672 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004673 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004674 (UO->isDecrementOp() ? -1 : 1))
4675 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004676 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00004677 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004678 switch (BO->getOpcode()) {
4679 case BO_AddAssign:
4680 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004681 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4682 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004683 break;
4684 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004685 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4686 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004687 break;
4688 default:
4689 break;
4690 }
David Majnemer9d168222016-08-05 17:44:54 +00004691 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004692 switch (CE->getOperator()) {
4693 case OO_PlusPlus:
4694 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00004695 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4696 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00004697 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004698 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004699 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4700 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004701 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004702 break;
4703 case OO_PlusEqual:
4704 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004705 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4706 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004707 break;
4708 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00004709 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4710 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004711 break;
4712 default:
4713 break;
4714 }
4715 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004716 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004717 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004718 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004719 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004720 return true;
4721}
Alexander Musmana5f070a2014-10-01 06:03:56 +00004722
Alexey Bataev5a3af132016-03-29 08:58:54 +00004723static ExprResult
4724tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00004725 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00004726 if (SemaRef.CurContext->isDependentContext())
4727 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004728 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4729 return SemaRef.PerformImplicitConversion(
4730 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4731 /*AllowExplicit=*/true);
4732 auto I = Captures.find(Capture);
4733 if (I != Captures.end())
4734 return buildCapture(SemaRef, Capture, I->second);
4735 DeclRefExpr *Ref = nullptr;
4736 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4737 Captures[Capture] = Ref;
4738 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004739}
4740
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004741/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004742Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004743 Scope *S, const bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00004744 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004745 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00004746 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004747 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004748 SemaRef.getLangOpts().CPlusPlus) {
4749 // Upper - Lower
Kelvin Liefbe4af2018-11-21 19:10:48 +00004750 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
4751 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004752 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4753 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004754 if (!Upper || !Lower)
4755 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004756
4757 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4758
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004759 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004760 // BuildBinOp already emitted error, this one is to point user to upper
4761 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004762 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004763 << Upper->getSourceRange() << Lower->getSourceRange();
4764 return nullptr;
4765 }
4766 }
4767
4768 if (!Diff.isUsable())
4769 return nullptr;
4770
4771 // Upper - Lower [- 1]
4772 if (TestIsStrictOp)
4773 Diff = SemaRef.BuildBinOp(
4774 S, DefaultLoc, BO_Sub, Diff.get(),
4775 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4776 if (!Diff.isUsable())
4777 return nullptr;
4778
4779 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00004780 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004781 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004782 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004783 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004784 if (!Diff.isUsable())
4785 return nullptr;
4786
4787 // Parentheses (for dumping/debugging purposes only).
4788 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4789 if (!Diff.isUsable())
4790 return nullptr;
4791
4792 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004793 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004794 if (!Diff.isUsable())
4795 return nullptr;
4796
Alexander Musman174b3ca2014-10-06 11:16:29 +00004797 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004798 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00004799 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004800 bool UseVarType = VarType->hasIntegerRepresentation() &&
4801 C.getTypeSize(Type) > C.getTypeSize(VarType);
4802 if (!Type->isIntegerType() || UseVarType) {
4803 unsigned NewSize =
4804 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4805 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4806 : Type->hasSignedIntegerRepresentation();
4807 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004808 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4809 Diff = SemaRef.PerformImplicitConversion(
4810 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4811 if (!Diff.isUsable())
4812 return nullptr;
4813 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004814 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004815 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004816 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4817 if (NewSize != C.getTypeSize(Type)) {
4818 if (NewSize < C.getTypeSize(Type)) {
4819 assert(NewSize == 64 && "incorrect loop var size");
4820 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4821 << InitSrcRange << ConditionSrcRange;
4822 }
4823 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004824 NewSize, Type->hasSignedIntegerRepresentation() ||
4825 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004826 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4827 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4828 Sema::AA_Converting, true);
4829 if (!Diff.isUsable())
4830 return nullptr;
4831 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004832 }
4833 }
4834
Alexander Musmana5f070a2014-10-01 06:03:56 +00004835 return Diff.get();
4836}
4837
Alexey Bataeve3727102018-04-18 15:57:46 +00004838Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004839 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00004840 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004841 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4842 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4843 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004844
Alexey Bataeve3727102018-04-18 15:57:46 +00004845 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4846 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004847 if (!NewLB.isUsable() || !NewUB.isUsable())
4848 return nullptr;
4849
Alexey Bataeve3727102018-04-18 15:57:46 +00004850 ExprResult CondExpr =
4851 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004852 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004853 (TestIsStrictOp ? BO_LT : BO_LE) :
4854 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00004855 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004856 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004857 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4858 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004859 CondExpr = SemaRef.PerformImplicitConversion(
4860 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4861 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004862 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004863 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00004864 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004865 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4866}
4867
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004868/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004869DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00004870 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4871 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004872 auto *VD = dyn_cast<VarDecl>(LCDecl);
4873 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004874 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4875 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004876 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004877 const DSAStackTy::DSAVarData Data =
4878 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004879 // If the loop control decl is explicitly marked as private, do not mark it
4880 // as captured again.
4881 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4882 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004883 return Ref;
4884 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00004885 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00004886}
4887
Alexey Bataeve3727102018-04-18 15:57:46 +00004888Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004889 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004890 QualType Type = LCDecl->getType().getNonReferenceType();
4891 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004892 SemaRef, DefaultLoc, Type, LCDecl->getName(),
4893 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4894 isa<VarDecl>(LCDecl)
4895 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4896 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004897 if (PrivateVar->isInvalidDecl())
4898 return nullptr;
4899 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4900 }
4901 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004902}
4903
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004904/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004905Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004906
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004907/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004908Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004909
Alexey Bataevf138fda2018-08-13 19:04:24 +00004910Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
4911 Scope *S, Expr *Counter,
4912 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
4913 Expr *Inc, OverloadedOperatorKind OOK) {
4914 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
4915 if (!Cnt)
4916 return nullptr;
4917 if (Inc) {
4918 assert((OOK == OO_Plus || OOK == OO_Minus) &&
4919 "Expected only + or - operations for depend clauses.");
4920 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
4921 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
4922 if (!Cnt)
4923 return nullptr;
4924 }
4925 ExprResult Diff;
4926 QualType VarType = LCDecl->getType().getNonReferenceType();
4927 if (VarType->isIntegerType() || VarType->isPointerType() ||
4928 SemaRef.getLangOpts().CPlusPlus) {
4929 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00004930 Expr *Upper = TestIsLessOp.getValue()
4931 ? Cnt
4932 : tryBuildCapture(SemaRef, UB, Captures).get();
4933 Expr *Lower = TestIsLessOp.getValue()
4934 ? tryBuildCapture(SemaRef, LB, Captures).get()
4935 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004936 if (!Upper || !Lower)
4937 return nullptr;
4938
4939 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4940
4941 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4942 // BuildBinOp already emitted error, this one is to point user to upper
4943 // and lower bound, and to tell what is passed to 'operator-'.
4944 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4945 << Upper->getSourceRange() << Lower->getSourceRange();
4946 return nullptr;
4947 }
4948 }
4949
4950 if (!Diff.isUsable())
4951 return nullptr;
4952
4953 // Parentheses (for dumping/debugging purposes only).
4954 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4955 if (!Diff.isUsable())
4956 return nullptr;
4957
4958 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4959 if (!NewStep.isUsable())
4960 return nullptr;
4961 // (Upper - Lower) / Step
4962 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4963 if (!Diff.isUsable())
4964 return nullptr;
4965
4966 return Diff.get();
4967}
4968
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004969/// Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004970struct LoopIterationSpace final {
Alexey Bataev316ccf62019-01-29 18:51:58 +00004971 /// True if the condition operator is the strict compare operator (<, > or
4972 /// !=).
4973 bool IsStrictCompare = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004974 /// Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004975 Expr *PreCond = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004976 /// This expression calculates the number of iterations in the loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004977 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004978 Expr *NumIterations = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004979 /// The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004980 Expr *CounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004981 /// Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004982 Expr *PrivateCounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004983 /// This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004984 Expr *CounterInit = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004985 /// This is step for the #CounterVar used to generate its update:
Alexander Musmana5f070a2014-10-01 06:03:56 +00004986 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004987 Expr *CounterStep = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004988 /// Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004989 bool Subtract = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004990 /// Source range of the loop init.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004991 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004992 /// Source range of the loop condition.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004993 SourceRange CondSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004994 /// Source range of the loop increment.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004995 SourceRange IncSrcRange;
4996};
4997
Alexey Bataev23b69422014-06-18 07:08:49 +00004998} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004999
Alexey Bataev9c821032015-04-30 04:23:23 +00005000void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
5001 assert(getLangOpts().OpenMP && "OpenMP is not active.");
5002 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005003 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
5004 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00005005 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00005006 DSAStack->loopStart();
Alexey Bataev9c821032015-04-30 04:23:23 +00005007 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00005008 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
5009 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005010 auto *VD = dyn_cast<VarDecl>(D);
5011 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005012 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005013 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00005014 } else {
5015 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
5016 /*WithInit=*/false);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005017 VD = cast<VarDecl>(Ref->getDecl());
5018 }
5019 }
5020 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005021 const Decl *LD = DSAStack->getPossiblyLoopCunter();
5022 if (LD != D->getCanonicalDecl()) {
5023 DSAStack->resetPossibleLoopCounter();
5024 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
5025 MarkDeclarationsReferencedInExpr(
5026 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
5027 Var->getType().getNonLValueExprType(Context),
5028 ForLoc, /*RefersToCapture=*/true));
5029 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005030 }
5031 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005032 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00005033 }
5034}
5035
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005036/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005037/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00005038static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00005039 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
5040 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00005041 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
5042 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00005043 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005044 LoopIterationSpace &ResultIterSpace,
Alexey Bataeve3727102018-04-18 15:57:46 +00005045 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005046 // OpenMP [2.6, Canonical Loop Form]
5047 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00005048 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005049 if (!For) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005050 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005051 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00005052 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00005053 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005054 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005055 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
5056 SemaRef.Diag(DSA.getConstructLoc(),
5057 diag::note_omp_collapse_ordered_expr)
5058 << 2 << CollapseLoopCountExpr->getSourceRange()
5059 << OrderedLoopCountExpr->getSourceRange();
5060 else if (CollapseLoopCountExpr)
5061 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5062 diag::note_omp_collapse_ordered_expr)
5063 << 0 << CollapseLoopCountExpr->getSourceRange();
5064 else
5065 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5066 diag::note_omp_collapse_ordered_expr)
5067 << 1 << OrderedLoopCountExpr->getSourceRange();
5068 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005069 return true;
5070 }
5071 assert(For->getBody());
5072
5073 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
5074
5075 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005076 Stmt *Init = For->getInit();
5077 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005078 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005079
5080 bool HasErrors = false;
5081
5082 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005083 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
5084 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005085
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005086 // OpenMP [2.6, Canonical Loop Form]
5087 // Var is one of the following:
5088 // A variable of signed or unsigned integer type.
5089 // For C++, a variable of a random access iterator type.
5090 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005091 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005092 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
5093 !VarType->isPointerType() &&
5094 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005095 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005096 << SemaRef.getLangOpts().CPlusPlus;
5097 HasErrors = true;
5098 }
5099
5100 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
5101 // a Construct
5102 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5103 // parallel for construct is (are) private.
5104 // The loop iteration variable in the associated for-loop of a simd
5105 // construct with just one associated for-loop is linear with a
5106 // constant-linear-step that is the increment of the associated for-loop.
5107 // Exclude loop var from the list of variables with implicitly defined data
5108 // sharing attributes.
5109 VarsWithImplicitDSA.erase(LCDecl);
5110
5111 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5112 // in a Construct, C/C++].
5113 // The loop iteration variable in the associated for-loop of a simd
5114 // construct with just one associated for-loop may be listed in a linear
5115 // clause with a constant-linear-step that is the increment of the
5116 // associated for-loop.
5117 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5118 // parallel for construct may be listed in a private or lastprivate clause.
5119 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
5120 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
5121 // declared in the loop and it is predetermined as a private.
Alexey Bataeve3727102018-04-18 15:57:46 +00005122 OpenMPClauseKind PredeterminedCKind =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005123 isOpenMPSimdDirective(DKind)
5124 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
5125 : OMPC_private;
5126 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5127 DVar.CKind != PredeterminedCKind) ||
5128 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
5129 isOpenMPDistributeDirective(DKind)) &&
5130 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5131 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
5132 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005133 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005134 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
5135 << getOpenMPClauseName(PredeterminedCKind);
5136 if (DVar.RefExpr == nullptr)
5137 DVar.CKind = PredeterminedCKind;
Alexey Bataeve3727102018-04-18 15:57:46 +00005138 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005139 HasErrors = true;
5140 } else if (LoopDeclRefExpr != nullptr) {
5141 // Make the loop iteration variable private (for worksharing constructs),
5142 // linear (for simd directives with the only one associated loop) or
5143 // lastprivate (for simd directives with several collapsed or ordered
5144 // loops).
5145 if (DVar.CKind == OMPC_unknown)
Alexey Bataevc2cdff62019-01-29 21:12:28 +00005146 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005147 }
5148
5149 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
5150
5151 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005152 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005153
5154 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005155 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005156 }
5157
Alexey Bataeve3727102018-04-18 15:57:46 +00005158 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005159 return HasErrors;
5160
Alexander Musmana5f070a2014-10-01 06:03:56 +00005161 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005162 ResultIterSpace.PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00005163 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
5164 ResultIterSpace.NumIterations = ISC.buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005165 DSA.getCurScope(),
5166 (isOpenMPWorksharingDirective(DKind) ||
5167 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
5168 Captures);
Alexey Bataeve3727102018-04-18 15:57:46 +00005169 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
5170 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
5171 ResultIterSpace.CounterInit = ISC.buildCounterInit();
5172 ResultIterSpace.CounterStep = ISC.buildCounterStep();
5173 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
5174 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
5175 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
5176 ResultIterSpace.Subtract = ISC.shouldSubtractStep();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005177 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005178
Alexey Bataev62dbb972015-04-22 11:59:37 +00005179 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
5180 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005181 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00005182 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005183 ResultIterSpace.CounterInit == nullptr ||
5184 ResultIterSpace.CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00005185 if (!HasErrors && DSA.isOrderedRegion()) {
5186 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
5187 if (CurrentNestedLoopCount <
5188 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
5189 DSA.getOrderedRegionParam().second->setLoopNumIterations(
5190 CurrentNestedLoopCount, ResultIterSpace.NumIterations);
5191 DSA.getOrderedRegionParam().second->setLoopCounter(
5192 CurrentNestedLoopCount, ResultIterSpace.CounterVar);
5193 }
5194 }
5195 for (auto &Pair : DSA.getDoacrossDependClauses()) {
5196 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
5197 // Erroneous case - clause has some problems.
5198 continue;
5199 }
5200 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
5201 Pair.second.size() <= CurrentNestedLoopCount) {
5202 // Erroneous case - clause has some problems.
5203 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
5204 continue;
5205 }
5206 Expr *CntValue;
5207 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5208 CntValue = ISC.buildOrderedLoopData(
5209 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5210 Pair.first->getDependencyLoc());
5211 else
5212 CntValue = ISC.buildOrderedLoopData(
5213 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5214 Pair.first->getDependencyLoc(),
5215 Pair.second[CurrentNestedLoopCount].first,
5216 Pair.second[CurrentNestedLoopCount].second);
5217 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
5218 }
5219 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005220
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005221 return HasErrors;
5222}
5223
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005224/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005225static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00005226buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005227 ExprResult Start,
Alexey Bataeve3727102018-04-18 15:57:46 +00005228 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005229 // Build 'VarRef = Start.
Alexey Bataeve3727102018-04-18 15:57:46 +00005230 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005231 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005232 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00005233 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00005234 VarRef.get()->getType())) {
5235 NewStart = SemaRef.PerformImplicitConversion(
5236 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
5237 /*AllowExplicit=*/true);
5238 if (!NewStart.isUsable())
5239 return ExprError();
5240 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005241
Alexey Bataeve3727102018-04-18 15:57:46 +00005242 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005243 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5244 return Init;
5245}
5246
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005247/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00005248static ExprResult buildCounterUpdate(
5249 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5250 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
5251 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005252 // Add parentheses (for debugging purposes only).
5253 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
5254 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
5255 !Step.isUsable())
5256 return ExprError();
5257
Alexey Bataev5a3af132016-03-29 08:58:54 +00005258 ExprResult NewStep = Step;
5259 if (Captures)
5260 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005261 if (NewStep.isInvalid())
5262 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005263 ExprResult Update =
5264 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005265 if (!Update.isUsable())
5266 return ExprError();
5267
Alexey Bataevc0214e02016-02-16 12:13:49 +00005268 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
5269 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005270 ExprResult NewStart = Start;
5271 if (Captures)
5272 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005273 if (NewStart.isInvalid())
5274 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005275
Alexey Bataevc0214e02016-02-16 12:13:49 +00005276 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5277 ExprResult SavedUpdate = Update;
5278 ExprResult UpdateVal;
5279 if (VarRef.get()->getType()->isOverloadableType() ||
5280 NewStart.get()->getType()->isOverloadableType() ||
5281 Update.get()->getType()->isOverloadableType()) {
5282 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5283 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5284 Update =
5285 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5286 if (Update.isUsable()) {
5287 UpdateVal =
5288 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5289 VarRef.get(), SavedUpdate.get());
5290 if (UpdateVal.isUsable()) {
5291 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5292 UpdateVal.get());
5293 }
5294 }
5295 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5296 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005297
Alexey Bataevc0214e02016-02-16 12:13:49 +00005298 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5299 if (!Update.isUsable() || !UpdateVal.isUsable()) {
5300 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5301 NewStart.get(), SavedUpdate.get());
5302 if (!Update.isUsable())
5303 return ExprError();
5304
Alexey Bataev11481f52016-02-17 10:29:05 +00005305 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5306 VarRef.get()->getType())) {
5307 Update = SemaRef.PerformImplicitConversion(
5308 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5309 if (!Update.isUsable())
5310 return ExprError();
5311 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00005312
5313 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5314 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005315 return Update;
5316}
5317
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005318/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005319/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005320static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005321 if (E == nullptr)
5322 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00005323 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005324 QualType OldType = E->getType();
5325 unsigned HasBits = C.getTypeSize(OldType);
5326 if (HasBits >= Bits)
5327 return ExprResult(E);
5328 // OK to convert to signed, because new type has more bits than old.
5329 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5330 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5331 true);
5332}
5333
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005334/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005335/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005336static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005337 if (E == nullptr)
5338 return false;
5339 llvm::APSInt Result;
5340 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5341 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5342 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005343}
5344
Alexey Bataev5a3af132016-03-29 08:58:54 +00005345/// Build preinits statement for the given declarations.
5346static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00005347 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005348 if (!PreInits.empty()) {
5349 return new (Context) DeclStmt(
5350 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5351 SourceLocation(), SourceLocation());
5352 }
5353 return nullptr;
5354}
5355
5356/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00005357static Stmt *
5358buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00005359 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005360 if (!Captures.empty()) {
5361 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00005362 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00005363 PreInits.push_back(Pair.second->getDecl());
5364 return buildPreInits(Context, PreInits);
5365 }
5366 return nullptr;
5367}
5368
5369/// Build postupdate expression for the given list of postupdates expressions.
5370static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5371 Expr *PostUpdate = nullptr;
5372 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005373 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005374 Expr *ConvE = S.BuildCStyleCastExpr(
5375 E->getExprLoc(),
5376 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5377 E->getExprLoc(), E)
5378 .get();
5379 PostUpdate = PostUpdate
5380 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5381 PostUpdate, ConvE)
5382 .get()
5383 : ConvE;
5384 }
5385 }
5386 return PostUpdate;
5387}
5388
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005389/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00005390/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5391/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005392static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00005393checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00005394 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5395 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00005396 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00005397 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005398 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005399 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005400 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005401 Expr::EvalResult Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005402 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Fangrui Song407659a2018-11-30 23:41:18 +00005403 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005404 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005405 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005406 if (OrderedLoopCountExpr) {
5407 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005408 Expr::EvalResult EVResult;
5409 if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5410 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005411 if (Result.getLimitedValue() < NestedLoopCount) {
5412 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5413 diag::err_omp_wrong_ordered_loop_count)
5414 << OrderedLoopCountExpr->getSourceRange();
5415 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5416 diag::note_collapse_loop_count)
5417 << CollapseLoopCountExpr->getSourceRange();
5418 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005419 OrderedLoopCount = Result.getLimitedValue();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005420 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005421 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005422 // This is helper routine for loop directives (e.g., 'for', 'simd',
5423 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00005424 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00005425 SmallVector<LoopIterationSpace, 4> IterSpaces(
5426 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00005427 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005428 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005429 if (checkOpenMPIterationSpace(
5430 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5431 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5432 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5433 Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00005434 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005435 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005436 // OpenMP [2.8.1, simd construct, Restrictions]
5437 // All loops associated with the construct must be perfectly nested; that
5438 // is, there must be no intervening code nor any OpenMP directive between
5439 // any two loops.
5440 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005441 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005442 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5443 if (checkOpenMPIterationSpace(
5444 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5445 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5446 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5447 Captures))
5448 return 0;
5449 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5450 // Handle initialization of captured loop iterator variables.
5451 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5452 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5453 Captures[DRE] = DRE;
5454 }
5455 }
5456 // Move on to the next nested for loop, or to the loop body.
5457 // OpenMP [2.8.1, simd construct, Restrictions]
5458 // All loops associated with the construct must be perfectly nested; that
5459 // is, there must be no intervening code nor any OpenMP directive between
5460 // any two loops.
5461 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5462 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005463
Alexander Musmana5f070a2014-10-01 06:03:56 +00005464 Built.clear(/* size */ NestedLoopCount);
5465
5466 if (SemaRef.CurContext->isDependentContext())
5467 return NestedLoopCount;
5468
5469 // An example of what is generated for the following code:
5470 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00005471 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00005472 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005473 // for (k = 0; k < NK; ++k)
5474 // for (j = J0; j < NJ; j+=2) {
5475 // <loop body>
5476 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005477 //
5478 // We generate the code below.
5479 // Note: the loop body may be outlined in CodeGen.
5480 // Note: some counters may be C++ classes, operator- is used to find number of
5481 // iterations and operator+= to calculate counter value.
5482 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5483 // or i64 is currently supported).
5484 //
5485 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5486 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5487 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5488 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5489 // // similar updates for vars in clauses (e.g. 'linear')
5490 // <loop body (using local i and j)>
5491 // }
5492 // i = NI; // assign final values of counters
5493 // j = NJ;
5494 //
5495
5496 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5497 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00005498 // Precondition tests if there is at least one iteration (all conditions are
5499 // true).
5500 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00005501 Expr *N0 = IterSpaces[0].NumIterations;
5502 ExprResult LastIteration32 =
5503 widenIterationCount(/*Bits=*/32,
5504 SemaRef
5505 .PerformImplicitConversion(
5506 N0->IgnoreImpCasts(), N0->getType(),
5507 Sema::AA_Converting, /*AllowExplicit=*/true)
5508 .get(),
5509 SemaRef);
5510 ExprResult LastIteration64 = widenIterationCount(
5511 /*Bits=*/64,
5512 SemaRef
5513 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5514 Sema::AA_Converting,
5515 /*AllowExplicit=*/true)
5516 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005517 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005518
5519 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5520 return NestedLoopCount;
5521
Alexey Bataeve3727102018-04-18 15:57:46 +00005522 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005523 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5524
5525 Scope *CurScope = DSA.getCurScope();
5526 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00005527 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00005528 PreCond =
5529 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5530 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00005531 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005532 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00005533 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005534 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5535 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005536 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005537 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005538 SemaRef
5539 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5540 Sema::AA_Converting,
5541 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005542 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005543 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005544 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005545 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005546 SemaRef
5547 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5548 Sema::AA_Converting,
5549 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005550 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005551 }
5552
5553 // Choose either the 32-bit or 64-bit version.
5554 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005555 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
5556 (LastIteration32.isUsable() &&
5557 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5558 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5559 fitsInto(
5560 /*Bits=*/32,
5561 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5562 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00005563 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00005564 QualType VType = LastIteration.get()->getType();
5565 QualType RealVType = VType;
5566 QualType StrideVType = VType;
5567 if (isOpenMPTaskLoopDirective(DKind)) {
5568 VType =
5569 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5570 StrideVType =
5571 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5572 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005573
5574 if (!LastIteration.isUsable())
5575 return 0;
5576
5577 // Save the number of iterations.
5578 ExprResult NumIterations = LastIteration;
5579 {
5580 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005581 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5582 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005583 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5584 if (!LastIteration.isUsable())
5585 return 0;
5586 }
5587
5588 // Calculate the last iteration number beforehand instead of doing this on
5589 // each iteration. Do not do this if the number of iterations may be kfold-ed.
5590 llvm::APSInt Result;
5591 bool IsConstant =
5592 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5593 ExprResult CalcLastIteration;
5594 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005595 ExprResult SaveRef =
5596 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005597 LastIteration = SaveRef;
5598
5599 // Prepare SaveRef + 1.
5600 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005601 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005602 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5603 if (!NumIterations.isUsable())
5604 return 0;
5605 }
5606
5607 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5608
David Majnemer9d168222016-08-05 17:44:54 +00005609 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005610 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005611 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5612 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005613 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005614 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5615 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005616 SemaRef.AddInitializerToDecl(LBDecl,
5617 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5618 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005619
5620 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005621 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
5622 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00005623 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00005624 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005625
5626 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
5627 // This will be used to implement clause 'lastprivate'.
5628 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005629 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
5630 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005631 SemaRef.AddInitializerToDecl(ILDecl,
5632 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5633 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005634
5635 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00005636 VarDecl *STDecl =
5637 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
5638 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005639 SemaRef.AddInitializerToDecl(STDecl,
5640 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
5641 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005642
5643 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00005644 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00005645 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
5646 UB.get(), LastIteration.get());
5647 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00005648 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
5649 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00005650 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
5651 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005652 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005653
5654 // If we have a combined directive that combines 'distribute', 'for' or
5655 // 'simd' we need to be able to access the bounds of the schedule of the
5656 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
5657 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
5658 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00005659 // Lower bound variable, initialized with zero.
5660 VarDecl *CombLBDecl =
5661 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
5662 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
5663 SemaRef.AddInitializerToDecl(
5664 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5665 /*DirectInit*/ false);
5666
5667 // Upper bound variable, initialized with last iteration number.
5668 VarDecl *CombUBDecl =
5669 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
5670 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
5671 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
5672 /*DirectInit*/ false);
5673
5674 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
5675 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
5676 ExprResult CombCondOp =
5677 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
5678 LastIteration.get(), CombUB.get());
5679 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
5680 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005681 CombEUB =
5682 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005683
Alexey Bataeve3727102018-04-18 15:57:46 +00005684 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005685 // We expect to have at least 2 more parameters than the 'parallel'
5686 // directive does - the lower and upper bounds of the previous schedule.
5687 assert(CD->getNumParams() >= 4 &&
5688 "Unexpected number of parameters in loop combined directive");
5689
5690 // Set the proper type for the bounds given what we learned from the
5691 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005692 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
5693 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005694
5695 // Previous lower and upper bounds are obtained from the region
5696 // parameters.
5697 PrevLB =
5698 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
5699 PrevUB =
5700 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
5701 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005702 }
5703
5704 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005705 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005706 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005707 {
Alexey Bataev7292c292016-04-25 12:22:29 +00005708 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
5709 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00005710 Expr *RHS =
5711 (isOpenMPWorksharingDirective(DKind) ||
5712 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5713 ? LB.get()
5714 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005715 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005716 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005717
5718 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5719 Expr *CombRHS =
5720 (isOpenMPWorksharingDirective(DKind) ||
5721 isOpenMPTaskLoopDirective(DKind) ||
5722 isOpenMPDistributeDirective(DKind))
5723 ? CombLB.get()
5724 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5725 CombInit =
5726 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005727 CombInit =
5728 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005729 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005730 }
5731
Alexey Bataev316ccf62019-01-29 18:51:58 +00005732 bool UseStrictCompare =
5733 RealVType->hasUnsignedIntegerRepresentation() &&
5734 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
5735 return LIS.IsStrictCompare;
5736 });
5737 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
5738 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005739 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005740 Expr *BoundUB = UB.get();
5741 if (UseStrictCompare) {
5742 BoundUB =
5743 SemaRef
5744 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
5745 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5746 .get();
5747 BoundUB =
5748 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
5749 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005750 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005751 (isOpenMPWorksharingDirective(DKind) ||
5752 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00005753 ? SemaRef.BuildBinOp(CurScope, CondLoc,
5754 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
5755 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00005756 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5757 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005758 ExprResult CombDistCond;
5759 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005760 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5761 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005762 }
5763
Carlo Bertolliffafe102017-04-20 00:39:39 +00005764 ExprResult CombCond;
5765 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005766 Expr *BoundCombUB = CombUB.get();
5767 if (UseStrictCompare) {
5768 BoundCombUB =
5769 SemaRef
5770 .BuildBinOp(
5771 CurScope, CondLoc, BO_Add, BoundCombUB,
5772 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5773 .get();
5774 BoundCombUB =
5775 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
5776 .get();
5777 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00005778 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005779 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5780 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005781 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005782 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005783 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005784 ExprResult Inc =
5785 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5786 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5787 if (!Inc.isUsable())
5788 return 0;
5789 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005790 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005791 if (!Inc.isUsable())
5792 return 0;
5793
5794 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5795 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005796 // In combined construct, add combined version that use CombLB and CombUB
5797 // base variables for the update
5798 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005799 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5800 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005801 // LB + ST
5802 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5803 if (!NextLB.isUsable())
5804 return 0;
5805 // LB = LB + ST
5806 NextLB =
5807 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005808 NextLB =
5809 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005810 if (!NextLB.isUsable())
5811 return 0;
5812 // UB + ST
5813 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5814 if (!NextUB.isUsable())
5815 return 0;
5816 // UB = UB + ST
5817 NextUB =
5818 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005819 NextUB =
5820 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005821 if (!NextUB.isUsable())
5822 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005823 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5824 CombNextLB =
5825 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5826 if (!NextLB.isUsable())
5827 return 0;
5828 // LB = LB + ST
5829 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5830 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005831 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
5832 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005833 if (!CombNextLB.isUsable())
5834 return 0;
5835 // UB + ST
5836 CombNextUB =
5837 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5838 if (!CombNextUB.isUsable())
5839 return 0;
5840 // UB = UB + ST
5841 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5842 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005843 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
5844 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005845 if (!CombNextUB.isUsable())
5846 return 0;
5847 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005848 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005849
Carlo Bertolliffafe102017-04-20 00:39:39 +00005850 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00005851 // directive with for as IV = IV + ST; ensure upper bound expression based
5852 // on PrevUB instead of NumIterations - used to implement 'for' when found
5853 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005854 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005855 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00005856 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005857 DistCond = SemaRef.BuildBinOp(
5858 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005859 assert(DistCond.isUsable() && "distribute cond expr was not built");
5860
5861 DistInc =
5862 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5863 assert(DistInc.isUsable() && "distribute inc expr was not built");
5864 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5865 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005866 DistInc =
5867 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005868 assert(DistInc.isUsable() && "distribute inc expr was not built");
5869
5870 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5871 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005872 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005873 ExprResult IsUBGreater =
5874 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5875 ExprResult CondOp = SemaRef.ActOnConditionalOp(
5876 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5877 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5878 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005879 PrevEUB =
5880 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005881
Alexey Bataev316ccf62019-01-29 18:51:58 +00005882 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
5883 // parallel for is in combination with a distribute directive with
5884 // schedule(static, 1)
5885 Expr *BoundPrevUB = PrevUB.get();
5886 if (UseStrictCompare) {
5887 BoundPrevUB =
5888 SemaRef
5889 .BuildBinOp(
5890 CurScope, CondLoc, BO_Add, BoundPrevUB,
5891 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5892 .get();
5893 BoundPrevUB =
5894 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
5895 .get();
5896 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005897 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005898 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5899 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005900 }
5901
Alexander Musmana5f070a2014-10-01 06:03:56 +00005902 // Build updates and final values of the loop counters.
5903 bool HasErrors = false;
5904 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005905 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005906 Built.Updates.resize(NestedLoopCount);
5907 Built.Finals.resize(NestedLoopCount);
5908 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005909 // We implement the following algorithm for obtaining the
5910 // original loop iteration variable values based on the
5911 // value of the collapsed loop iteration variable IV.
5912 //
5913 // Let n+1 be the number of collapsed loops in the nest.
5914 // Iteration variables (I0, I1, .... In)
5915 // Iteration counts (N0, N1, ... Nn)
5916 //
5917 // Acc = IV;
5918 //
5919 // To compute Ik for loop k, 0 <= k <= n, generate:
5920 // Prod = N(k+1) * N(k+2) * ... * Nn;
5921 // Ik = Acc / Prod;
5922 // Acc -= Ik * Prod;
5923 //
5924 ExprResult Acc = IV;
5925 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005926 LoopIterationSpace &IS = IterSpaces[Cnt];
5927 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005928 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005929
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005930 // Compute prod
5931 ExprResult Prod =
5932 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5933 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
5934 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
5935 IterSpaces[K].NumIterations);
5936
5937 // Iter = Acc / Prod
5938 // If there is at least one more inner loop to avoid
5939 // multiplication by 1.
5940 if (Cnt + 1 < NestedLoopCount)
5941 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
5942 Acc.get(), Prod.get());
5943 else
5944 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005945 if (!Iter.isUsable()) {
5946 HasErrors = true;
5947 break;
5948 }
5949
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005950 // Update Acc:
5951 // Acc -= Iter * Prod
5952 // Check if there is at least one more inner loop to avoid
5953 // multiplication by 1.
5954 if (Cnt + 1 < NestedLoopCount)
5955 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
5956 Iter.get(), Prod.get());
5957 else
5958 Prod = Iter;
5959 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
5960 Acc.get(), Prod.get());
5961
Alexey Bataev39f915b82015-05-08 10:41:21 +00005962 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005963 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00005964 DeclRefExpr *CounterVar = buildDeclRefExpr(
5965 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5966 /*RefersToCapture=*/true);
5967 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005968 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005969 if (!Init.isUsable()) {
5970 HasErrors = true;
5971 break;
5972 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005973 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005974 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5975 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005976 if (!Update.isUsable()) {
5977 HasErrors = true;
5978 break;
5979 }
5980
5981 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataeve3727102018-04-18 15:57:46 +00005982 ExprResult Final = buildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00005983 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005984 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005985 if (!Final.isUsable()) {
5986 HasErrors = true;
5987 break;
5988 }
5989
Alexander Musmana5f070a2014-10-01 06:03:56 +00005990 if (!Update.isUsable() || !Final.isUsable()) {
5991 HasErrors = true;
5992 break;
5993 }
5994 // Save results
5995 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00005996 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005997 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005998 Built.Updates[Cnt] = Update.get();
5999 Built.Finals[Cnt] = Final.get();
6000 }
6001 }
6002
6003 if (HasErrors)
6004 return 0;
6005
6006 // Save results
6007 Built.IterationVarRef = IV.get();
6008 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00006009 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006010 Built.CalcLastIteration = SemaRef
6011 .ActOnFinishFullExpr(CalcLastIteration.get(),
6012 /*DiscardedValue*/ false)
6013 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006014 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00006015 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006016 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006017 Built.Init = Init.get();
6018 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00006019 Built.LB = LB.get();
6020 Built.UB = UB.get();
6021 Built.IL = IL.get();
6022 Built.ST = ST.get();
6023 Built.EUB = EUB.get();
6024 Built.NLB = NextLB.get();
6025 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00006026 Built.PrevLB = PrevLB.get();
6027 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00006028 Built.DistInc = DistInc.get();
6029 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00006030 Built.DistCombinedFields.LB = CombLB.get();
6031 Built.DistCombinedFields.UB = CombUB.get();
6032 Built.DistCombinedFields.EUB = CombEUB.get();
6033 Built.DistCombinedFields.Init = CombInit.get();
6034 Built.DistCombinedFields.Cond = CombCond.get();
6035 Built.DistCombinedFields.NLB = CombNextLB.get();
6036 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006037 Built.DistCombinedFields.DistCond = CombDistCond.get();
6038 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006039
Alexey Bataevabfc0692014-06-25 06:52:00 +00006040 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006041}
6042
Alexey Bataev10e775f2015-07-30 11:36:16 +00006043static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006044 auto CollapseClauses =
6045 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
6046 if (CollapseClauses.begin() != CollapseClauses.end())
6047 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006048 return nullptr;
6049}
6050
Alexey Bataev10e775f2015-07-30 11:36:16 +00006051static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006052 auto OrderedClauses =
6053 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
6054 if (OrderedClauses.begin() != OrderedClauses.end())
6055 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00006056 return nullptr;
6057}
6058
Kelvin Lic5609492016-07-15 04:39:07 +00006059static bool checkSimdlenSafelenSpecified(Sema &S,
6060 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006061 const OMPSafelenClause *Safelen = nullptr;
6062 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00006063
Alexey Bataeve3727102018-04-18 15:57:46 +00006064 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00006065 if (Clause->getClauseKind() == OMPC_safelen)
6066 Safelen = cast<OMPSafelenClause>(Clause);
6067 else if (Clause->getClauseKind() == OMPC_simdlen)
6068 Simdlen = cast<OMPSimdlenClause>(Clause);
6069 if (Safelen && Simdlen)
6070 break;
6071 }
6072
6073 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006074 const Expr *SimdlenLength = Simdlen->getSimdlen();
6075 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00006076 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
6077 SimdlenLength->isInstantiationDependent() ||
6078 SimdlenLength->containsUnexpandedParameterPack())
6079 return false;
6080 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
6081 SafelenLength->isInstantiationDependent() ||
6082 SafelenLength->containsUnexpandedParameterPack())
6083 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00006084 Expr::EvalResult SimdlenResult, SafelenResult;
6085 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
6086 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
6087 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
6088 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00006089 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
6090 // If both simdlen and safelen clauses are specified, the value of the
6091 // simdlen parameter must be less than or equal to the value of the safelen
6092 // parameter.
6093 if (SimdlenRes > SafelenRes) {
6094 S.Diag(SimdlenLength->getExprLoc(),
6095 diag::err_omp_wrong_simdlen_safelen_values)
6096 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
6097 return true;
6098 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00006099 }
6100 return false;
6101}
6102
Alexey Bataeve3727102018-04-18 15:57:46 +00006103StmtResult
6104Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6105 SourceLocation StartLoc, SourceLocation EndLoc,
6106 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006107 if (!AStmt)
6108 return StmtError();
6109
6110 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006111 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006112 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6113 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006114 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006115 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6116 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006117 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006118 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006119
Alexander Musmana5f070a2014-10-01 06:03:56 +00006120 assert((CurContext->isDependentContext() || B.builtAll()) &&
6121 "omp simd loop exprs were not built");
6122
Alexander Musman3276a272015-03-21 10:12:56 +00006123 if (!CurContext->isDependentContext()) {
6124 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006125 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006126 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00006127 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006128 B.NumIterations, *this, CurScope,
6129 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00006130 return StmtError();
6131 }
6132 }
6133
Kelvin Lic5609492016-07-15 04:39:07 +00006134 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006135 return StmtError();
6136
Reid Kleckner87a31802018-03-12 21:43:02 +00006137 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006138 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6139 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006140}
6141
Alexey Bataeve3727102018-04-18 15:57:46 +00006142StmtResult
6143Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6144 SourceLocation StartLoc, SourceLocation EndLoc,
6145 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006146 if (!AStmt)
6147 return StmtError();
6148
6149 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006150 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006151 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6152 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006153 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006154 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6155 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006156 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00006157 return StmtError();
6158
Alexander Musmana5f070a2014-10-01 06:03:56 +00006159 assert((CurContext->isDependentContext() || B.builtAll()) &&
6160 "omp for loop exprs were not built");
6161
Alexey Bataev54acd402015-08-04 11:18:19 +00006162 if (!CurContext->isDependentContext()) {
6163 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006164 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006165 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006166 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006167 B.NumIterations, *this, CurScope,
6168 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006169 return StmtError();
6170 }
6171 }
6172
Reid Kleckner87a31802018-03-12 21:43:02 +00006173 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006174 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006175 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00006176}
6177
Alexander Musmanf82886e2014-09-18 05:12:34 +00006178StmtResult Sema::ActOnOpenMPForSimdDirective(
6179 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006180 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006181 if (!AStmt)
6182 return StmtError();
6183
6184 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006185 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006186 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6187 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00006188 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006189 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006190 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6191 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006192 if (NestedLoopCount == 0)
6193 return StmtError();
6194
Alexander Musmanc6388682014-12-15 07:07:06 +00006195 assert((CurContext->isDependentContext() || B.builtAll()) &&
6196 "omp for simd loop exprs were not built");
6197
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006198 if (!CurContext->isDependentContext()) {
6199 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006200 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006201 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006202 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006203 B.NumIterations, *this, CurScope,
6204 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006205 return StmtError();
6206 }
6207 }
6208
Kelvin Lic5609492016-07-15 04:39:07 +00006209 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006210 return StmtError();
6211
Reid Kleckner87a31802018-03-12 21:43:02 +00006212 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006213 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6214 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006215}
6216
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006217StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
6218 Stmt *AStmt,
6219 SourceLocation StartLoc,
6220 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006221 if (!AStmt)
6222 return StmtError();
6223
6224 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006225 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006226 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006227 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006228 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006229 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006230 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006231 return StmtError();
6232 // All associated statements must be '#pragma omp section' except for
6233 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006234 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006235 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6236 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006237 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006238 diag::err_omp_sections_substmt_not_section);
6239 return StmtError();
6240 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006241 cast<OMPSectionDirective>(SectionStmt)
6242 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006243 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006244 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006245 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006246 return StmtError();
6247 }
6248
Reid Kleckner87a31802018-03-12 21:43:02 +00006249 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006250
Alexey Bataev25e5b442015-09-15 12:52:43 +00006251 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6252 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006253}
6254
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006255StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
6256 SourceLocation StartLoc,
6257 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006258 if (!AStmt)
6259 return StmtError();
6260
6261 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006262
Reid Kleckner87a31802018-03-12 21:43:02 +00006263 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00006264 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006265
Alexey Bataev25e5b442015-09-15 12:52:43 +00006266 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
6267 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006268}
6269
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006270StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
6271 Stmt *AStmt,
6272 SourceLocation StartLoc,
6273 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006274 if (!AStmt)
6275 return StmtError();
6276
6277 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00006278
Reid Kleckner87a31802018-03-12 21:43:02 +00006279 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00006280
Alexey Bataev3255bf32015-01-19 05:20:46 +00006281 // OpenMP [2.7.3, single Construct, Restrictions]
6282 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00006283 const OMPClause *Nowait = nullptr;
6284 const OMPClause *Copyprivate = nullptr;
6285 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00006286 if (Clause->getClauseKind() == OMPC_nowait)
6287 Nowait = Clause;
6288 else if (Clause->getClauseKind() == OMPC_copyprivate)
6289 Copyprivate = Clause;
6290 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006291 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00006292 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006293 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00006294 return StmtError();
6295 }
6296 }
6297
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006298 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6299}
6300
Alexander Musman80c22892014-07-17 08:54:58 +00006301StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6302 SourceLocation StartLoc,
6303 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006304 if (!AStmt)
6305 return StmtError();
6306
6307 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00006308
Reid Kleckner87a31802018-03-12 21:43:02 +00006309 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00006310
6311 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6312}
6313
Alexey Bataev28c75412015-12-15 08:19:24 +00006314StmtResult Sema::ActOnOpenMPCriticalDirective(
6315 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6316 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006317 if (!AStmt)
6318 return StmtError();
6319
6320 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006321
Alexey Bataev28c75412015-12-15 08:19:24 +00006322 bool ErrorFound = false;
6323 llvm::APSInt Hint;
6324 SourceLocation HintLoc;
6325 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006326 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006327 if (C->getClauseKind() == OMPC_hint) {
6328 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006329 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00006330 ErrorFound = true;
6331 }
6332 Expr *E = cast<OMPHintClause>(C)->getHint();
6333 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00006334 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006335 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006336 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00006337 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006338 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00006339 }
6340 }
6341 }
6342 if (ErrorFound)
6343 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006344 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00006345 if (Pair.first && DirName.getName() && !DependentHint) {
6346 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6347 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00006348 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00006349 Diag(HintLoc, diag::note_omp_critical_hint_here)
6350 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006351 else
Alexey Bataev28c75412015-12-15 08:19:24 +00006352 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00006353 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006354 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00006355 << 1
6356 << C->getHint()->EvaluateKnownConstInt(Context).toString(
6357 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006358 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006359 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00006360 }
Alexey Bataev28c75412015-12-15 08:19:24 +00006361 }
6362 }
6363
Reid Kleckner87a31802018-03-12 21:43:02 +00006364 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006365
Alexey Bataev28c75412015-12-15 08:19:24 +00006366 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6367 Clauses, AStmt);
6368 if (!Pair.first && DirName.getName() && !DependentHint)
6369 DSAStack->addCriticalWithHint(Dir, Hint);
6370 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006371}
6372
Alexey Bataev4acb8592014-07-07 13:01:15 +00006373StmtResult Sema::ActOnOpenMPParallelForDirective(
6374 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006375 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006376 if (!AStmt)
6377 return StmtError();
6378
Alexey Bataeve3727102018-04-18 15:57:46 +00006379 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006380 // 1.2.2 OpenMP Language Terminology
6381 // Structured block - An executable statement with a single entry at the
6382 // top and a single exit at the bottom.
6383 // The point of exit cannot be a branch out of the structured block.
6384 // longjmp() and throw() must not violate the entry/exit criteria.
6385 CS->getCapturedDecl()->setNothrow();
6386
Alexander Musmanc6388682014-12-15 07:07:06 +00006387 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006388 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6389 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006390 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006391 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006392 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6393 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006394 if (NestedLoopCount == 0)
6395 return StmtError();
6396
Alexander Musmana5f070a2014-10-01 06:03:56 +00006397 assert((CurContext->isDependentContext() || B.builtAll()) &&
6398 "omp parallel for loop exprs were not built");
6399
Alexey Bataev54acd402015-08-04 11:18:19 +00006400 if (!CurContext->isDependentContext()) {
6401 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006402 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006403 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006404 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006405 B.NumIterations, *this, CurScope,
6406 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006407 return StmtError();
6408 }
6409 }
6410
Reid Kleckner87a31802018-03-12 21:43:02 +00006411 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006412 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006413 NestedLoopCount, Clauses, AStmt, B,
6414 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00006415}
6416
Alexander Musmane4e893b2014-09-23 09:33:00 +00006417StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6418 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006419 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006420 if (!AStmt)
6421 return StmtError();
6422
Alexey Bataeve3727102018-04-18 15:57:46 +00006423 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006424 // 1.2.2 OpenMP Language Terminology
6425 // Structured block - An executable statement with a single entry at the
6426 // top and a single exit at the bottom.
6427 // The point of exit cannot be a branch out of the structured block.
6428 // longjmp() and throw() must not violate the entry/exit criteria.
6429 CS->getCapturedDecl()->setNothrow();
6430
Alexander Musmanc6388682014-12-15 07:07:06 +00006431 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006432 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6433 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00006434 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006435 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006436 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6437 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006438 if (NestedLoopCount == 0)
6439 return StmtError();
6440
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006441 if (!CurContext->isDependentContext()) {
6442 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006443 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006444 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006445 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006446 B.NumIterations, *this, CurScope,
6447 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006448 return StmtError();
6449 }
6450 }
6451
Kelvin Lic5609492016-07-15 04:39:07 +00006452 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006453 return StmtError();
6454
Reid Kleckner87a31802018-03-12 21:43:02 +00006455 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006456 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00006457 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006458}
6459
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006460StmtResult
6461Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6462 Stmt *AStmt, SourceLocation StartLoc,
6463 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006464 if (!AStmt)
6465 return StmtError();
6466
6467 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006468 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006469 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006470 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006471 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006472 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006473 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006474 return StmtError();
6475 // All associated statements must be '#pragma omp section' except for
6476 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006477 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006478 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6479 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006480 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006481 diag::err_omp_parallel_sections_substmt_not_section);
6482 return StmtError();
6483 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006484 cast<OMPSectionDirective>(SectionStmt)
6485 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006486 }
6487 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006488 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006489 diag::err_omp_parallel_sections_not_compound_stmt);
6490 return StmtError();
6491 }
6492
Reid Kleckner87a31802018-03-12 21:43:02 +00006493 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006494
Alexey Bataev25e5b442015-09-15 12:52:43 +00006495 return OMPParallelSectionsDirective::Create(
6496 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006497}
6498
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006499StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6500 Stmt *AStmt, SourceLocation StartLoc,
6501 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006502 if (!AStmt)
6503 return StmtError();
6504
David Majnemer9d168222016-08-05 17:44:54 +00006505 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006506 // 1.2.2 OpenMP Language Terminology
6507 // Structured block - An executable statement with a single entry at the
6508 // top and a single exit at the bottom.
6509 // The point of exit cannot be a branch out of the structured block.
6510 // longjmp() and throw() must not violate the entry/exit criteria.
6511 CS->getCapturedDecl()->setNothrow();
6512
Reid Kleckner87a31802018-03-12 21:43:02 +00006513 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006514
Alexey Bataev25e5b442015-09-15 12:52:43 +00006515 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6516 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006517}
6518
Alexey Bataev68446b72014-07-18 07:47:19 +00006519StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6520 SourceLocation EndLoc) {
6521 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6522}
6523
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00006524StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6525 SourceLocation EndLoc) {
6526 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6527}
6528
Alexey Bataev2df347a2014-07-18 10:17:07 +00006529StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6530 SourceLocation EndLoc) {
6531 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6532}
6533
Alexey Bataev169d96a2017-07-18 20:17:46 +00006534StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6535 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006536 SourceLocation StartLoc,
6537 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006538 if (!AStmt)
6539 return StmtError();
6540
6541 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006542
Reid Kleckner87a31802018-03-12 21:43:02 +00006543 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006544
Alexey Bataev169d96a2017-07-18 20:17:46 +00006545 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00006546 AStmt,
6547 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006548}
6549
Alexey Bataev6125da92014-07-21 11:26:11 +00006550StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6551 SourceLocation StartLoc,
6552 SourceLocation EndLoc) {
6553 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6554 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6555}
6556
Alexey Bataev346265e2015-09-25 10:37:12 +00006557StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6558 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006559 SourceLocation StartLoc,
6560 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006561 const OMPClause *DependFound = nullptr;
6562 const OMPClause *DependSourceClause = nullptr;
6563 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00006564 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006565 const OMPThreadsClause *TC = nullptr;
6566 const OMPSIMDClause *SC = nullptr;
6567 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00006568 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6569 DependFound = C;
6570 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6571 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006572 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00006573 << getOpenMPDirectiveName(OMPD_ordered)
6574 << getOpenMPClauseName(OMPC_depend) << 2;
6575 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006576 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00006577 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00006578 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006579 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006580 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006581 << 0;
6582 ErrorFound = true;
6583 }
6584 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6585 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006586 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006587 << 1;
6588 ErrorFound = true;
6589 }
6590 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00006591 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006592 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00006593 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006594 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006595 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006596 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006597 }
Alexey Bataeveb482352015-12-18 05:05:56 +00006598 if (!ErrorFound && !SC &&
6599 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006600 // OpenMP [2.8.1,simd Construct, Restrictions]
6601 // An ordered construct with the simd clause is the only OpenMP construct
6602 // that can appear in the simd region.
6603 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00006604 ErrorFound = true;
6605 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006606 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00006607 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6608 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006609 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006610 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00006611 diag::err_omp_ordered_directive_without_param);
6612 ErrorFound = true;
6613 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006614 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006615 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00006616 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6617 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006618 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00006619 ErrorFound = true;
6620 }
6621 }
6622 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006623 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00006624
6625 if (AStmt) {
6626 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6627
Reid Kleckner87a31802018-03-12 21:43:02 +00006628 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006629 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006630
6631 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006632}
6633
Alexey Bataev1d160b12015-03-13 12:27:31 +00006634namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006635/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006636/// construct.
6637class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006638 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006639 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006640 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006641 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006642 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006643 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006644 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006645 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006646 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006647 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006648 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006649 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006650 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006651 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006652 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00006653 /// expression.
6654 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006655 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00006656 /// part.
6657 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006658 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006659 NoError
6660 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006661 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006662 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006663 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00006664 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006665 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006666 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006667 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006668 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006669 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00006670 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6671 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6672 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006673 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00006674 /// important for non-associative operations.
6675 bool IsXLHSInRHSPart;
6676 BinaryOperatorKind Op;
6677 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006678 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006679 /// if it is a prefix unary operation.
6680 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006681
6682public:
6683 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00006684 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00006685 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006686 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006687 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00006688 /// expression. If DiagId and NoteId == 0, then only check is performed
6689 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006690 /// \param DiagId Diagnostic which should be emitted if error is found.
6691 /// \param NoteId Diagnostic note for the main error message.
6692 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00006693 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006694 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006695 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006696 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006697 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006698 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00006699 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6700 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6701 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006702 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00006703 /// false otherwise.
6704 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
6705
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006706 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006707 /// if it is a prefix unary operation.
6708 bool isPostfixUpdate() const { return IsPostfixUpdate; }
6709
Alexey Bataev1d160b12015-03-13 12:27:31 +00006710private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00006711 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
6712 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00006713};
6714} // namespace
6715
6716bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
6717 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
6718 ExprAnalysisErrorCode ErrorFound = NoError;
6719 SourceLocation ErrorLoc, NoteLoc;
6720 SourceRange ErrorRange, NoteRange;
6721 // Allowed constructs are:
6722 // x = x binop expr;
6723 // x = expr binop x;
6724 if (AtomicBinOp->getOpcode() == BO_Assign) {
6725 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00006726 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006727 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
6728 if (AtomicInnerBinOp->isMultiplicativeOp() ||
6729 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
6730 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006731 Op = AtomicInnerBinOp->getOpcode();
6732 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00006733 Expr *LHS = AtomicInnerBinOp->getLHS();
6734 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006735 llvm::FoldingSetNodeID XId, LHSId, RHSId;
6736 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
6737 /*Canonical=*/true);
6738 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
6739 /*Canonical=*/true);
6740 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
6741 /*Canonical=*/true);
6742 if (XId == LHSId) {
6743 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006744 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006745 } else if (XId == RHSId) {
6746 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006747 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006748 } else {
6749 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6750 ErrorRange = AtomicInnerBinOp->getSourceRange();
6751 NoteLoc = X->getExprLoc();
6752 NoteRange = X->getSourceRange();
6753 ErrorFound = NotAnUpdateExpression;
6754 }
6755 } else {
6756 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6757 ErrorRange = AtomicInnerBinOp->getSourceRange();
6758 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
6759 NoteRange = SourceRange(NoteLoc, NoteLoc);
6760 ErrorFound = NotABinaryOperator;
6761 }
6762 } else {
6763 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
6764 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
6765 ErrorFound = NotABinaryExpression;
6766 }
6767 } else {
6768 ErrorLoc = AtomicBinOp->getExprLoc();
6769 ErrorRange = AtomicBinOp->getSourceRange();
6770 NoteLoc = AtomicBinOp->getOperatorLoc();
6771 NoteRange = SourceRange(NoteLoc, NoteLoc);
6772 ErrorFound = NotAnAssignmentOp;
6773 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006774 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006775 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6776 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6777 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006778 }
6779 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006780 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006781 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006782}
6783
6784bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6785 unsigned NoteId) {
6786 ExprAnalysisErrorCode ErrorFound = NoError;
6787 SourceLocation ErrorLoc, NoteLoc;
6788 SourceRange ErrorRange, NoteRange;
6789 // Allowed constructs are:
6790 // x++;
6791 // x--;
6792 // ++x;
6793 // --x;
6794 // x binop= expr;
6795 // x = x binop expr;
6796 // x = expr binop x;
6797 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6798 AtomicBody = AtomicBody->IgnoreParenImpCasts();
6799 if (AtomicBody->getType()->isScalarType() ||
6800 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006801 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006802 AtomicBody->IgnoreParenImpCasts())) {
6803 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00006804 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006805 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00006806 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006807 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006808 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006809 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006810 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6811 AtomicBody->IgnoreParenImpCasts())) {
6812 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00006813 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00006814 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006815 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00006816 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006817 // Check for Unary Operation
6818 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006819 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006820 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6821 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006822 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006823 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6824 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006825 } else {
6826 ErrorFound = NotAnUnaryIncDecExpression;
6827 ErrorLoc = AtomicUnaryOp->getExprLoc();
6828 ErrorRange = AtomicUnaryOp->getSourceRange();
6829 NoteLoc = AtomicUnaryOp->getOperatorLoc();
6830 NoteRange = SourceRange(NoteLoc, NoteLoc);
6831 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006832 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006833 ErrorFound = NotABinaryOrUnaryExpression;
6834 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6835 NoteRange = ErrorRange = AtomicBody->getSourceRange();
6836 }
6837 } else {
6838 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006839 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006840 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6841 }
6842 } else {
6843 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006844 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006845 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6846 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006847 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006848 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6849 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6850 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006851 }
6852 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006853 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006854 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006855 // Build an update expression of form 'OpaqueValueExpr(x) binop
6856 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6857 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6858 auto *OVEX = new (SemaRef.getASTContext())
6859 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6860 auto *OVEExpr = new (SemaRef.getASTContext())
6861 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00006862 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00006863 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6864 IsXLHSInRHSPart ? OVEExpr : OVEX);
6865 if (Update.isInvalid())
6866 return true;
6867 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6868 Sema::AA_Casting);
6869 if (Update.isInvalid())
6870 return true;
6871 UpdateExpr = Update.get();
6872 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00006873 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006874}
6875
Alexey Bataev0162e452014-07-22 10:10:35 +00006876StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6877 Stmt *AStmt,
6878 SourceLocation StartLoc,
6879 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006880 if (!AStmt)
6881 return StmtError();
6882
David Majnemer9d168222016-08-05 17:44:54 +00006883 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00006884 // 1.2.2 OpenMP Language Terminology
6885 // Structured block - An executable statement with a single entry at the
6886 // top and a single exit at the bottom.
6887 // The point of exit cannot be a branch out of the structured block.
6888 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00006889 OpenMPClauseKind AtomicKind = OMPC_unknown;
6890 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00006891 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00006892 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00006893 C->getClauseKind() == OMPC_update ||
6894 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00006895 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006896 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006897 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00006898 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6899 << getOpenMPClauseName(AtomicKind);
6900 } else {
6901 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006902 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006903 }
6904 }
6905 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006906
Alexey Bataeve3727102018-04-18 15:57:46 +00006907 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00006908 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6909 Body = EWC->getSubExpr();
6910
Alexey Bataev62cec442014-11-18 10:14:22 +00006911 Expr *X = nullptr;
6912 Expr *V = nullptr;
6913 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006914 Expr *UE = nullptr;
6915 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006916 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006917 // OpenMP [2.12.6, atomic Construct]
6918 // In the next expressions:
6919 // * x and v (as applicable) are both l-value expressions with scalar type.
6920 // * During the execution of an atomic region, multiple syntactic
6921 // occurrences of x must designate the same storage location.
6922 // * Neither of v and expr (as applicable) may access the storage location
6923 // designated by x.
6924 // * Neither of x and expr (as applicable) may access the storage location
6925 // designated by v.
6926 // * expr is an expression with scalar type.
6927 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6928 // * binop, binop=, ++, and -- are not overloaded operators.
6929 // * The expression x binop expr must be numerically equivalent to x binop
6930 // (expr). This requirement is satisfied if the operators in expr have
6931 // precedence greater than binop, or by using parentheses around expr or
6932 // subexpressions of expr.
6933 // * The expression expr binop x must be numerically equivalent to (expr)
6934 // binop x. This requirement is satisfied if the operators in expr have
6935 // precedence equal to or greater than binop, or by using parentheses around
6936 // expr or subexpressions of expr.
6937 // * For forms that allow multiple occurrences of x, the number of times
6938 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006939 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006940 enum {
6941 NotAnExpression,
6942 NotAnAssignmentOp,
6943 NotAScalarType,
6944 NotAnLValue,
6945 NoError
6946 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006947 SourceLocation ErrorLoc, NoteLoc;
6948 SourceRange ErrorRange, NoteRange;
6949 // If clause is read:
6950 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006951 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6952 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006953 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6954 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6955 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6956 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6957 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6958 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6959 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006960 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00006961 ErrorFound = NotAnLValue;
6962 ErrorLoc = AtomicBinOp->getExprLoc();
6963 ErrorRange = AtomicBinOp->getSourceRange();
6964 NoteLoc = NotLValueExpr->getExprLoc();
6965 NoteRange = NotLValueExpr->getSourceRange();
6966 }
6967 } else if (!X->isInstantiationDependent() ||
6968 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006969 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00006970 (X->isInstantiationDependent() || X->getType()->isScalarType())
6971 ? V
6972 : X;
6973 ErrorFound = NotAScalarType;
6974 ErrorLoc = AtomicBinOp->getExprLoc();
6975 ErrorRange = AtomicBinOp->getSourceRange();
6976 NoteLoc = NotScalarExpr->getExprLoc();
6977 NoteRange = NotScalarExpr->getSourceRange();
6978 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006979 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00006980 ErrorFound = NotAnAssignmentOp;
6981 ErrorLoc = AtomicBody->getExprLoc();
6982 ErrorRange = AtomicBody->getSourceRange();
6983 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6984 : AtomicBody->getExprLoc();
6985 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6986 : AtomicBody->getSourceRange();
6987 }
6988 } else {
6989 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006990 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00006991 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006992 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006993 if (ErrorFound != NoError) {
6994 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6995 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006996 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6997 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00006998 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006999 }
7000 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00007001 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00007002 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007003 enum {
7004 NotAnExpression,
7005 NotAnAssignmentOp,
7006 NotAScalarType,
7007 NotAnLValue,
7008 NoError
7009 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00007010 SourceLocation ErrorLoc, NoteLoc;
7011 SourceRange ErrorRange, NoteRange;
7012 // If clause is write:
7013 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00007014 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7015 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007016 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7017 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00007018 X = AtomicBinOp->getLHS();
7019 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007020 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7021 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
7022 if (!X->isLValue()) {
7023 ErrorFound = NotAnLValue;
7024 ErrorLoc = AtomicBinOp->getExprLoc();
7025 ErrorRange = AtomicBinOp->getSourceRange();
7026 NoteLoc = X->getExprLoc();
7027 NoteRange = X->getSourceRange();
7028 }
7029 } else if (!X->isInstantiationDependent() ||
7030 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007031 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007032 (X->isInstantiationDependent() || X->getType()->isScalarType())
7033 ? E
7034 : X;
7035 ErrorFound = NotAScalarType;
7036 ErrorLoc = AtomicBinOp->getExprLoc();
7037 ErrorRange = AtomicBinOp->getSourceRange();
7038 NoteLoc = NotScalarExpr->getExprLoc();
7039 NoteRange = NotScalarExpr->getSourceRange();
7040 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007041 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00007042 ErrorFound = NotAnAssignmentOp;
7043 ErrorLoc = AtomicBody->getExprLoc();
7044 ErrorRange = AtomicBody->getSourceRange();
7045 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7046 : AtomicBody->getExprLoc();
7047 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7048 : AtomicBody->getSourceRange();
7049 }
7050 } else {
7051 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007052 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007053 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00007054 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00007055 if (ErrorFound != NoError) {
7056 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
7057 << ErrorRange;
7058 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7059 << NoteRange;
7060 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007061 }
7062 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00007063 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007064 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007065 // If clause is update:
7066 // x++;
7067 // x--;
7068 // ++x;
7069 // --x;
7070 // x binop= expr;
7071 // x = x binop expr;
7072 // x = expr binop x;
7073 OpenMPAtomicUpdateChecker Checker(*this);
7074 if (Checker.checkStatement(
7075 Body, (AtomicKind == OMPC_update)
7076 ? diag::err_omp_atomic_update_not_expression_statement
7077 : diag::err_omp_atomic_not_expression_statement,
7078 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00007079 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007080 if (!CurContext->isDependentContext()) {
7081 E = Checker.getExpr();
7082 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007083 UE = Checker.getUpdateExpr();
7084 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00007085 }
Alexey Bataev459dec02014-07-24 06:46:57 +00007086 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007087 enum {
7088 NotAnAssignmentOp,
7089 NotACompoundStatement,
7090 NotTwoSubstatements,
7091 NotASpecificExpression,
7092 NoError
7093 } ErrorFound = NoError;
7094 SourceLocation ErrorLoc, NoteLoc;
7095 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00007096 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007097 // If clause is a capture:
7098 // v = x++;
7099 // v = x--;
7100 // v = ++x;
7101 // v = --x;
7102 // v = x binop= expr;
7103 // v = x = x binop expr;
7104 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00007105 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00007106 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7107 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7108 V = AtomicBinOp->getLHS();
7109 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7110 OpenMPAtomicUpdateChecker Checker(*this);
7111 if (Checker.checkStatement(
7112 Body, diag::err_omp_atomic_capture_not_expression_statement,
7113 diag::note_omp_atomic_update))
7114 return StmtError();
7115 E = Checker.getExpr();
7116 X = Checker.getX();
7117 UE = Checker.getUpdateExpr();
7118 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7119 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00007120 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007121 ErrorLoc = AtomicBody->getExprLoc();
7122 ErrorRange = AtomicBody->getSourceRange();
7123 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7124 : AtomicBody->getExprLoc();
7125 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7126 : AtomicBody->getSourceRange();
7127 ErrorFound = NotAnAssignmentOp;
7128 }
7129 if (ErrorFound != NoError) {
7130 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
7131 << ErrorRange;
7132 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7133 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007134 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007135 if (CurContext->isDependentContext())
7136 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007137 } else {
7138 // If clause is a capture:
7139 // { v = x; x = expr; }
7140 // { v = x; x++; }
7141 // { v = x; x--; }
7142 // { v = x; ++x; }
7143 // { v = x; --x; }
7144 // { v = x; x binop= expr; }
7145 // { v = x; x = x binop expr; }
7146 // { v = x; x = expr binop x; }
7147 // { x++; v = x; }
7148 // { x--; v = x; }
7149 // { ++x; v = x; }
7150 // { --x; v = x; }
7151 // { x binop= expr; v = x; }
7152 // { x = x binop expr; v = x; }
7153 // { x = expr binop x; v = x; }
7154 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
7155 // Check that this is { expr1; expr2; }
7156 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007157 Stmt *First = CS->body_front();
7158 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007159 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
7160 First = EWC->getSubExpr()->IgnoreParenImpCasts();
7161 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
7162 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
7163 // Need to find what subexpression is 'v' and what is 'x'.
7164 OpenMPAtomicUpdateChecker Checker(*this);
7165 bool IsUpdateExprFound = !Checker.checkStatement(Second);
7166 BinaryOperator *BinOp = nullptr;
7167 if (IsUpdateExprFound) {
7168 BinOp = dyn_cast<BinaryOperator>(First);
7169 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7170 }
7171 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7172 // { v = x; x++; }
7173 // { v = x; x--; }
7174 // { v = x; ++x; }
7175 // { v = x; --x; }
7176 // { v = x; x binop= expr; }
7177 // { v = x; x = x binop expr; }
7178 // { v = x; x = expr binop x; }
7179 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007180 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007181 llvm::FoldingSetNodeID XId, PossibleXId;
7182 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7183 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7184 IsUpdateExprFound = XId == PossibleXId;
7185 if (IsUpdateExprFound) {
7186 V = BinOp->getLHS();
7187 X = Checker.getX();
7188 E = Checker.getExpr();
7189 UE = Checker.getUpdateExpr();
7190 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007191 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007192 }
7193 }
7194 if (!IsUpdateExprFound) {
7195 IsUpdateExprFound = !Checker.checkStatement(First);
7196 BinOp = nullptr;
7197 if (IsUpdateExprFound) {
7198 BinOp = dyn_cast<BinaryOperator>(Second);
7199 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7200 }
7201 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7202 // { x++; v = x; }
7203 // { x--; v = x; }
7204 // { ++x; v = x; }
7205 // { --x; v = x; }
7206 // { x binop= expr; v = x; }
7207 // { x = x binop expr; v = x; }
7208 // { x = expr binop x; v = x; }
7209 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007210 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007211 llvm::FoldingSetNodeID XId, PossibleXId;
7212 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7213 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7214 IsUpdateExprFound = XId == PossibleXId;
7215 if (IsUpdateExprFound) {
7216 V = BinOp->getLHS();
7217 X = Checker.getX();
7218 E = Checker.getExpr();
7219 UE = Checker.getUpdateExpr();
7220 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007221 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007222 }
7223 }
7224 }
7225 if (!IsUpdateExprFound) {
7226 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00007227 auto *FirstExpr = dyn_cast<Expr>(First);
7228 auto *SecondExpr = dyn_cast<Expr>(Second);
7229 if (!FirstExpr || !SecondExpr ||
7230 !(FirstExpr->isInstantiationDependent() ||
7231 SecondExpr->isInstantiationDependent())) {
7232 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
7233 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007234 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00007235 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007236 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007237 NoteRange = ErrorRange = FirstBinOp
7238 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00007239 : SourceRange(ErrorLoc, ErrorLoc);
7240 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00007241 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
7242 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
7243 ErrorFound = NotAnAssignmentOp;
7244 NoteLoc = ErrorLoc = SecondBinOp
7245 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007246 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007247 NoteRange = ErrorRange =
7248 SecondBinOp ? SecondBinOp->getSourceRange()
7249 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00007250 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007251 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00007252 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00007253 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00007254 SecondBinOp->getLHS()->IgnoreParenImpCasts();
7255 llvm::FoldingSetNodeID X1Id, X2Id;
7256 PossibleXRHSInFirst->Profile(X1Id, Context,
7257 /*Canonical=*/true);
7258 PossibleXLHSInSecond->Profile(X2Id, Context,
7259 /*Canonical=*/true);
7260 IsUpdateExprFound = X1Id == X2Id;
7261 if (IsUpdateExprFound) {
7262 V = FirstBinOp->getLHS();
7263 X = SecondBinOp->getLHS();
7264 E = SecondBinOp->getRHS();
7265 UE = nullptr;
7266 IsXLHSInRHSPart = false;
7267 IsPostfixUpdate = true;
7268 } else {
7269 ErrorFound = NotASpecificExpression;
7270 ErrorLoc = FirstBinOp->getExprLoc();
7271 ErrorRange = FirstBinOp->getSourceRange();
7272 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
7273 NoteRange = SecondBinOp->getRHS()->getSourceRange();
7274 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007275 }
7276 }
7277 }
7278 }
7279 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007280 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007281 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007282 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007283 ErrorFound = NotTwoSubstatements;
7284 }
7285 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007286 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007287 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007288 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007289 ErrorFound = NotACompoundStatement;
7290 }
7291 if (ErrorFound != NoError) {
7292 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7293 << ErrorRange;
7294 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7295 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007296 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007297 if (CurContext->isDependentContext())
7298 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00007299 }
Alexey Bataevdea47612014-07-23 07:46:59 +00007300 }
Alexey Bataev0162e452014-07-22 10:10:35 +00007301
Reid Kleckner87a31802018-03-12 21:43:02 +00007302 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00007303
Alexey Bataev62cec442014-11-18 10:14:22 +00007304 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00007305 X, V, E, UE, IsXLHSInRHSPart,
7306 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00007307}
7308
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007309StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7310 Stmt *AStmt,
7311 SourceLocation StartLoc,
7312 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007313 if (!AStmt)
7314 return StmtError();
7315
Alexey Bataeve3727102018-04-18 15:57:46 +00007316 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00007317 // 1.2.2 OpenMP Language Terminology
7318 // Structured block - An executable statement with a single entry at the
7319 // top and a single exit at the bottom.
7320 // The point of exit cannot be a branch out of the structured block.
7321 // longjmp() and throw() must not violate the entry/exit criteria.
7322 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007323 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7324 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7325 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7326 // 1.2.2 OpenMP Language Terminology
7327 // Structured block - An executable statement with a single entry at the
7328 // top and a single exit at the bottom.
7329 // The point of exit cannot be a branch out of the structured block.
7330 // longjmp() and throw() must not violate the entry/exit criteria.
7331 CS->getCapturedDecl()->setNothrow();
7332 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007333
Alexey Bataev13314bf2014-10-09 04:18:56 +00007334 // OpenMP [2.16, Nesting of Regions]
7335 // If specified, a teams construct must be contained within a target
7336 // construct. That target construct must contain no statements or directives
7337 // outside of the teams construct.
7338 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007339 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007340 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007341 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00007342 auto I = CS->body_begin();
7343 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007344 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00007345 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7346 OMPTeamsFound) {
7347
Alexey Bataev13314bf2014-10-09 04:18:56 +00007348 OMPTeamsFound = false;
7349 break;
7350 }
7351 ++I;
7352 }
7353 assert(I != CS->body_end() && "Not found statement");
7354 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00007355 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007356 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00007357 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00007358 }
7359 if (!OMPTeamsFound) {
7360 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7361 Diag(DSAStack->getInnerTeamsRegionLoc(),
7362 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007363 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00007364 << isa<OMPExecutableDirective>(S);
7365 return StmtError();
7366 }
7367 }
7368
Reid Kleckner87a31802018-03-12 21:43:02 +00007369 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007370
7371 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7372}
7373
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007374StmtResult
7375Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7376 Stmt *AStmt, SourceLocation StartLoc,
7377 SourceLocation EndLoc) {
7378 if (!AStmt)
7379 return StmtError();
7380
Alexey Bataeve3727102018-04-18 15:57:46 +00007381 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007382 // 1.2.2 OpenMP Language Terminology
7383 // Structured block - An executable statement with a single entry at the
7384 // top and a single exit at the bottom.
7385 // The point of exit cannot be a branch out of the structured block.
7386 // longjmp() and throw() must not violate the entry/exit criteria.
7387 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007388 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7389 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7390 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7391 // 1.2.2 OpenMP Language Terminology
7392 // Structured block - An executable statement with a single entry at the
7393 // top and a single exit at the bottom.
7394 // The point of exit cannot be a branch out of the structured block.
7395 // longjmp() and throw() must not violate the entry/exit criteria.
7396 CS->getCapturedDecl()->setNothrow();
7397 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007398
Reid Kleckner87a31802018-03-12 21:43:02 +00007399 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007400
7401 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7402 AStmt);
7403}
7404
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007405StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7406 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007407 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007408 if (!AStmt)
7409 return StmtError();
7410
Alexey Bataeve3727102018-04-18 15:57:46 +00007411 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007412 // 1.2.2 OpenMP Language Terminology
7413 // Structured block - An executable statement with a single entry at the
7414 // top and a single exit at the bottom.
7415 // The point of exit cannot be a branch out of the structured block.
7416 // longjmp() and throw() must not violate the entry/exit criteria.
7417 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007418 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7419 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7420 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7421 // 1.2.2 OpenMP Language Terminology
7422 // Structured block - An executable statement with a single entry at the
7423 // top and a single exit at the bottom.
7424 // The point of exit cannot be a branch out of the structured block.
7425 // longjmp() and throw() must not violate the entry/exit criteria.
7426 CS->getCapturedDecl()->setNothrow();
7427 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007428
7429 OMPLoopDirective::HelperExprs B;
7430 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7431 // define the nested loops number.
7432 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007433 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007434 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007435 VarsWithImplicitDSA, B);
7436 if (NestedLoopCount == 0)
7437 return StmtError();
7438
7439 assert((CurContext->isDependentContext() || B.builtAll()) &&
7440 "omp target parallel for loop exprs were not built");
7441
7442 if (!CurContext->isDependentContext()) {
7443 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007444 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007445 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007446 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007447 B.NumIterations, *this, CurScope,
7448 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007449 return StmtError();
7450 }
7451 }
7452
Reid Kleckner87a31802018-03-12 21:43:02 +00007453 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007454 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7455 NestedLoopCount, Clauses, AStmt,
7456 B, DSAStack->isCancelRegion());
7457}
7458
Alexey Bataev95b64a92017-05-30 16:00:04 +00007459/// Check for existence of a map clause in the list of clauses.
7460static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7461 const OpenMPClauseKind K) {
7462 return llvm::any_of(
7463 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7464}
Samuel Antaodf67fc42016-01-19 19:15:56 +00007465
Alexey Bataev95b64a92017-05-30 16:00:04 +00007466template <typename... Params>
7467static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7468 const Params... ClauseTypes) {
7469 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007470}
7471
Michael Wong65f367f2015-07-21 13:44:28 +00007472StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7473 Stmt *AStmt,
7474 SourceLocation StartLoc,
7475 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007476 if (!AStmt)
7477 return StmtError();
7478
7479 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7480
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007481 // OpenMP [2.10.1, Restrictions, p. 97]
7482 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007483 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7484 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7485 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00007486 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007487 return StmtError();
7488 }
7489
Reid Kleckner87a31802018-03-12 21:43:02 +00007490 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00007491
7492 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7493 AStmt);
7494}
7495
Samuel Antaodf67fc42016-01-19 19:15:56 +00007496StmtResult
7497Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7498 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007499 SourceLocation EndLoc, Stmt *AStmt) {
7500 if (!AStmt)
7501 return StmtError();
7502
Alexey Bataeve3727102018-04-18 15:57:46 +00007503 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007504 // 1.2.2 OpenMP Language Terminology
7505 // Structured block - An executable statement with a single entry at the
7506 // top and a single exit at the bottom.
7507 // The point of exit cannot be a branch out of the structured block.
7508 // longjmp() and throw() must not violate the entry/exit criteria.
7509 CS->getCapturedDecl()->setNothrow();
7510 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7511 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7512 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7513 // 1.2.2 OpenMP Language Terminology
7514 // Structured block - An executable statement with a single entry at the
7515 // top and a single exit at the bottom.
7516 // The point of exit cannot be a branch out of the structured block.
7517 // longjmp() and throw() must not violate the entry/exit criteria.
7518 CS->getCapturedDecl()->setNothrow();
7519 }
7520
Samuel Antaodf67fc42016-01-19 19:15:56 +00007521 // OpenMP [2.10.2, Restrictions, p. 99]
7522 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007523 if (!hasClauses(Clauses, OMPC_map)) {
7524 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7525 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007526 return StmtError();
7527 }
7528
Alexey Bataev7828b252017-11-21 17:08:48 +00007529 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7530 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007531}
7532
Samuel Antao72590762016-01-19 20:04:50 +00007533StmtResult
7534Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7535 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007536 SourceLocation EndLoc, Stmt *AStmt) {
7537 if (!AStmt)
7538 return StmtError();
7539
Alexey Bataeve3727102018-04-18 15:57:46 +00007540 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007541 // 1.2.2 OpenMP Language Terminology
7542 // Structured block - An executable statement with a single entry at the
7543 // top and a single exit at the bottom.
7544 // The point of exit cannot be a branch out of the structured block.
7545 // longjmp() and throw() must not violate the entry/exit criteria.
7546 CS->getCapturedDecl()->setNothrow();
7547 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7548 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7549 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7550 // 1.2.2 OpenMP Language Terminology
7551 // Structured block - An executable statement with a single entry at the
7552 // top and a single exit at the bottom.
7553 // The point of exit cannot be a branch out of the structured block.
7554 // longjmp() and throw() must not violate the entry/exit criteria.
7555 CS->getCapturedDecl()->setNothrow();
7556 }
7557
Samuel Antao72590762016-01-19 20:04:50 +00007558 // OpenMP [2.10.3, Restrictions, p. 102]
7559 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007560 if (!hasClauses(Clauses, OMPC_map)) {
7561 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7562 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00007563 return StmtError();
7564 }
7565
Alexey Bataev7828b252017-11-21 17:08:48 +00007566 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7567 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00007568}
7569
Samuel Antao686c70c2016-05-26 17:30:50 +00007570StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7571 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007572 SourceLocation EndLoc,
7573 Stmt *AStmt) {
7574 if (!AStmt)
7575 return StmtError();
7576
Alexey Bataeve3727102018-04-18 15:57:46 +00007577 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007578 // 1.2.2 OpenMP Language Terminology
7579 // Structured block - An executable statement with a single entry at the
7580 // top and a single exit at the bottom.
7581 // The point of exit cannot be a branch out of the structured block.
7582 // longjmp() and throw() must not violate the entry/exit criteria.
7583 CS->getCapturedDecl()->setNothrow();
7584 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7585 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7586 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7587 // 1.2.2 OpenMP Language Terminology
7588 // Structured block - An executable statement with a single entry at the
7589 // top and a single exit at the bottom.
7590 // The point of exit cannot be a branch out of the structured block.
7591 // longjmp() and throw() must not violate the entry/exit criteria.
7592 CS->getCapturedDecl()->setNothrow();
7593 }
7594
Alexey Bataev95b64a92017-05-30 16:00:04 +00007595 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00007596 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7597 return StmtError();
7598 }
Alexey Bataev7828b252017-11-21 17:08:48 +00007599 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7600 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00007601}
7602
Alexey Bataev13314bf2014-10-09 04:18:56 +00007603StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7604 Stmt *AStmt, SourceLocation StartLoc,
7605 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007606 if (!AStmt)
7607 return StmtError();
7608
Alexey Bataeve3727102018-04-18 15:57:46 +00007609 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007610 // 1.2.2 OpenMP Language Terminology
7611 // Structured block - An executable statement with a single entry at the
7612 // top and a single exit at the bottom.
7613 // The point of exit cannot be a branch out of the structured block.
7614 // longjmp() and throw() must not violate the entry/exit criteria.
7615 CS->getCapturedDecl()->setNothrow();
7616
Reid Kleckner87a31802018-03-12 21:43:02 +00007617 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00007618
Alexey Bataevceabd412017-11-30 18:01:54 +00007619 DSAStack->setParentTeamsRegionLoc(StartLoc);
7620
Alexey Bataev13314bf2014-10-09 04:18:56 +00007621 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7622}
7623
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007624StmtResult
7625Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7626 SourceLocation EndLoc,
7627 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007628 if (DSAStack->isParentNowaitRegion()) {
7629 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
7630 return StmtError();
7631 }
7632 if (DSAStack->isParentOrderedRegion()) {
7633 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
7634 return StmtError();
7635 }
7636 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
7637 CancelRegion);
7638}
7639
Alexey Bataev87933c72015-09-18 08:07:34 +00007640StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7641 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00007642 SourceLocation EndLoc,
7643 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00007644 if (DSAStack->isParentNowaitRegion()) {
7645 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
7646 return StmtError();
7647 }
7648 if (DSAStack->isParentOrderedRegion()) {
7649 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
7650 return StmtError();
7651 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007652 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00007653 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7654 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00007655}
7656
Alexey Bataev382967a2015-12-08 12:06:20 +00007657static bool checkGrainsizeNumTasksClauses(Sema &S,
7658 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007659 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00007660 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007661 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00007662 if (C->getClauseKind() == OMPC_grainsize ||
7663 C->getClauseKind() == OMPC_num_tasks) {
7664 if (!PrevClause)
7665 PrevClause = C;
7666 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007667 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007668 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
7669 << getOpenMPClauseName(C->getClauseKind())
7670 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007671 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007672 diag::note_omp_previous_grainsize_num_tasks)
7673 << getOpenMPClauseName(PrevClause->getClauseKind());
7674 ErrorFound = true;
7675 }
7676 }
7677 }
7678 return ErrorFound;
7679}
7680
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007681static bool checkReductionClauseWithNogroup(Sema &S,
7682 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007683 const OMPClause *ReductionClause = nullptr;
7684 const OMPClause *NogroupClause = nullptr;
7685 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007686 if (C->getClauseKind() == OMPC_reduction) {
7687 ReductionClause = C;
7688 if (NogroupClause)
7689 break;
7690 continue;
7691 }
7692 if (C->getClauseKind() == OMPC_nogroup) {
7693 NogroupClause = C;
7694 if (ReductionClause)
7695 break;
7696 continue;
7697 }
7698 }
7699 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007700 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
7701 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007702 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007703 return true;
7704 }
7705 return false;
7706}
7707
Alexey Bataev49f6e782015-12-01 04:18:41 +00007708StmtResult Sema::ActOnOpenMPTaskLoopDirective(
7709 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007710 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00007711 if (!AStmt)
7712 return StmtError();
7713
7714 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7715 OMPLoopDirective::HelperExprs B;
7716 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7717 // define the nested loops number.
7718 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007719 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007720 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00007721 VarsWithImplicitDSA, B);
7722 if (NestedLoopCount == 0)
7723 return StmtError();
7724
7725 assert((CurContext->isDependentContext() || B.builtAll()) &&
7726 "omp for loop exprs were not built");
7727
Alexey Bataev382967a2015-12-08 12:06:20 +00007728 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7729 // The grainsize clause and num_tasks clause are mutually exclusive and may
7730 // not appear on the same taskloop directive.
7731 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7732 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007733 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7734 // If a reduction clause is present on the taskloop directive, the nogroup
7735 // clause must not be specified.
7736 if (checkReductionClauseWithNogroup(*this, Clauses))
7737 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007738
Reid Kleckner87a31802018-03-12 21:43:02 +00007739 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00007740 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
7741 NestedLoopCount, Clauses, AStmt, B);
7742}
7743
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007744StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
7745 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007746 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007747 if (!AStmt)
7748 return StmtError();
7749
7750 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7751 OMPLoopDirective::HelperExprs B;
7752 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7753 // define the nested loops number.
7754 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007755 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007756 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7757 VarsWithImplicitDSA, B);
7758 if (NestedLoopCount == 0)
7759 return StmtError();
7760
7761 assert((CurContext->isDependentContext() || B.builtAll()) &&
7762 "omp for loop exprs were not built");
7763
Alexey Bataev5a3af132016-03-29 08:58:54 +00007764 if (!CurContext->isDependentContext()) {
7765 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007766 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007767 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007768 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007769 B.NumIterations, *this, CurScope,
7770 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007771 return StmtError();
7772 }
7773 }
7774
Alexey Bataev382967a2015-12-08 12:06:20 +00007775 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7776 // The grainsize clause and num_tasks clause are mutually exclusive and may
7777 // not appear on the same taskloop directive.
7778 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7779 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007780 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7781 // If a reduction clause is present on the taskloop directive, the nogroup
7782 // clause must not be specified.
7783 if (checkReductionClauseWithNogroup(*this, Clauses))
7784 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00007785 if (checkSimdlenSafelenSpecified(*this, Clauses))
7786 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007787
Reid Kleckner87a31802018-03-12 21:43:02 +00007788 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007789 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7790 NestedLoopCount, Clauses, AStmt, B);
7791}
7792
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007793StmtResult Sema::ActOnOpenMPDistributeDirective(
7794 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007795 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007796 if (!AStmt)
7797 return StmtError();
7798
7799 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7800 OMPLoopDirective::HelperExprs B;
7801 // In presence of clause 'collapse' with number of loops, it will
7802 // define the nested loops number.
7803 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007804 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007805 nullptr /*ordered not a clause on distribute*/, AStmt,
7806 *this, *DSAStack, VarsWithImplicitDSA, B);
7807 if (NestedLoopCount == 0)
7808 return StmtError();
7809
7810 assert((CurContext->isDependentContext() || B.builtAll()) &&
7811 "omp for loop exprs were not built");
7812
Reid Kleckner87a31802018-03-12 21:43:02 +00007813 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007814 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7815 NestedLoopCount, Clauses, AStmt, B);
7816}
7817
Carlo Bertolli9925f152016-06-27 14:55:37 +00007818StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7819 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007820 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00007821 if (!AStmt)
7822 return StmtError();
7823
Alexey Bataeve3727102018-04-18 15:57:46 +00007824 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007825 // 1.2.2 OpenMP Language Terminology
7826 // Structured block - An executable statement with a single entry at the
7827 // top and a single exit at the bottom.
7828 // The point of exit cannot be a branch out of the structured block.
7829 // longjmp() and throw() must not violate the entry/exit criteria.
7830 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00007831 for (int ThisCaptureLevel =
7832 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7833 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7834 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7835 // 1.2.2 OpenMP Language Terminology
7836 // Structured block - An executable statement with a single entry at the
7837 // top and a single exit at the bottom.
7838 // The point of exit cannot be a branch out of the structured block.
7839 // longjmp() and throw() must not violate the entry/exit criteria.
7840 CS->getCapturedDecl()->setNothrow();
7841 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00007842
7843 OMPLoopDirective::HelperExprs B;
7844 // In presence of clause 'collapse' with number of loops, it will
7845 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007846 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00007847 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00007848 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00007849 VarsWithImplicitDSA, B);
7850 if (NestedLoopCount == 0)
7851 return StmtError();
7852
7853 assert((CurContext->isDependentContext() || B.builtAll()) &&
7854 "omp for loop exprs were not built");
7855
Reid Kleckner87a31802018-03-12 21:43:02 +00007856 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007857 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007858 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7859 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00007860}
7861
Kelvin Li4a39add2016-07-05 05:00:15 +00007862StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7863 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007864 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00007865 if (!AStmt)
7866 return StmtError();
7867
Alexey Bataeve3727102018-04-18 15:57:46 +00007868 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00007869 // 1.2.2 OpenMP Language Terminology
7870 // Structured block - An executable statement with a single entry at the
7871 // top and a single exit at the bottom.
7872 // The point of exit cannot be a branch out of the structured block.
7873 // longjmp() and throw() must not violate the entry/exit criteria.
7874 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00007875 for (int ThisCaptureLevel =
7876 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7877 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7878 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7879 // 1.2.2 OpenMP Language Terminology
7880 // Structured block - An executable statement with a single entry at the
7881 // top and a single exit at the bottom.
7882 // The point of exit cannot be a branch out of the structured block.
7883 // longjmp() and throw() must not violate the entry/exit criteria.
7884 CS->getCapturedDecl()->setNothrow();
7885 }
Kelvin Li4a39add2016-07-05 05:00:15 +00007886
7887 OMPLoopDirective::HelperExprs B;
7888 // In presence of clause 'collapse' with number of loops, it will
7889 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007890 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00007891 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00007892 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00007893 VarsWithImplicitDSA, B);
7894 if (NestedLoopCount == 0)
7895 return StmtError();
7896
7897 assert((CurContext->isDependentContext() || B.builtAll()) &&
7898 "omp for loop exprs were not built");
7899
Alexey Bataev438388c2017-11-22 18:34:02 +00007900 if (!CurContext->isDependentContext()) {
7901 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007902 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007903 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7904 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7905 B.NumIterations, *this, CurScope,
7906 DSAStack))
7907 return StmtError();
7908 }
7909 }
7910
Kelvin Lic5609492016-07-15 04:39:07 +00007911 if (checkSimdlenSafelenSpecified(*this, Clauses))
7912 return StmtError();
7913
Reid Kleckner87a31802018-03-12 21:43:02 +00007914 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00007915 return OMPDistributeParallelForSimdDirective::Create(
7916 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7917}
7918
Kelvin Li787f3fc2016-07-06 04:45:38 +00007919StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7920 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007921 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00007922 if (!AStmt)
7923 return StmtError();
7924
Alexey Bataeve3727102018-04-18 15:57:46 +00007925 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007926 // 1.2.2 OpenMP Language Terminology
7927 // Structured block - An executable statement with a single entry at the
7928 // top and a single exit at the bottom.
7929 // The point of exit cannot be a branch out of the structured block.
7930 // longjmp() and throw() must not violate the entry/exit criteria.
7931 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00007932 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7933 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7934 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7935 // 1.2.2 OpenMP Language Terminology
7936 // Structured block - An executable statement with a single entry at the
7937 // top and a single exit at the bottom.
7938 // The point of exit cannot be a branch out of the structured block.
7939 // longjmp() and throw() must not violate the entry/exit criteria.
7940 CS->getCapturedDecl()->setNothrow();
7941 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007942
7943 OMPLoopDirective::HelperExprs B;
7944 // In presence of clause 'collapse' with number of loops, it will
7945 // define the nested loops number.
7946 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007947 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007948 nullptr /*ordered not a clause on distribute*/, CS, *this,
7949 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007950 if (NestedLoopCount == 0)
7951 return StmtError();
7952
7953 assert((CurContext->isDependentContext() || B.builtAll()) &&
7954 "omp for loop exprs were not built");
7955
Alexey Bataev438388c2017-11-22 18:34:02 +00007956 if (!CurContext->isDependentContext()) {
7957 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007958 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007959 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7960 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7961 B.NumIterations, *this, CurScope,
7962 DSAStack))
7963 return StmtError();
7964 }
7965 }
7966
Kelvin Lic5609492016-07-15 04:39:07 +00007967 if (checkSimdlenSafelenSpecified(*this, Clauses))
7968 return StmtError();
7969
Reid Kleckner87a31802018-03-12 21:43:02 +00007970 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00007971 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7972 NestedLoopCount, Clauses, AStmt, B);
7973}
7974
Kelvin Lia579b912016-07-14 02:54:56 +00007975StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7976 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007977 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00007978 if (!AStmt)
7979 return StmtError();
7980
Alexey Bataeve3727102018-04-18 15:57:46 +00007981 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00007982 // 1.2.2 OpenMP Language Terminology
7983 // Structured block - An executable statement with a single entry at the
7984 // top and a single exit at the bottom.
7985 // The point of exit cannot be a branch out of the structured block.
7986 // longjmp() and throw() must not violate the entry/exit criteria.
7987 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007988 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7989 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7990 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7991 // 1.2.2 OpenMP Language Terminology
7992 // Structured block - An executable statement with a single entry at the
7993 // top and a single exit at the bottom.
7994 // The point of exit cannot be a branch out of the structured block.
7995 // longjmp() and throw() must not violate the entry/exit criteria.
7996 CS->getCapturedDecl()->setNothrow();
7997 }
Kelvin Lia579b912016-07-14 02:54:56 +00007998
7999 OMPLoopDirective::HelperExprs B;
8000 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8001 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008002 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00008003 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008004 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00008005 VarsWithImplicitDSA, B);
8006 if (NestedLoopCount == 0)
8007 return StmtError();
8008
8009 assert((CurContext->isDependentContext() || B.builtAll()) &&
8010 "omp target parallel for simd loop exprs were not built");
8011
8012 if (!CurContext->isDependentContext()) {
8013 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008014 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008015 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00008016 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8017 B.NumIterations, *this, CurScope,
8018 DSAStack))
8019 return StmtError();
8020 }
8021 }
Kelvin Lic5609492016-07-15 04:39:07 +00008022 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00008023 return StmtError();
8024
Reid Kleckner87a31802018-03-12 21:43:02 +00008025 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00008026 return OMPTargetParallelForSimdDirective::Create(
8027 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8028}
8029
Kelvin Li986330c2016-07-20 22:57:10 +00008030StmtResult Sema::ActOnOpenMPTargetSimdDirective(
8031 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008032 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00008033 if (!AStmt)
8034 return StmtError();
8035
Alexey Bataeve3727102018-04-18 15:57:46 +00008036 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00008037 // 1.2.2 OpenMP Language Terminology
8038 // Structured block - An executable statement with a single entry at the
8039 // top and a single exit at the bottom.
8040 // The point of exit cannot be a branch out of the structured block.
8041 // longjmp() and throw() must not violate the entry/exit criteria.
8042 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00008043 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
8044 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8045 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8046 // 1.2.2 OpenMP Language Terminology
8047 // Structured block - An executable statement with a single entry at the
8048 // top and a single exit at the bottom.
8049 // The point of exit cannot be a branch out of the structured block.
8050 // longjmp() and throw() must not violate the entry/exit criteria.
8051 CS->getCapturedDecl()->setNothrow();
8052 }
8053
Kelvin Li986330c2016-07-20 22:57:10 +00008054 OMPLoopDirective::HelperExprs B;
8055 // In presence of clause 'collapse' with number of loops, it will define the
8056 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00008057 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008058 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00008059 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00008060 VarsWithImplicitDSA, B);
8061 if (NestedLoopCount == 0)
8062 return StmtError();
8063
8064 assert((CurContext->isDependentContext() || B.builtAll()) &&
8065 "omp target simd loop exprs were not built");
8066
8067 if (!CurContext->isDependentContext()) {
8068 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008069 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008070 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00008071 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8072 B.NumIterations, *this, CurScope,
8073 DSAStack))
8074 return StmtError();
8075 }
8076 }
8077
8078 if (checkSimdlenSafelenSpecified(*this, Clauses))
8079 return StmtError();
8080
Reid Kleckner87a31802018-03-12 21:43:02 +00008081 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00008082 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
8083 NestedLoopCount, Clauses, AStmt, B);
8084}
8085
Kelvin Li02532872016-08-05 14:37:37 +00008086StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
8087 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008088 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00008089 if (!AStmt)
8090 return StmtError();
8091
Alexey Bataeve3727102018-04-18 15:57:46 +00008092 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00008093 // 1.2.2 OpenMP Language Terminology
8094 // Structured block - An executable statement with a single entry at the
8095 // top and a single exit at the bottom.
8096 // The point of exit cannot be a branch out of the structured block.
8097 // longjmp() and throw() must not violate the entry/exit criteria.
8098 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008099 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
8100 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8101 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8102 // 1.2.2 OpenMP Language Terminology
8103 // Structured block - An executable statement with a single entry at the
8104 // top and a single exit at the bottom.
8105 // The point of exit cannot be a branch out of the structured block.
8106 // longjmp() and throw() must not violate the entry/exit criteria.
8107 CS->getCapturedDecl()->setNothrow();
8108 }
Kelvin Li02532872016-08-05 14:37:37 +00008109
8110 OMPLoopDirective::HelperExprs B;
8111 // In presence of clause 'collapse' with number of loops, it will
8112 // define the nested loops number.
8113 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008114 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008115 nullptr /*ordered not a clause on distribute*/, CS, *this,
8116 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00008117 if (NestedLoopCount == 0)
8118 return StmtError();
8119
8120 assert((CurContext->isDependentContext() || B.builtAll()) &&
8121 "omp teams distribute loop exprs were not built");
8122
Reid Kleckner87a31802018-03-12 21:43:02 +00008123 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008124
8125 DSAStack->setParentTeamsRegionLoc(StartLoc);
8126
David Majnemer9d168222016-08-05 17:44:54 +00008127 return OMPTeamsDistributeDirective::Create(
8128 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00008129}
8130
Kelvin Li4e325f72016-10-25 12:50:55 +00008131StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
8132 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008133 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008134 if (!AStmt)
8135 return StmtError();
8136
Alexey Bataeve3727102018-04-18 15:57:46 +00008137 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00008138 // 1.2.2 OpenMP Language Terminology
8139 // Structured block - An executable statement with a single entry at the
8140 // top and a single exit at the bottom.
8141 // The point of exit cannot be a branch out of the structured block.
8142 // longjmp() and throw() must not violate the entry/exit criteria.
8143 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00008144 for (int ThisCaptureLevel =
8145 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
8146 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8147 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8148 // 1.2.2 OpenMP Language Terminology
8149 // Structured block - An executable statement with a single entry at the
8150 // top and a single exit at the bottom.
8151 // The point of exit cannot be a branch out of the structured block.
8152 // longjmp() and throw() must not violate the entry/exit criteria.
8153 CS->getCapturedDecl()->setNothrow();
8154 }
8155
Kelvin Li4e325f72016-10-25 12:50:55 +00008156
8157 OMPLoopDirective::HelperExprs B;
8158 // In presence of clause 'collapse' with number of loops, it will
8159 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008160 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00008161 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00008162 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00008163 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00008164
8165 if (NestedLoopCount == 0)
8166 return StmtError();
8167
8168 assert((CurContext->isDependentContext() || B.builtAll()) &&
8169 "omp teams distribute simd loop exprs were not built");
8170
8171 if (!CurContext->isDependentContext()) {
8172 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008173 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008174 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8175 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8176 B.NumIterations, *this, CurScope,
8177 DSAStack))
8178 return StmtError();
8179 }
8180 }
8181
8182 if (checkSimdlenSafelenSpecified(*this, Clauses))
8183 return StmtError();
8184
Reid Kleckner87a31802018-03-12 21:43:02 +00008185 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008186
8187 DSAStack->setParentTeamsRegionLoc(StartLoc);
8188
Kelvin Li4e325f72016-10-25 12:50:55 +00008189 return OMPTeamsDistributeSimdDirective::Create(
8190 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8191}
8192
Kelvin Li579e41c2016-11-30 23:51:03 +00008193StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8194 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008195 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008196 if (!AStmt)
8197 return StmtError();
8198
Alexey Bataeve3727102018-04-18 15:57:46 +00008199 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00008200 // 1.2.2 OpenMP Language Terminology
8201 // Structured block - An executable statement with a single entry at the
8202 // top and a single exit at the bottom.
8203 // The point of exit cannot be a branch out of the structured block.
8204 // longjmp() and throw() must not violate the entry/exit criteria.
8205 CS->getCapturedDecl()->setNothrow();
8206
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008207 for (int ThisCaptureLevel =
8208 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
8209 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8210 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8211 // 1.2.2 OpenMP Language Terminology
8212 // Structured block - An executable statement with a single entry at the
8213 // top and a single exit at the bottom.
8214 // The point of exit cannot be a branch out of the structured block.
8215 // longjmp() and throw() must not violate the entry/exit criteria.
8216 CS->getCapturedDecl()->setNothrow();
8217 }
8218
Kelvin Li579e41c2016-11-30 23:51:03 +00008219 OMPLoopDirective::HelperExprs B;
8220 // In presence of clause 'collapse' with number of loops, it will
8221 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008222 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00008223 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008224 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00008225 VarsWithImplicitDSA, B);
8226
8227 if (NestedLoopCount == 0)
8228 return StmtError();
8229
8230 assert((CurContext->isDependentContext() || B.builtAll()) &&
8231 "omp for loop exprs were not built");
8232
8233 if (!CurContext->isDependentContext()) {
8234 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008235 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008236 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8237 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8238 B.NumIterations, *this, CurScope,
8239 DSAStack))
8240 return StmtError();
8241 }
8242 }
8243
8244 if (checkSimdlenSafelenSpecified(*this, Clauses))
8245 return StmtError();
8246
Reid Kleckner87a31802018-03-12 21:43:02 +00008247 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008248
8249 DSAStack->setParentTeamsRegionLoc(StartLoc);
8250
Kelvin Li579e41c2016-11-30 23:51:03 +00008251 return OMPTeamsDistributeParallelForSimdDirective::Create(
8252 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8253}
8254
Kelvin Li7ade93f2016-12-09 03:24:30 +00008255StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
8256 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008257 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00008258 if (!AStmt)
8259 return StmtError();
8260
Alexey Bataeve3727102018-04-18 15:57:46 +00008261 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00008262 // 1.2.2 OpenMP Language Terminology
8263 // Structured block - An executable statement with a single entry at the
8264 // top and a single exit at the bottom.
8265 // The point of exit cannot be a branch out of the structured block.
8266 // longjmp() and throw() must not violate the entry/exit criteria.
8267 CS->getCapturedDecl()->setNothrow();
8268
Carlo Bertolli62fae152017-11-20 20:46:39 +00008269 for (int ThisCaptureLevel =
8270 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
8271 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8272 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8273 // 1.2.2 OpenMP Language Terminology
8274 // Structured block - An executable statement with a single entry at the
8275 // top and a single exit at the bottom.
8276 // The point of exit cannot be a branch out of the structured block.
8277 // longjmp() and throw() must not violate the entry/exit criteria.
8278 CS->getCapturedDecl()->setNothrow();
8279 }
8280
Kelvin Li7ade93f2016-12-09 03:24:30 +00008281 OMPLoopDirective::HelperExprs B;
8282 // In presence of clause 'collapse' with number of loops, it will
8283 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008284 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00008285 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00008286 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00008287 VarsWithImplicitDSA, B);
8288
8289 if (NestedLoopCount == 0)
8290 return StmtError();
8291
8292 assert((CurContext->isDependentContext() || B.builtAll()) &&
8293 "omp for loop exprs were not built");
8294
Reid Kleckner87a31802018-03-12 21:43:02 +00008295 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008296
8297 DSAStack->setParentTeamsRegionLoc(StartLoc);
8298
Kelvin Li7ade93f2016-12-09 03:24:30 +00008299 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008300 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8301 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00008302}
8303
Kelvin Libf594a52016-12-17 05:48:59 +00008304StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8305 Stmt *AStmt,
8306 SourceLocation StartLoc,
8307 SourceLocation EndLoc) {
8308 if (!AStmt)
8309 return StmtError();
8310
Alexey Bataeve3727102018-04-18 15:57:46 +00008311 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00008312 // 1.2.2 OpenMP Language Terminology
8313 // Structured block - An executable statement with a single entry at the
8314 // top and a single exit at the bottom.
8315 // The point of exit cannot be a branch out of the structured block.
8316 // longjmp() and throw() must not violate the entry/exit criteria.
8317 CS->getCapturedDecl()->setNothrow();
8318
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00008319 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
8320 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8321 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8322 // 1.2.2 OpenMP Language Terminology
8323 // Structured block - An executable statement with a single entry at the
8324 // top and a single exit at the bottom.
8325 // The point of exit cannot be a branch out of the structured block.
8326 // longjmp() and throw() must not violate the entry/exit criteria.
8327 CS->getCapturedDecl()->setNothrow();
8328 }
Reid Kleckner87a31802018-03-12 21:43:02 +00008329 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00008330
8331 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8332 AStmt);
8333}
8334
Kelvin Li83c451e2016-12-25 04:52:54 +00008335StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8336 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008337 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00008338 if (!AStmt)
8339 return StmtError();
8340
Alexey Bataeve3727102018-04-18 15:57:46 +00008341 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00008342 // 1.2.2 OpenMP Language Terminology
8343 // Structured block - An executable statement with a single entry at the
8344 // top and a single exit at the bottom.
8345 // The point of exit cannot be a branch out of the structured block.
8346 // longjmp() and throw() must not violate the entry/exit criteria.
8347 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008348 for (int ThisCaptureLevel =
8349 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8350 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8351 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8352 // 1.2.2 OpenMP Language Terminology
8353 // Structured block - An executable statement with a single entry at the
8354 // top and a single exit at the bottom.
8355 // The point of exit cannot be a branch out of the structured block.
8356 // longjmp() and throw() must not violate the entry/exit criteria.
8357 CS->getCapturedDecl()->setNothrow();
8358 }
Kelvin Li83c451e2016-12-25 04:52:54 +00008359
8360 OMPLoopDirective::HelperExprs B;
8361 // In presence of clause 'collapse' with number of loops, it will
8362 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008363 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008364 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8365 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00008366 VarsWithImplicitDSA, B);
8367 if (NestedLoopCount == 0)
8368 return StmtError();
8369
8370 assert((CurContext->isDependentContext() || B.builtAll()) &&
8371 "omp target teams distribute loop exprs were not built");
8372
Reid Kleckner87a31802018-03-12 21:43:02 +00008373 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00008374 return OMPTargetTeamsDistributeDirective::Create(
8375 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8376}
8377
Kelvin Li80e8f562016-12-29 22:16:30 +00008378StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8379 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008380 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00008381 if (!AStmt)
8382 return StmtError();
8383
Alexey Bataeve3727102018-04-18 15:57:46 +00008384 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00008385 // 1.2.2 OpenMP Language Terminology
8386 // Structured block - An executable statement with a single entry at the
8387 // top and a single exit at the bottom.
8388 // The point of exit cannot be a branch out of the structured block.
8389 // longjmp() and throw() must not violate the entry/exit criteria.
8390 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00008391 for (int ThisCaptureLevel =
8392 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8393 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8394 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8395 // 1.2.2 OpenMP Language Terminology
8396 // Structured block - An executable statement with a single entry at the
8397 // top and a single exit at the bottom.
8398 // The point of exit cannot be a branch out of the structured block.
8399 // longjmp() and throw() must not violate the entry/exit criteria.
8400 CS->getCapturedDecl()->setNothrow();
8401 }
8402
Kelvin Li80e8f562016-12-29 22:16:30 +00008403 OMPLoopDirective::HelperExprs B;
8404 // In presence of clause 'collapse' with number of loops, it will
8405 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008406 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00008407 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8408 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00008409 VarsWithImplicitDSA, B);
8410 if (NestedLoopCount == 0)
8411 return StmtError();
8412
8413 assert((CurContext->isDependentContext() || B.builtAll()) &&
8414 "omp target teams distribute parallel for loop exprs were not built");
8415
Alexey Bataev647dd842018-01-15 20:59:40 +00008416 if (!CurContext->isDependentContext()) {
8417 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008418 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00008419 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8420 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8421 B.NumIterations, *this, CurScope,
8422 DSAStack))
8423 return StmtError();
8424 }
8425 }
8426
Reid Kleckner87a31802018-03-12 21:43:02 +00008427 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00008428 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00008429 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8430 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00008431}
8432
Kelvin Li1851df52017-01-03 05:23:48 +00008433StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8434 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008435 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00008436 if (!AStmt)
8437 return StmtError();
8438
Alexey Bataeve3727102018-04-18 15:57:46 +00008439 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00008440 // 1.2.2 OpenMP Language Terminology
8441 // Structured block - An executable statement with a single entry at the
8442 // top and a single exit at the bottom.
8443 // The point of exit cannot be a branch out of the structured block.
8444 // longjmp() and throw() must not violate the entry/exit criteria.
8445 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00008446 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8447 OMPD_target_teams_distribute_parallel_for_simd);
8448 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8449 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8450 // 1.2.2 OpenMP Language Terminology
8451 // Structured block - An executable statement with a single entry at the
8452 // top and a single exit at the bottom.
8453 // The point of exit cannot be a branch out of the structured block.
8454 // longjmp() and throw() must not violate the entry/exit criteria.
8455 CS->getCapturedDecl()->setNothrow();
8456 }
Kelvin Li1851df52017-01-03 05:23:48 +00008457
8458 OMPLoopDirective::HelperExprs B;
8459 // In presence of clause 'collapse' with number of loops, it will
8460 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008461 unsigned NestedLoopCount =
8462 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00008463 getCollapseNumberExpr(Clauses),
8464 nullptr /*ordered not a clause on distribute*/, CS, *this,
8465 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00008466 if (NestedLoopCount == 0)
8467 return StmtError();
8468
8469 assert((CurContext->isDependentContext() || B.builtAll()) &&
8470 "omp target teams distribute parallel for simd loop exprs were not "
8471 "built");
8472
8473 if (!CurContext->isDependentContext()) {
8474 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008475 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00008476 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8477 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8478 B.NumIterations, *this, CurScope,
8479 DSAStack))
8480 return StmtError();
8481 }
8482 }
8483
Alexey Bataev438388c2017-11-22 18:34:02 +00008484 if (checkSimdlenSafelenSpecified(*this, Clauses))
8485 return StmtError();
8486
Reid Kleckner87a31802018-03-12 21:43:02 +00008487 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00008488 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8489 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8490}
8491
Kelvin Lida681182017-01-10 18:08:18 +00008492StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8493 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008494 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00008495 if (!AStmt)
8496 return StmtError();
8497
8498 auto *CS = cast<CapturedStmt>(AStmt);
8499 // 1.2.2 OpenMP Language Terminology
8500 // Structured block - An executable statement with a single entry at the
8501 // top and a single exit at the bottom.
8502 // The point of exit cannot be a branch out of the structured block.
8503 // longjmp() and throw() must not violate the entry/exit criteria.
8504 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008505 for (int ThisCaptureLevel =
8506 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
8507 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8508 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8509 // 1.2.2 OpenMP Language Terminology
8510 // Structured block - An executable statement with a single entry at the
8511 // top and a single exit at the bottom.
8512 // The point of exit cannot be a branch out of the structured block.
8513 // longjmp() and throw() must not violate the entry/exit criteria.
8514 CS->getCapturedDecl()->setNothrow();
8515 }
Kelvin Lida681182017-01-10 18:08:18 +00008516
8517 OMPLoopDirective::HelperExprs B;
8518 // In presence of clause 'collapse' with number of loops, it will
8519 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008520 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00008521 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008522 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00008523 VarsWithImplicitDSA, B);
8524 if (NestedLoopCount == 0)
8525 return StmtError();
8526
8527 assert((CurContext->isDependentContext() || B.builtAll()) &&
8528 "omp target teams distribute simd loop exprs were not built");
8529
Alexey Bataev438388c2017-11-22 18:34:02 +00008530 if (!CurContext->isDependentContext()) {
8531 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008532 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008533 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8534 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8535 B.NumIterations, *this, CurScope,
8536 DSAStack))
8537 return StmtError();
8538 }
8539 }
8540
8541 if (checkSimdlenSafelenSpecified(*this, Clauses))
8542 return StmtError();
8543
Reid Kleckner87a31802018-03-12 21:43:02 +00008544 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00008545 return OMPTargetTeamsDistributeSimdDirective::Create(
8546 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8547}
8548
Alexey Bataeved09d242014-05-28 05:53:51 +00008549OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008550 SourceLocation StartLoc,
8551 SourceLocation LParenLoc,
8552 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008553 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008554 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00008555 case OMPC_final:
8556 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8557 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00008558 case OMPC_num_threads:
8559 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8560 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008561 case OMPC_safelen:
8562 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8563 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00008564 case OMPC_simdlen:
8565 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8566 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00008567 case OMPC_allocator:
8568 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
8569 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00008570 case OMPC_collapse:
8571 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8572 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008573 case OMPC_ordered:
8574 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8575 break;
Michael Wonge710d542015-08-07 16:16:36 +00008576 case OMPC_device:
8577 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8578 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00008579 case OMPC_num_teams:
8580 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8581 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008582 case OMPC_thread_limit:
8583 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8584 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00008585 case OMPC_priority:
8586 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8587 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008588 case OMPC_grainsize:
8589 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8590 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00008591 case OMPC_num_tasks:
8592 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8593 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00008594 case OMPC_hint:
8595 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8596 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008597 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008598 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008599 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008600 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008601 case OMPC_private:
8602 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008603 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008604 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008605 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008606 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008607 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008608 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008609 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008610 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008611 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00008612 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008613 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008614 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008615 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008616 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008617 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008618 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008619 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008620 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008621 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008622 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008623 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00008624 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008625 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008626 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00008627 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008628 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008629 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008630 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008631 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008632 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008633 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008634 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008635 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00008636 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00008637 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00008638 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00008639 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00008640 case OMPC_atomic_default_mem_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008641 llvm_unreachable("Clause is not allowed.");
8642 }
8643 return Res;
8644}
8645
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008646// An OpenMP directive such as 'target parallel' has two captured regions:
8647// for the 'target' and 'parallel' respectively. This function returns
8648// the region in which to capture expressions associated with a clause.
8649// A return value of OMPD_unknown signifies that the expression should not
8650// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008651static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
8652 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
8653 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008654 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008655 switch (CKind) {
8656 case OMPC_if:
8657 switch (DKind) {
8658 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008659 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008660 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008661 // If this clause applies to the nested 'parallel' region, capture within
8662 // the 'target' region, otherwise do not capture.
8663 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8664 CaptureRegion = OMPD_target;
8665 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00008666 case OMPD_target_teams_distribute_parallel_for:
8667 case OMPD_target_teams_distribute_parallel_for_simd:
8668 // If this clause applies to the nested 'parallel' region, capture within
8669 // the 'teams' region, otherwise do not capture.
8670 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8671 CaptureRegion = OMPD_teams;
8672 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008673 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008674 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008675 CaptureRegion = OMPD_teams;
8676 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008677 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008678 case OMPD_target_enter_data:
8679 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008680 CaptureRegion = OMPD_task;
8681 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008682 case OMPD_cancel:
8683 case OMPD_parallel:
8684 case OMPD_parallel_sections:
8685 case OMPD_parallel_for:
8686 case OMPD_parallel_for_simd:
8687 case OMPD_target:
8688 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008689 case OMPD_target_teams:
8690 case OMPD_target_teams_distribute:
8691 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008692 case OMPD_distribute_parallel_for:
8693 case OMPD_distribute_parallel_for_simd:
8694 case OMPD_task:
8695 case OMPD_taskloop:
8696 case OMPD_taskloop_simd:
8697 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008698 // Do not capture if-clause expressions.
8699 break;
8700 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008701 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008702 case OMPD_taskyield:
8703 case OMPD_barrier:
8704 case OMPD_taskwait:
8705 case OMPD_cancellation_point:
8706 case OMPD_flush:
8707 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008708 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008709 case OMPD_declare_simd:
8710 case OMPD_declare_target:
8711 case OMPD_end_declare_target:
8712 case OMPD_teams:
8713 case OMPD_simd:
8714 case OMPD_for:
8715 case OMPD_for_simd:
8716 case OMPD_sections:
8717 case OMPD_section:
8718 case OMPD_single:
8719 case OMPD_master:
8720 case OMPD_critical:
8721 case OMPD_taskgroup:
8722 case OMPD_distribute:
8723 case OMPD_ordered:
8724 case OMPD_atomic:
8725 case OMPD_distribute_simd:
8726 case OMPD_teams_distribute:
8727 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008728 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008729 llvm_unreachable("Unexpected OpenMP directive with if-clause");
8730 case OMPD_unknown:
8731 llvm_unreachable("Unknown OpenMP directive");
8732 }
8733 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008734 case OMPC_num_threads:
8735 switch (DKind) {
8736 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008737 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008738 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008739 CaptureRegion = OMPD_target;
8740 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008741 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008742 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008743 case OMPD_target_teams_distribute_parallel_for:
8744 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008745 CaptureRegion = OMPD_teams;
8746 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008747 case OMPD_parallel:
8748 case OMPD_parallel_sections:
8749 case OMPD_parallel_for:
8750 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008751 case OMPD_distribute_parallel_for:
8752 case OMPD_distribute_parallel_for_simd:
8753 // Do not capture num_threads-clause expressions.
8754 break;
8755 case OMPD_target_data:
8756 case OMPD_target_enter_data:
8757 case OMPD_target_exit_data:
8758 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008759 case OMPD_target:
8760 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008761 case OMPD_target_teams:
8762 case OMPD_target_teams_distribute:
8763 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008764 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008765 case OMPD_task:
8766 case OMPD_taskloop:
8767 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008768 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008769 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008770 case OMPD_taskyield:
8771 case OMPD_barrier:
8772 case OMPD_taskwait:
8773 case OMPD_cancellation_point:
8774 case OMPD_flush:
8775 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008776 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008777 case OMPD_declare_simd:
8778 case OMPD_declare_target:
8779 case OMPD_end_declare_target:
8780 case OMPD_teams:
8781 case OMPD_simd:
8782 case OMPD_for:
8783 case OMPD_for_simd:
8784 case OMPD_sections:
8785 case OMPD_section:
8786 case OMPD_single:
8787 case OMPD_master:
8788 case OMPD_critical:
8789 case OMPD_taskgroup:
8790 case OMPD_distribute:
8791 case OMPD_ordered:
8792 case OMPD_atomic:
8793 case OMPD_distribute_simd:
8794 case OMPD_teams_distribute:
8795 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008796 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008797 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8798 case OMPD_unknown:
8799 llvm_unreachable("Unknown OpenMP directive");
8800 }
8801 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008802 case OMPC_num_teams:
8803 switch (DKind) {
8804 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008805 case OMPD_target_teams_distribute:
8806 case OMPD_target_teams_distribute_simd:
8807 case OMPD_target_teams_distribute_parallel_for:
8808 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008809 CaptureRegion = OMPD_target;
8810 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008811 case OMPD_teams_distribute_parallel_for:
8812 case OMPD_teams_distribute_parallel_for_simd:
8813 case OMPD_teams:
8814 case OMPD_teams_distribute:
8815 case OMPD_teams_distribute_simd:
8816 // Do not capture num_teams-clause expressions.
8817 break;
8818 case OMPD_distribute_parallel_for:
8819 case OMPD_distribute_parallel_for_simd:
8820 case OMPD_task:
8821 case OMPD_taskloop:
8822 case OMPD_taskloop_simd:
8823 case OMPD_target_data:
8824 case OMPD_target_enter_data:
8825 case OMPD_target_exit_data:
8826 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008827 case OMPD_cancel:
8828 case OMPD_parallel:
8829 case OMPD_parallel_sections:
8830 case OMPD_parallel_for:
8831 case OMPD_parallel_for_simd:
8832 case OMPD_target:
8833 case OMPD_target_simd:
8834 case OMPD_target_parallel:
8835 case OMPD_target_parallel_for:
8836 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008837 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008838 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008839 case OMPD_taskyield:
8840 case OMPD_barrier:
8841 case OMPD_taskwait:
8842 case OMPD_cancellation_point:
8843 case OMPD_flush:
8844 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008845 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008846 case OMPD_declare_simd:
8847 case OMPD_declare_target:
8848 case OMPD_end_declare_target:
8849 case OMPD_simd:
8850 case OMPD_for:
8851 case OMPD_for_simd:
8852 case OMPD_sections:
8853 case OMPD_section:
8854 case OMPD_single:
8855 case OMPD_master:
8856 case OMPD_critical:
8857 case OMPD_taskgroup:
8858 case OMPD_distribute:
8859 case OMPD_ordered:
8860 case OMPD_atomic:
8861 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008862 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008863 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8864 case OMPD_unknown:
8865 llvm_unreachable("Unknown OpenMP directive");
8866 }
8867 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008868 case OMPC_thread_limit:
8869 switch (DKind) {
8870 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008871 case OMPD_target_teams_distribute:
8872 case OMPD_target_teams_distribute_simd:
8873 case OMPD_target_teams_distribute_parallel_for:
8874 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008875 CaptureRegion = OMPD_target;
8876 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008877 case OMPD_teams_distribute_parallel_for:
8878 case OMPD_teams_distribute_parallel_for_simd:
8879 case OMPD_teams:
8880 case OMPD_teams_distribute:
8881 case OMPD_teams_distribute_simd:
8882 // Do not capture thread_limit-clause expressions.
8883 break;
8884 case OMPD_distribute_parallel_for:
8885 case OMPD_distribute_parallel_for_simd:
8886 case OMPD_task:
8887 case OMPD_taskloop:
8888 case OMPD_taskloop_simd:
8889 case OMPD_target_data:
8890 case OMPD_target_enter_data:
8891 case OMPD_target_exit_data:
8892 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008893 case OMPD_cancel:
8894 case OMPD_parallel:
8895 case OMPD_parallel_sections:
8896 case OMPD_parallel_for:
8897 case OMPD_parallel_for_simd:
8898 case OMPD_target:
8899 case OMPD_target_simd:
8900 case OMPD_target_parallel:
8901 case OMPD_target_parallel_for:
8902 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008903 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008904 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008905 case OMPD_taskyield:
8906 case OMPD_barrier:
8907 case OMPD_taskwait:
8908 case OMPD_cancellation_point:
8909 case OMPD_flush:
8910 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008911 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008912 case OMPD_declare_simd:
8913 case OMPD_declare_target:
8914 case OMPD_end_declare_target:
8915 case OMPD_simd:
8916 case OMPD_for:
8917 case OMPD_for_simd:
8918 case OMPD_sections:
8919 case OMPD_section:
8920 case OMPD_single:
8921 case OMPD_master:
8922 case OMPD_critical:
8923 case OMPD_taskgroup:
8924 case OMPD_distribute:
8925 case OMPD_ordered:
8926 case OMPD_atomic:
8927 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008928 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008929 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8930 case OMPD_unknown:
8931 llvm_unreachable("Unknown OpenMP directive");
8932 }
8933 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008934 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008935 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008936 case OMPD_parallel_for:
8937 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008938 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008939 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008940 case OMPD_teams_distribute_parallel_for:
8941 case OMPD_teams_distribute_parallel_for_simd:
8942 case OMPD_target_parallel_for:
8943 case OMPD_target_parallel_for_simd:
8944 case OMPD_target_teams_distribute_parallel_for:
8945 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008946 CaptureRegion = OMPD_parallel;
8947 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008948 case OMPD_for:
8949 case OMPD_for_simd:
8950 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008951 break;
8952 case OMPD_task:
8953 case OMPD_taskloop:
8954 case OMPD_taskloop_simd:
8955 case OMPD_target_data:
8956 case OMPD_target_enter_data:
8957 case OMPD_target_exit_data:
8958 case OMPD_target_update:
8959 case OMPD_teams:
8960 case OMPD_teams_distribute:
8961 case OMPD_teams_distribute_simd:
8962 case OMPD_target_teams_distribute:
8963 case OMPD_target_teams_distribute_simd:
8964 case OMPD_target:
8965 case OMPD_target_simd:
8966 case OMPD_target_parallel:
8967 case OMPD_cancel:
8968 case OMPD_parallel:
8969 case OMPD_parallel_sections:
8970 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008971 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008972 case OMPD_taskyield:
8973 case OMPD_barrier:
8974 case OMPD_taskwait:
8975 case OMPD_cancellation_point:
8976 case OMPD_flush:
8977 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008978 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008979 case OMPD_declare_simd:
8980 case OMPD_declare_target:
8981 case OMPD_end_declare_target:
8982 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008983 case OMPD_sections:
8984 case OMPD_section:
8985 case OMPD_single:
8986 case OMPD_master:
8987 case OMPD_critical:
8988 case OMPD_taskgroup:
8989 case OMPD_distribute:
8990 case OMPD_ordered:
8991 case OMPD_atomic:
8992 case OMPD_distribute_simd:
8993 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00008994 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008995 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8996 case OMPD_unknown:
8997 llvm_unreachable("Unknown OpenMP directive");
8998 }
8999 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009000 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009001 switch (DKind) {
9002 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009003 case OMPD_teams_distribute_parallel_for_simd:
9004 case OMPD_teams_distribute:
9005 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009006 case OMPD_target_teams_distribute_parallel_for:
9007 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009008 case OMPD_target_teams_distribute:
9009 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00009010 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009011 break;
9012 case OMPD_distribute_parallel_for:
9013 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009014 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009015 case OMPD_distribute_simd:
9016 // Do not capture thread_limit-clause expressions.
9017 break;
9018 case OMPD_parallel_for:
9019 case OMPD_parallel_for_simd:
9020 case OMPD_target_parallel_for_simd:
9021 case OMPD_target_parallel_for:
9022 case OMPD_task:
9023 case OMPD_taskloop:
9024 case OMPD_taskloop_simd:
9025 case OMPD_target_data:
9026 case OMPD_target_enter_data:
9027 case OMPD_target_exit_data:
9028 case OMPD_target_update:
9029 case OMPD_teams:
9030 case OMPD_target:
9031 case OMPD_target_simd:
9032 case OMPD_target_parallel:
9033 case OMPD_cancel:
9034 case OMPD_parallel:
9035 case OMPD_parallel_sections:
9036 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009037 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009038 case OMPD_taskyield:
9039 case OMPD_barrier:
9040 case OMPD_taskwait:
9041 case OMPD_cancellation_point:
9042 case OMPD_flush:
9043 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009044 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009045 case OMPD_declare_simd:
9046 case OMPD_declare_target:
9047 case OMPD_end_declare_target:
9048 case OMPD_simd:
9049 case OMPD_for:
9050 case OMPD_for_simd:
9051 case OMPD_sections:
9052 case OMPD_section:
9053 case OMPD_single:
9054 case OMPD_master:
9055 case OMPD_critical:
9056 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009057 case OMPD_ordered:
9058 case OMPD_atomic:
9059 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00009060 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009061 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9062 case OMPD_unknown:
9063 llvm_unreachable("Unknown OpenMP directive");
9064 }
9065 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009066 case OMPC_device:
9067 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009068 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00009069 case OMPD_target_enter_data:
9070 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00009071 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00009072 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00009073 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00009074 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00009075 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00009076 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00009077 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00009078 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00009079 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00009080 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009081 CaptureRegion = OMPD_task;
9082 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009083 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009084 // Do not capture device-clause expressions.
9085 break;
9086 case OMPD_teams_distribute_parallel_for:
9087 case OMPD_teams_distribute_parallel_for_simd:
9088 case OMPD_teams:
9089 case OMPD_teams_distribute:
9090 case OMPD_teams_distribute_simd:
9091 case OMPD_distribute_parallel_for:
9092 case OMPD_distribute_parallel_for_simd:
9093 case OMPD_task:
9094 case OMPD_taskloop:
9095 case OMPD_taskloop_simd:
9096 case OMPD_cancel:
9097 case OMPD_parallel:
9098 case OMPD_parallel_sections:
9099 case OMPD_parallel_for:
9100 case OMPD_parallel_for_simd:
9101 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009102 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009103 case OMPD_taskyield:
9104 case OMPD_barrier:
9105 case OMPD_taskwait:
9106 case OMPD_cancellation_point:
9107 case OMPD_flush:
9108 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009109 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009110 case OMPD_declare_simd:
9111 case OMPD_declare_target:
9112 case OMPD_end_declare_target:
9113 case OMPD_simd:
9114 case OMPD_for:
9115 case OMPD_for_simd:
9116 case OMPD_sections:
9117 case OMPD_section:
9118 case OMPD_single:
9119 case OMPD_master:
9120 case OMPD_critical:
9121 case OMPD_taskgroup:
9122 case OMPD_distribute:
9123 case OMPD_ordered:
9124 case OMPD_atomic:
9125 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009126 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009127 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
9128 case OMPD_unknown:
9129 llvm_unreachable("Unknown OpenMP directive");
9130 }
9131 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009132 case OMPC_firstprivate:
9133 case OMPC_lastprivate:
9134 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009135 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009136 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009137 case OMPC_linear:
9138 case OMPC_default:
9139 case OMPC_proc_bind:
9140 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009141 case OMPC_safelen:
9142 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009143 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009144 case OMPC_collapse:
9145 case OMPC_private:
9146 case OMPC_shared:
9147 case OMPC_aligned:
9148 case OMPC_copyin:
9149 case OMPC_copyprivate:
9150 case OMPC_ordered:
9151 case OMPC_nowait:
9152 case OMPC_untied:
9153 case OMPC_mergeable:
9154 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009155 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009156 case OMPC_flush:
9157 case OMPC_read:
9158 case OMPC_write:
9159 case OMPC_update:
9160 case OMPC_capture:
9161 case OMPC_seq_cst:
9162 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009163 case OMPC_threads:
9164 case OMPC_simd:
9165 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009166 case OMPC_priority:
9167 case OMPC_grainsize:
9168 case OMPC_nogroup:
9169 case OMPC_num_tasks:
9170 case OMPC_hint:
9171 case OMPC_defaultmap:
9172 case OMPC_unknown:
9173 case OMPC_uniform:
9174 case OMPC_to:
9175 case OMPC_from:
9176 case OMPC_use_device_ptr:
9177 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009178 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009179 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009180 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009181 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009182 case OMPC_atomic_default_mem_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009183 llvm_unreachable("Unexpected OpenMP clause.");
9184 }
9185 return CaptureRegion;
9186}
9187
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009188OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9189 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009190 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009191 SourceLocation NameModifierLoc,
9192 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009193 SourceLocation EndLoc) {
9194 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009195 Stmt *HelperValStmt = nullptr;
9196 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009197 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9198 !Condition->isInstantiationDependent() &&
9199 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009200 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009201 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009202 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009203
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009204 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009205
9206 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
9207 CaptureRegion =
9208 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00009209 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009210 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009211 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009212 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9213 HelperValStmt = buildPreInits(Context, Captures);
9214 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009215 }
9216
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009217 return new (Context)
9218 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
9219 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009220}
9221
Alexey Bataev3778b602014-07-17 07:32:53 +00009222OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
9223 SourceLocation StartLoc,
9224 SourceLocation LParenLoc,
9225 SourceLocation EndLoc) {
9226 Expr *ValExpr = Condition;
9227 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9228 !Condition->isInstantiationDependent() &&
9229 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009230 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00009231 if (Val.isInvalid())
9232 return nullptr;
9233
Richard Smith03a4aa32016-06-23 19:02:52 +00009234 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00009235 }
9236
9237 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9238}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009239ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
9240 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00009241 if (!Op)
9242 return ExprError();
9243
9244 class IntConvertDiagnoser : public ICEConvertDiagnoser {
9245 public:
9246 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00009247 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00009248 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9249 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009250 return S.Diag(Loc, diag::err_omp_not_integral) << T;
9251 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009252 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
9253 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009254 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
9255 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009256 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
9257 QualType T,
9258 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009259 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
9260 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009261 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
9262 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009263 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009264 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009265 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009266 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9267 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009268 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
9269 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009270 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
9271 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009272 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009273 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009274 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009275 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
9276 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009277 llvm_unreachable("conversion functions are permitted");
9278 }
9279 } ConvertDiagnoser;
9280 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
9281}
9282
Alexey Bataeve3727102018-04-18 15:57:46 +00009283static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00009284 OpenMPClauseKind CKind,
9285 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009286 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
9287 !ValExpr->isInstantiationDependent()) {
9288 SourceLocation Loc = ValExpr->getExprLoc();
9289 ExprResult Value =
9290 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9291 if (Value.isInvalid())
9292 return false;
9293
9294 ValExpr = Value.get();
9295 // The expression must evaluate to a non-negative integer value.
9296 llvm::APSInt Result;
9297 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00009298 Result.isSigned() &&
9299 !((!StrictlyPositive && Result.isNonNegative()) ||
9300 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009301 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009302 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9303 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009304 return false;
9305 }
9306 }
9307 return true;
9308}
9309
Alexey Bataev568a8332014-03-06 06:15:19 +00009310OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9311 SourceLocation StartLoc,
9312 SourceLocation LParenLoc,
9313 SourceLocation EndLoc) {
9314 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009315 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009316
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009317 // OpenMP [2.5, Restrictions]
9318 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +00009319 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +00009320 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009321 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009322
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009323 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00009324 OpenMPDirectiveKind CaptureRegion =
9325 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9326 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009327 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009328 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009329 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9330 HelperValStmt = buildPreInits(Context, Captures);
9331 }
9332
9333 return new (Context) OMPNumThreadsClause(
9334 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00009335}
9336
Alexey Bataev62c87d22014-03-21 04:51:18 +00009337ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009338 OpenMPClauseKind CKind,
9339 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009340 if (!E)
9341 return ExprError();
9342 if (E->isValueDependent() || E->isTypeDependent() ||
9343 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009344 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009345 llvm::APSInt Result;
9346 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9347 if (ICE.isInvalid())
9348 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009349 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9350 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009351 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009352 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9353 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00009354 return ExprError();
9355 }
Alexander Musman09184fe2014-09-30 05:29:28 +00009356 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9357 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9358 << E->getSourceRange();
9359 return ExprError();
9360 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009361 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9362 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00009363 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009364 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00009365 return ICE;
9366}
9367
9368OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9369 SourceLocation LParenLoc,
9370 SourceLocation EndLoc) {
9371 // OpenMP [2.8.1, simd construct, Description]
9372 // The parameter of the safelen clause must be a constant
9373 // positive integer expression.
9374 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9375 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009376 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009377 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009378 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00009379}
9380
Alexey Bataev66b15b52015-08-21 11:14:16 +00009381OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9382 SourceLocation LParenLoc,
9383 SourceLocation EndLoc) {
9384 // OpenMP [2.8.1, simd construct, Description]
9385 // The parameter of the simdlen clause must be a constant
9386 // positive integer expression.
9387 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9388 if (Simdlen.isInvalid())
9389 return nullptr;
9390 return new (Context)
9391 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9392}
9393
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009394/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +00009395static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
9396 DSAStackTy *Stack) {
9397 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009398 if (!OMPAllocatorHandleT.isNull())
9399 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +00009400 // Build the predefined allocator expressions.
9401 bool ErrorFound = false;
9402 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
9403 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
9404 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
9405 StringRef Allocator =
9406 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
9407 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
9408 auto *VD = dyn_cast_or_null<ValueDecl>(
9409 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
9410 if (!VD) {
9411 ErrorFound = true;
9412 break;
9413 }
9414 QualType AllocatorType =
9415 VD->getType().getNonLValueExprType(S.getASTContext());
9416 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
9417 if (!Res.isUsable()) {
9418 ErrorFound = true;
9419 break;
9420 }
9421 if (OMPAllocatorHandleT.isNull())
9422 OMPAllocatorHandleT = AllocatorType;
9423 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
9424 ErrorFound = true;
9425 break;
9426 }
9427 Stack->setAllocator(AllocatorKind, Res.get());
9428 }
9429 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009430 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
9431 return false;
9432 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00009433 OMPAllocatorHandleT.addConst();
9434 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009435 return true;
9436}
9437
9438OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
9439 SourceLocation LParenLoc,
9440 SourceLocation EndLoc) {
9441 // OpenMP [2.11.3, allocate Directive, Description]
9442 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +00009443 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009444 return nullptr;
9445
9446 ExprResult Allocator = DefaultLvalueConversion(A);
9447 if (Allocator.isInvalid())
9448 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +00009449 Allocator = PerformImplicitConversion(Allocator.get(),
9450 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009451 Sema::AA_Initializing,
9452 /*AllowExplicit=*/true);
9453 if (Allocator.isInvalid())
9454 return nullptr;
9455 return new (Context)
9456 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
9457}
9458
Alexander Musman64d33f12014-06-04 07:53:32 +00009459OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
9460 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00009461 SourceLocation LParenLoc,
9462 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00009463 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009464 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00009465 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009466 // The parameter of the collapse clause must be a constant
9467 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00009468 ExprResult NumForLoopsResult =
9469 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
9470 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00009471 return nullptr;
9472 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00009473 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00009474}
9475
Alexey Bataev10e775f2015-07-30 11:36:16 +00009476OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
9477 SourceLocation EndLoc,
9478 SourceLocation LParenLoc,
9479 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00009480 // OpenMP [2.7.1, loop construct, Description]
9481 // OpenMP [2.8.1, simd construct, Description]
9482 // OpenMP [2.9.6, distribute construct, Description]
9483 // The parameter of the ordered clause must be a constant
9484 // positive integer expression if any.
9485 if (NumForLoops && LParenLoc.isValid()) {
9486 ExprResult NumForLoopsResult =
9487 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
9488 if (NumForLoopsResult.isInvalid())
9489 return nullptr;
9490 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009491 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +00009492 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00009493 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009494 auto *Clause = OMPOrderedClause::Create(
9495 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
9496 StartLoc, LParenLoc, EndLoc);
9497 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
9498 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +00009499}
9500
Alexey Bataeved09d242014-05-28 05:53:51 +00009501OMPClause *Sema::ActOnOpenMPSimpleClause(
9502 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
9503 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009504 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009505 switch (Kind) {
9506 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009507 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00009508 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
9509 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009510 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009511 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00009512 Res = ActOnOpenMPProcBindClause(
9513 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
9514 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009515 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009516 case OMPC_atomic_default_mem_order:
9517 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
9518 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
9519 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9520 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009521 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009522 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009523 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009524 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009525 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009526 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009527 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009528 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009529 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009530 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00009531 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009532 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00009533 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009534 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009535 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00009536 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009537 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009538 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009539 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009540 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009541 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009542 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009543 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009544 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009545 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009546 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009547 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009548 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009549 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009550 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009551 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009552 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009553 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009554 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009555 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009556 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009557 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009558 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009559 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009560 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009561 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009562 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009563 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009564 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009565 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009566 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009567 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009568 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009569 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009570 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009571 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009572 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009573 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009574 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009575 case OMPC_dynamic_allocators:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009576 llvm_unreachable("Clause is not allowed.");
9577 }
9578 return Res;
9579}
9580
Alexey Bataev6402bca2015-12-28 07:25:51 +00009581static std::string
9582getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
9583 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009584 SmallString<256> Buffer;
9585 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +00009586 unsigned Bound = Last >= 2 ? Last - 2 : 0;
9587 unsigned Skipped = Exclude.size();
9588 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +00009589 for (unsigned I = First; I < Last; ++I) {
9590 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009591 --Skipped;
9592 continue;
9593 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009594 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
9595 if (I == Bound - Skipped)
9596 Out << " or ";
9597 else if (I != Bound + 1 - Skipped)
9598 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +00009599 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009600 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +00009601}
9602
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009603OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9604 SourceLocation KindKwLoc,
9605 SourceLocation StartLoc,
9606 SourceLocation LParenLoc,
9607 SourceLocation EndLoc) {
9608 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00009609 static_assert(OMPC_DEFAULT_unknown > 0,
9610 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009611 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009612 << getListOfPossibleValues(OMPC_default, /*First=*/0,
9613 /*Last=*/OMPC_DEFAULT_unknown)
9614 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009615 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009616 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00009617 switch (Kind) {
9618 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009619 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009620 break;
9621 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009622 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009623 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009624 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009625 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00009626 break;
9627 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009628 return new (Context)
9629 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009630}
9631
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009632OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9633 SourceLocation KindKwLoc,
9634 SourceLocation StartLoc,
9635 SourceLocation LParenLoc,
9636 SourceLocation EndLoc) {
9637 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009638 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009639 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
9640 /*Last=*/OMPC_PROC_BIND_unknown)
9641 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009642 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009643 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009644 return new (Context)
9645 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009646}
9647
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009648OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
9649 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
9650 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9651 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
9652 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9653 << getListOfPossibleValues(
9654 OMPC_atomic_default_mem_order, /*First=*/0,
9655 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
9656 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
9657 return nullptr;
9658 }
9659 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
9660 LParenLoc, EndLoc);
9661}
9662
Alexey Bataev56dafe82014-06-20 07:16:17 +00009663OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009664 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009665 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009666 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009667 SourceLocation EndLoc) {
9668 OMPClause *Res = nullptr;
9669 switch (Kind) {
9670 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009671 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
9672 assert(Argument.size() == NumberOfElements &&
9673 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009674 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009675 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
9676 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
9677 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
9678 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
9679 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009680 break;
9681 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009682 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
9683 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
9684 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
9685 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009686 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00009687 case OMPC_dist_schedule:
9688 Res = ActOnOpenMPDistScheduleClause(
9689 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
9690 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
9691 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009692 case OMPC_defaultmap:
9693 enum { Modifier, DefaultmapKind };
9694 Res = ActOnOpenMPDefaultmapClause(
9695 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
9696 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00009697 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
9698 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009699 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00009700 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009701 case OMPC_num_threads:
9702 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009703 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009704 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009705 case OMPC_collapse:
9706 case OMPC_default:
9707 case OMPC_proc_bind:
9708 case OMPC_private:
9709 case OMPC_firstprivate:
9710 case OMPC_lastprivate:
9711 case OMPC_shared:
9712 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009713 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009714 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009715 case OMPC_linear:
9716 case OMPC_aligned:
9717 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009718 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009719 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009720 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009721 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009722 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009723 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009724 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009725 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009726 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009727 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009728 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009729 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009730 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009731 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009732 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009733 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009734 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009735 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009736 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009737 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009738 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009739 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009740 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009741 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009742 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009743 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009744 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009745 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009746 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009747 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009748 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009749 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009750 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009751 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009752 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009753 case OMPC_atomic_default_mem_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009754 llvm_unreachable("Clause is not allowed.");
9755 }
9756 return Res;
9757}
9758
Alexey Bataev6402bca2015-12-28 07:25:51 +00009759static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
9760 OpenMPScheduleClauseModifier M2,
9761 SourceLocation M1Loc, SourceLocation M2Loc) {
9762 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
9763 SmallVector<unsigned, 2> Excluded;
9764 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
9765 Excluded.push_back(M2);
9766 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
9767 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
9768 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
9769 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
9770 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
9771 << getListOfPossibleValues(OMPC_schedule,
9772 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
9773 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9774 Excluded)
9775 << getOpenMPClauseName(OMPC_schedule);
9776 return true;
9777 }
9778 return false;
9779}
9780
Alexey Bataev56dafe82014-06-20 07:16:17 +00009781OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009782 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009783 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009784 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9785 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
9786 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
9787 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
9788 return nullptr;
9789 // OpenMP, 2.7.1, Loop Construct, Restrictions
9790 // Either the monotonic modifier or the nonmonotonic modifier can be specified
9791 // but not both.
9792 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
9793 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
9794 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
9795 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
9796 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
9797 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
9798 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
9799 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
9800 return nullptr;
9801 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009802 if (Kind == OMPC_SCHEDULE_unknown) {
9803 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00009804 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
9805 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
9806 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9807 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9808 Exclude);
9809 } else {
9810 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9811 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009812 }
9813 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
9814 << Values << getOpenMPClauseName(OMPC_schedule);
9815 return nullptr;
9816 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00009817 // OpenMP, 2.7.1, Loop Construct, Restrictions
9818 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
9819 // schedule(guided).
9820 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
9821 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
9822 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
9823 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
9824 diag::err_omp_schedule_nonmonotonic_static);
9825 return nullptr;
9826 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009827 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00009828 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00009829 if (ChunkSize) {
9830 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
9831 !ChunkSize->isInstantiationDependent() &&
9832 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009833 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +00009834 ExprResult Val =
9835 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
9836 if (Val.isInvalid())
9837 return nullptr;
9838
9839 ValExpr = Val.get();
9840
9841 // OpenMP [2.7.1, Restrictions]
9842 // chunk_size must be a loop invariant integer expression with a positive
9843 // value.
9844 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00009845 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
9846 if (Result.isSigned() && !Result.isStrictlyPositive()) {
9847 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009848 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00009849 return nullptr;
9850 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00009851 } else if (getOpenMPCaptureRegionForClause(
9852 DSAStack->getCurrentDirective(), OMPC_schedule) !=
9853 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00009854 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009855 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009856 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +00009857 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9858 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009859 }
9860 }
9861 }
9862
Alexey Bataev6402bca2015-12-28 07:25:51 +00009863 return new (Context)
9864 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00009865 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009866}
9867
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009868OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
9869 SourceLocation StartLoc,
9870 SourceLocation EndLoc) {
9871 OMPClause *Res = nullptr;
9872 switch (Kind) {
9873 case OMPC_ordered:
9874 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
9875 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00009876 case OMPC_nowait:
9877 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
9878 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009879 case OMPC_untied:
9880 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
9881 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009882 case OMPC_mergeable:
9883 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
9884 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009885 case OMPC_read:
9886 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
9887 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00009888 case OMPC_write:
9889 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
9890 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00009891 case OMPC_update:
9892 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
9893 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00009894 case OMPC_capture:
9895 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
9896 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009897 case OMPC_seq_cst:
9898 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
9899 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00009900 case OMPC_threads:
9901 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
9902 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009903 case OMPC_simd:
9904 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
9905 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00009906 case OMPC_nogroup:
9907 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9908 break;
Kelvin Li1408f912018-09-26 04:28:39 +00009909 case OMPC_unified_address:
9910 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
9911 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +00009912 case OMPC_unified_shared_memory:
9913 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9914 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009915 case OMPC_reverse_offload:
9916 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
9917 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009918 case OMPC_dynamic_allocators:
9919 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
9920 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009921 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009922 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009923 case OMPC_num_threads:
9924 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009925 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009926 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009927 case OMPC_collapse:
9928 case OMPC_schedule:
9929 case OMPC_private:
9930 case OMPC_firstprivate:
9931 case OMPC_lastprivate:
9932 case OMPC_shared:
9933 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009934 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009935 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009936 case OMPC_linear:
9937 case OMPC_aligned:
9938 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009939 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009940 case OMPC_default:
9941 case OMPC_proc_bind:
9942 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009943 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009944 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009945 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009946 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009947 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009948 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009949 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009950 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009951 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00009952 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009953 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009954 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009955 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009956 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009957 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009958 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009959 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009960 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009961 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009962 case OMPC_atomic_default_mem_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009963 llvm_unreachable("Clause is not allowed.");
9964 }
9965 return Res;
9966}
9967
Alexey Bataev236070f2014-06-20 11:19:47 +00009968OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9969 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009970 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00009971 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
9972}
9973
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009974OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9975 SourceLocation EndLoc) {
9976 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
9977}
9978
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009979OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9980 SourceLocation EndLoc) {
9981 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9982}
9983
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009984OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
9985 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009986 return new (Context) OMPReadClause(StartLoc, EndLoc);
9987}
9988
Alexey Bataevdea47612014-07-23 07:46:59 +00009989OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9990 SourceLocation EndLoc) {
9991 return new (Context) OMPWriteClause(StartLoc, EndLoc);
9992}
9993
Alexey Bataev67a4f222014-07-23 10:25:33 +00009994OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9995 SourceLocation EndLoc) {
9996 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9997}
9998
Alexey Bataev459dec02014-07-24 06:46:57 +00009999OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10000 SourceLocation EndLoc) {
10001 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
10002}
10003
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010004OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10005 SourceLocation EndLoc) {
10006 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
10007}
10008
Alexey Bataev346265e2015-09-25 10:37:12 +000010009OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10010 SourceLocation EndLoc) {
10011 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
10012}
10013
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010014OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10015 SourceLocation EndLoc) {
10016 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
10017}
10018
Alexey Bataevb825de12015-12-07 10:51:44 +000010019OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10020 SourceLocation EndLoc) {
10021 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
10022}
10023
Kelvin Li1408f912018-09-26 04:28:39 +000010024OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10025 SourceLocation EndLoc) {
10026 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
10027}
10028
Patrick Lyster4a370b92018-10-01 13:47:43 +000010029OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10030 SourceLocation EndLoc) {
10031 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10032}
10033
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010034OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10035 SourceLocation EndLoc) {
10036 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
10037}
10038
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010039OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10040 SourceLocation EndLoc) {
10041 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
10042}
10043
Alexey Bataevc5e02582014-06-16 07:08:35 +000010044OMPClause *Sema::ActOnOpenMPVarListClause(
10045 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010046 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10047 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10048 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000010049 OpenMPLinearClauseKind LinKind,
10050 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010051 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
10052 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
10053 SourceLocation StartLoc = Locs.StartLoc;
10054 SourceLocation LParenLoc = Locs.LParenLoc;
10055 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010056 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010057 switch (Kind) {
10058 case OMPC_private:
10059 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10060 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010061 case OMPC_firstprivate:
10062 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10063 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010064 case OMPC_lastprivate:
10065 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10066 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010067 case OMPC_shared:
10068 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
10069 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010070 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000010071 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010072 EndLoc, ReductionOrMapperIdScopeSpec,
10073 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010074 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000010075 case OMPC_task_reduction:
10076 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010077 EndLoc, ReductionOrMapperIdScopeSpec,
10078 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000010079 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000010080 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010081 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10082 EndLoc, ReductionOrMapperIdScopeSpec,
10083 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000010084 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000010085 case OMPC_linear:
10086 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010087 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000010088 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010089 case OMPC_aligned:
10090 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
10091 ColonLoc, EndLoc);
10092 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010093 case OMPC_copyin:
10094 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
10095 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010096 case OMPC_copyprivate:
10097 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10098 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000010099 case OMPC_flush:
10100 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
10101 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010102 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000010103 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010104 StartLoc, LParenLoc, EndLoc);
10105 break;
10106 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010107 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
10108 ReductionOrMapperIdScopeSpec,
10109 ReductionOrMapperId, MapType, IsMapTypeImplicit,
10110 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010111 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010112 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000010113 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
10114 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000010115 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000010116 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000010117 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
10118 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000010119 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000010120 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010121 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010122 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000010123 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010124 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010125 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010126 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010127 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000010128 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000010129 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010130 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010131 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000010132 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010133 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010134 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010135 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010136 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010137 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010138 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010139 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010140 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010141 case OMPC_allocate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010142 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010143 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010144 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010145 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010146 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000010147 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010148 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010149 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010150 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010151 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010152 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010153 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000010154 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000010155 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010156 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010157 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010158 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010159 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010160 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000010161 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010162 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010163 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010164 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010165 case OMPC_atomic_default_mem_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010166 llvm_unreachable("Clause is not allowed.");
10167 }
10168 return Res;
10169}
10170
Alexey Bataev90c228f2016-02-08 09:29:13 +000010171ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000010172 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000010173 ExprResult Res = BuildDeclRefExpr(
10174 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
10175 if (!Res.isUsable())
10176 return ExprError();
10177 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
10178 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
10179 if (!Res.isUsable())
10180 return ExprError();
10181 }
10182 if (VK != VK_LValue && Res.get()->isGLValue()) {
10183 Res = DefaultLvalueConversion(Res.get());
10184 if (!Res.isUsable())
10185 return ExprError();
10186 }
10187 return Res;
10188}
10189
Alexey Bataev60da77e2016-02-29 05:54:20 +000010190static std::pair<ValueDecl *, bool>
10191getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
10192 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010193 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
10194 RefExpr->containsUnexpandedParameterPack())
10195 return std::make_pair(nullptr, true);
10196
Alexey Bataevd985eda2016-02-10 11:29:16 +000010197 // OpenMP [3.1, C/C++]
10198 // A list item is a variable name.
10199 // OpenMP [2.9.3.3, Restrictions, p.1]
10200 // A variable that is part of another variable (as an array or
10201 // structure element) cannot appear in a private clause.
10202 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010203 enum {
10204 NoArrayExpr = -1,
10205 ArraySubscript = 0,
10206 OMPArraySection = 1
10207 } IsArrayExpr = NoArrayExpr;
10208 if (AllowArraySection) {
10209 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010210 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010211 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
10212 Base = TempASE->getBase()->IgnoreParenImpCasts();
10213 RefExpr = Base;
10214 IsArrayExpr = ArraySubscript;
10215 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010216 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010217 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
10218 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10219 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
10220 Base = TempASE->getBase()->IgnoreParenImpCasts();
10221 RefExpr = Base;
10222 IsArrayExpr = OMPArraySection;
10223 }
10224 }
10225 ELoc = RefExpr->getExprLoc();
10226 ERange = RefExpr->getSourceRange();
10227 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +000010228 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
10229 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
10230 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
10231 (S.getCurrentThisType().isNull() || !ME ||
10232 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
10233 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010234 if (IsArrayExpr != NoArrayExpr) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010235 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
10236 << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000010237 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010238 S.Diag(ELoc,
10239 AllowArraySection
10240 ? diag::err_omp_expected_var_name_member_expr_or_array_item
10241 : diag::err_omp_expected_var_name_member_expr)
10242 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
10243 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010244 return std::make_pair(nullptr, false);
10245 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010246 return std::make_pair(
10247 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010248}
10249
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010250OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10251 SourceLocation StartLoc,
10252 SourceLocation LParenLoc,
10253 SourceLocation EndLoc) {
10254 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000010255 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000010256 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010257 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010258 SourceLocation ELoc;
10259 SourceRange ERange;
10260 Expr *SimpleRefExpr = RefExpr;
10261 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010262 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010263 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010264 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010265 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010266 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010267 ValueDecl *D = Res.first;
10268 if (!D)
10269 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010270
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010271 QualType Type = D->getType();
10272 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010273
10274 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10275 // A variable that appears in a private clause must not have an incomplete
10276 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010277 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010278 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010279 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010280
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010281 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10282 // A variable that is privatized must not have a const-qualified type
10283 // unless it is of class type with a mutable member. This restriction does
10284 // not apply to the firstprivate clause.
10285 //
10286 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
10287 // A variable that appears in a private clause must not have a
10288 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010289 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010290 continue;
10291
Alexey Bataev758e55e2013-09-06 18:03:48 +000010292 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10293 // in a Construct]
10294 // Variables with the predetermined data-sharing attributes may not be
10295 // listed in data-sharing attributes clauses, except for the cases
10296 // listed below. For these exceptions only, listing a predetermined
10297 // variable in a data-sharing attribute clause is allowed and overrides
10298 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010299 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010300 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010301 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10302 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000010303 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010304 continue;
10305 }
10306
Alexey Bataeve3727102018-04-18 15:57:46 +000010307 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010308 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010309 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000010310 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010311 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10312 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000010313 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010314 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010315 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010316 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010317 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010318 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010319 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010320 continue;
10321 }
10322
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010323 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10324 // A list item cannot appear in both a map clause and a data-sharing
10325 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000010326 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010327 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010328 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010329 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010330 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
10331 OpenMPClauseKind WhereFoundClauseKind) -> bool {
10332 ConflictKind = WhereFoundClauseKind;
10333 return true;
10334 })) {
10335 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010336 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000010337 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000010338 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000010339 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010340 continue;
10341 }
10342 }
10343
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010344 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
10345 // A variable of class type (or array thereof) that appears in a private
10346 // clause requires an accessible, unambiguous default constructor for the
10347 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000010348 // Generate helper private variable and initialize it with the default
10349 // value. The address of the original variable is replaced by the address of
10350 // the new private variable in CodeGen. This new variable is not added to
10351 // IdResolver, so the code in the OpenMP region uses original variable for
10352 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010353 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010354 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010355 buildVarDecl(*this, ELoc, Type, D->getName(),
10356 D->hasAttrs() ? &D->getAttrs() : nullptr,
10357 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000010358 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010359 if (VDPrivate->isInvalidDecl())
10360 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000010361 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010362 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010363
Alexey Bataev90c228f2016-02-08 09:29:13 +000010364 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010365 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010366 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000010367 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010368 Vars.push_back((VD || CurContext->isDependentContext())
10369 ? RefExpr->IgnoreParens()
10370 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010371 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010372 }
10373
Alexey Bataeved09d242014-05-28 05:53:51 +000010374 if (Vars.empty())
10375 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010376
Alexey Bataev03b340a2014-10-21 03:16:40 +000010377 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10378 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010379}
10380
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010381namespace {
10382class DiagsUninitializedSeveretyRAII {
10383private:
10384 DiagnosticsEngine &Diags;
10385 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000010386 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010387
10388public:
10389 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10390 bool IsIgnored)
10391 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10392 if (!IsIgnored) {
10393 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10394 /*Map*/ diag::Severity::Ignored, Loc);
10395 }
10396 }
10397 ~DiagsUninitializedSeveretyRAII() {
10398 if (!IsIgnored)
10399 Diags.popMappings(SavedLoc);
10400 }
10401};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010402}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010403
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010404OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10405 SourceLocation StartLoc,
10406 SourceLocation LParenLoc,
10407 SourceLocation EndLoc) {
10408 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010409 SmallVector<Expr *, 8> PrivateCopies;
10410 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000010411 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010412 bool IsImplicitClause =
10413 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000010414 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010415
Alexey Bataeve3727102018-04-18 15:57:46 +000010416 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010417 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010418 SourceLocation ELoc;
10419 SourceRange ERange;
10420 Expr *SimpleRefExpr = RefExpr;
10421 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010422 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010423 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010424 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010425 PrivateCopies.push_back(nullptr);
10426 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010427 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010428 ValueDecl *D = Res.first;
10429 if (!D)
10430 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010431
Alexey Bataev60da77e2016-02-29 05:54:20 +000010432 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010433 QualType Type = D->getType();
10434 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010435
10436 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10437 // A variable that appears in a private clause must not have an incomplete
10438 // type or a reference type.
10439 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000010440 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010441 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010442 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010443
10444 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10445 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000010446 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010447 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000010448 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010449
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010450 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000010451 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010452 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010453 DSAStackTy::DSAVarData DVar =
10454 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000010455 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010456 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010457 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010458 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10459 // A list item that specifies a given variable may not appear in more
10460 // than one clause on the same directive, except that a variable may be
10461 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010462 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10463 // A list item may appear in a firstprivate or lastprivate clause but not
10464 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010465 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010466 (isOpenMPDistributeDirective(CurrDir) ||
10467 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010468 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010469 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010470 << getOpenMPClauseName(DVar.CKind)
10471 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010472 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010473 continue;
10474 }
10475
10476 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10477 // in a Construct]
10478 // Variables with the predetermined data-sharing attributes may not be
10479 // listed in data-sharing attributes clauses, except for the cases
10480 // listed below. For these exceptions only, listing a predetermined
10481 // variable in a data-sharing attribute clause is allowed and overrides
10482 // the variable's predetermined data-sharing attributes.
10483 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10484 // in a Construct, C/C++, p.2]
10485 // Variables with const-qualified type having no mutable member may be
10486 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000010487 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010488 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
10489 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010490 << getOpenMPClauseName(DVar.CKind)
10491 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010492 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010493 continue;
10494 }
10495
10496 // OpenMP [2.9.3.4, Restrictions, p.2]
10497 // A list item that is private within a parallel region must not appear
10498 // in a firstprivate clause on a worksharing construct if any of the
10499 // worksharing regions arising from the worksharing construct ever bind
10500 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010501 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10502 // A list item that is private within a teams region must not appear in a
10503 // firstprivate clause on a distribute construct if any of the distribute
10504 // regions arising from the distribute construct ever bind to any of the
10505 // teams regions arising from the teams construct.
10506 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10507 // A list item that appears in a reduction clause of a teams construct
10508 // must not appear in a firstprivate clause on a distribute construct if
10509 // any of the distribute regions arising from the distribute construct
10510 // ever bind to any of the teams regions arising from the teams construct.
10511 if ((isOpenMPWorksharingDirective(CurrDir) ||
10512 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010513 !isOpenMPParallelDirective(CurrDir) &&
10514 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010515 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010516 if (DVar.CKind != OMPC_shared &&
10517 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010518 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010519 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000010520 Diag(ELoc, diag::err_omp_required_access)
10521 << getOpenMPClauseName(OMPC_firstprivate)
10522 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010523 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010524 continue;
10525 }
10526 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010527 // OpenMP [2.9.3.4, Restrictions, p.3]
10528 // A list item that appears in a reduction clause of a parallel construct
10529 // must not appear in a firstprivate clause on a worksharing or task
10530 // construct if any of the worksharing or task regions arising from the
10531 // worksharing or task construct ever bind to any of the parallel regions
10532 // arising from the parallel construct.
10533 // OpenMP [2.9.3.4, Restrictions, p.4]
10534 // A list item that appears in a reduction clause in worksharing
10535 // construct must not appear in a firstprivate clause in a task construct
10536 // encountered during execution of any of the worksharing regions arising
10537 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000010538 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010539 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010540 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10541 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010542 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010543 isOpenMPWorksharingDirective(K) ||
10544 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010545 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010546 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010547 if (DVar.CKind == OMPC_reduction &&
10548 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010549 isOpenMPWorksharingDirective(DVar.DKind) ||
10550 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010551 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10552 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000010553 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010554 continue;
10555 }
10556 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010557
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010558 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10559 // A list item cannot appear in both a map clause and a data-sharing
10560 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +000010561 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010562 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010563 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010564 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000010565 [&ConflictKind](
10566 OMPClauseMappableExprCommon::MappableExprComponentListRef,
10567 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000010568 ConflictKind = WhereFoundClauseKind;
10569 return true;
10570 })) {
10571 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010572 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000010573 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010574 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000010575 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010576 continue;
10577 }
10578 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010579 }
10580
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010581 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010582 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000010583 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010584 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10585 << getOpenMPClauseName(OMPC_firstprivate) << Type
10586 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10587 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010588 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010589 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010590 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010591 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000010592 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010593 continue;
10594 }
10595
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010596 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010597 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010598 buildVarDecl(*this, ELoc, Type, D->getName(),
10599 D->hasAttrs() ? &D->getAttrs() : nullptr,
10600 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010601 // Generate helper private variable and initialize it with the value of the
10602 // original variable. The address of the original variable is replaced by
10603 // the address of the new private variable in the CodeGen. This new variable
10604 // is not added to IdResolver, so the code in the OpenMP region uses
10605 // original variable for proper diagnostics and variable capturing.
10606 Expr *VDInitRefExpr = nullptr;
10607 // For arrays generate initializer for single element and replace it by the
10608 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010609 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010610 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010611 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010612 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010613 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010614 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010615 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
10616 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000010617 InitializedEntity Entity =
10618 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010619 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
10620
10621 InitializationSequence InitSeq(*this, Entity, Kind, Init);
10622 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
10623 if (Result.isInvalid())
10624 VDPrivate->setInvalidDecl();
10625 else
10626 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010627 // Remove temp variable declaration.
10628 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010629 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000010630 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
10631 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000010632 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10633 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000010634 AddInitializerToDecl(VDPrivate,
10635 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010636 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010637 }
10638 if (VDPrivate->isInvalidDecl()) {
10639 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010640 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010641 diag::note_omp_task_predetermined_firstprivate_here);
10642 }
10643 continue;
10644 }
10645 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010646 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000010647 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10648 RefExpr->getExprLoc());
10649 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010650 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010651 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010652 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010653 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010654 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010655 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010656 ExprCaptures.push_back(Ref->getDecl());
10657 }
Alexey Bataev417089f2016-02-17 13:19:37 +000010658 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010659 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010660 Vars.push_back((VD || CurContext->isDependentContext())
10661 ? RefExpr->IgnoreParens()
10662 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010663 PrivateCopies.push_back(VDPrivateRefExpr);
10664 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010665 }
10666
Alexey Bataeved09d242014-05-28 05:53:51 +000010667 if (Vars.empty())
10668 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010669
10670 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010671 Vars, PrivateCopies, Inits,
10672 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010673}
10674
Alexander Musman1bb328c2014-06-04 13:06:39 +000010675OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
10676 SourceLocation StartLoc,
10677 SourceLocation LParenLoc,
10678 SourceLocation EndLoc) {
10679 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000010680 SmallVector<Expr *, 8> SrcExprs;
10681 SmallVector<Expr *, 8> DstExprs;
10682 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000010683 SmallVector<Decl *, 4> ExprCaptures;
10684 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000010685 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010686 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010687 SourceLocation ELoc;
10688 SourceRange ERange;
10689 Expr *SimpleRefExpr = RefExpr;
10690 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000010691 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010692 // It will be analyzed later.
10693 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010694 SrcExprs.push_back(nullptr);
10695 DstExprs.push_back(nullptr);
10696 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010697 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010698 ValueDecl *D = Res.first;
10699 if (!D)
10700 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010701
Alexey Bataev74caaf22016-02-20 04:09:36 +000010702 QualType Type = D->getType();
10703 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010704
10705 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
10706 // A variable that appears in a lastprivate clause must not have an
10707 // incomplete type or a reference type.
10708 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000010709 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000010710 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010711 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010712
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010713 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10714 // A variable that is privatized must not have a const-qualified type
10715 // unless it is of class type with a mutable member. This restriction does
10716 // not apply to the firstprivate clause.
10717 //
10718 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
10719 // A variable that appears in a lastprivate clause must not have a
10720 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010721 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010722 continue;
10723
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010724 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010725 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10726 // in a Construct]
10727 // Variables with the predetermined data-sharing attributes may not be
10728 // listed in data-sharing attributes clauses, except for the cases
10729 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010730 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10731 // A list item may appear in a firstprivate or lastprivate clause but not
10732 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000010733 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010734 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010735 (isOpenMPDistributeDirective(CurrDir) ||
10736 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000010737 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
10738 Diag(ELoc, diag::err_omp_wrong_dsa)
10739 << getOpenMPClauseName(DVar.CKind)
10740 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010741 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010742 continue;
10743 }
10744
Alexey Bataevf29276e2014-06-18 04:14:57 +000010745 // OpenMP [2.14.3.5, Restrictions, p.2]
10746 // A list item that is private within a parallel region, or that appears in
10747 // the reduction clause of a parallel construct, must not appear in a
10748 // lastprivate clause on a worksharing construct if any of the corresponding
10749 // worksharing regions ever binds to any of the corresponding parallel
10750 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000010751 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000010752 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010753 !isOpenMPParallelDirective(CurrDir) &&
10754 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000010755 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010756 if (DVar.CKind != OMPC_shared) {
10757 Diag(ELoc, diag::err_omp_required_access)
10758 << getOpenMPClauseName(OMPC_lastprivate)
10759 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010760 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010761 continue;
10762 }
10763 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010764
Alexander Musman1bb328c2014-06-04 13:06:39 +000010765 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000010766 // A variable of class type (or array thereof) that appears in a
10767 // lastprivate clause requires an accessible, unambiguous default
10768 // constructor for the class type, unless the list item is also specified
10769 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000010770 // A variable of class type (or array thereof) that appears in a
10771 // lastprivate clause requires an accessible, unambiguous copy assignment
10772 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000010773 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010774 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
10775 Type.getUnqualifiedType(), ".lastprivate.src",
10776 D->hasAttrs() ? &D->getAttrs() : nullptr);
10777 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000010778 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010779 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010780 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000010781 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000010782 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000010783 // For arrays generate assignment operation for single element and replace
10784 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010785 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
10786 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010787 if (AssignmentOp.isInvalid())
10788 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000010789 AssignmentOp =
10790 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000010791 if (AssignmentOp.isInvalid())
10792 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010793
Alexey Bataev74caaf22016-02-20 04:09:36 +000010794 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010795 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010796 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010797 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010798 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010799 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000010800 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010801 ExprCaptures.push_back(Ref->getDecl());
10802 }
10803 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000010804 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010805 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010806 ExprResult RefRes = DefaultLvalueConversion(Ref);
10807 if (!RefRes.isUsable())
10808 continue;
10809 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010810 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10811 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010812 if (!PostUpdateRes.isUsable())
10813 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010814 ExprPostUpdates.push_back(
10815 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010816 }
10817 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010818 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010819 Vars.push_back((VD || CurContext->isDependentContext())
10820 ? RefExpr->IgnoreParens()
10821 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000010822 SrcExprs.push_back(PseudoSrcExpr);
10823 DstExprs.push_back(PseudoDstExpr);
10824 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000010825 }
10826
10827 if (Vars.empty())
10828 return nullptr;
10829
10830 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000010831 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010832 buildPreInits(Context, ExprCaptures),
10833 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000010834}
10835
Alexey Bataev758e55e2013-09-06 18:03:48 +000010836OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10837 SourceLocation StartLoc,
10838 SourceLocation LParenLoc,
10839 SourceLocation EndLoc) {
10840 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000010841 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010842 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010843 SourceLocation ELoc;
10844 SourceRange ERange;
10845 Expr *SimpleRefExpr = RefExpr;
10846 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010847 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000010848 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010849 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010850 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010851 ValueDecl *D = Res.first;
10852 if (!D)
10853 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010854
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010855 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010856 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10857 // in a Construct]
10858 // Variables with the predetermined data-sharing attributes may not be
10859 // listed in data-sharing attributes clauses, except for the cases
10860 // listed below. For these exceptions only, listing a predetermined
10861 // variable in a data-sharing attribute clause is allowed and overrides
10862 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010863 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000010864 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
10865 DVar.RefExpr) {
10866 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10867 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010868 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010869 continue;
10870 }
10871
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010872 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010873 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010874 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010875 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010876 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
10877 ? RefExpr->IgnoreParens()
10878 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010879 }
10880
Alexey Bataeved09d242014-05-28 05:53:51 +000010881 if (Vars.empty())
10882 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010883
10884 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
10885}
10886
Alexey Bataevc5e02582014-06-16 07:08:35 +000010887namespace {
10888class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
10889 DSAStackTy *Stack;
10890
10891public:
10892 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010893 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
10894 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010895 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
10896 return false;
10897 if (DVar.CKind != OMPC_unknown)
10898 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010899 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010900 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010901 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010902 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010903 }
10904 return false;
10905 }
10906 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010907 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010908 if (Child && Visit(Child))
10909 return true;
10910 }
10911 return false;
10912 }
Alexey Bataev23b69422014-06-18 07:08:49 +000010913 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010914};
Alexey Bataev23b69422014-06-18 07:08:49 +000010915} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000010916
Alexey Bataev60da77e2016-02-29 05:54:20 +000010917namespace {
10918// Transform MemberExpression for specified FieldDecl of current class to
10919// DeclRefExpr to specified OMPCapturedExprDecl.
10920class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
10921 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000010922 ValueDecl *Field = nullptr;
10923 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010924
10925public:
10926 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
10927 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
10928
10929 ExprResult TransformMemberExpr(MemberExpr *E) {
10930 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
10931 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000010932 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010933 return CapturedExpr;
10934 }
10935 return BaseTransform::TransformMemberExpr(E);
10936 }
10937 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
10938};
10939} // namespace
10940
Alexey Bataev97d18bf2018-04-11 19:21:00 +000010941template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000010942static T filterLookupForUDReductionAndMapper(
10943 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010944 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010945 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010946 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010947 return Res;
10948 }
10949 }
10950 return T();
10951}
10952
Alexey Bataev43b90b72018-09-12 16:31:59 +000010953static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
10954 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
10955
10956 for (auto RD : D->redecls()) {
10957 // Don't bother with extra checks if we already know this one isn't visible.
10958 if (RD == D)
10959 continue;
10960
10961 auto ND = cast<NamedDecl>(RD);
10962 if (LookupResult::isVisible(SemaRef, ND))
10963 return ND;
10964 }
10965
10966 return nullptr;
10967}
10968
10969static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000010970argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000010971 SourceLocation Loc, QualType Ty,
10972 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
10973 // Find all of the associated namespaces and classes based on the
10974 // arguments we have.
10975 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10976 Sema::AssociatedClassSet AssociatedClasses;
10977 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
10978 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
10979 AssociatedClasses);
10980
10981 // C++ [basic.lookup.argdep]p3:
10982 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10983 // and let Y be the lookup set produced by argument dependent
10984 // lookup (defined as follows). If X contains [...] then Y is
10985 // empty. Otherwise Y is the set of declarations found in the
10986 // namespaces associated with the argument types as described
10987 // below. The set of declarations found by the lookup of the name
10988 // is the union of X and Y.
10989 //
10990 // Here, we compute Y and add its members to the overloaded
10991 // candidate set.
10992 for (auto *NS : AssociatedNamespaces) {
10993 // When considering an associated namespace, the lookup is the
10994 // same as the lookup performed when the associated namespace is
10995 // used as a qualifier (3.4.3.2) except that:
10996 //
10997 // -- Any using-directives in the associated namespace are
10998 // ignored.
10999 //
11000 // -- Any namespace-scope friend functions declared in
11001 // associated classes are visible within their respective
11002 // namespaces even if they are not visible during an ordinary
11003 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000011004 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000011005 for (auto *D : R) {
11006 auto *Underlying = D;
11007 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11008 Underlying = USD->getTargetDecl();
11009
Michael Kruse4304e9d2019-02-19 16:38:20 +000011010 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
11011 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000011012 continue;
11013
11014 if (!SemaRef.isVisible(D)) {
11015 D = findAcceptableDecl(SemaRef, D);
11016 if (!D)
11017 continue;
11018 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11019 Underlying = USD->getTargetDecl();
11020 }
11021 Lookups.emplace_back();
11022 Lookups.back().addDecl(Underlying);
11023 }
11024 }
11025}
11026
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011027static ExprResult
11028buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
11029 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
11030 const DeclarationNameInfo &ReductionId, QualType Ty,
11031 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
11032 if (ReductionIdScopeSpec.isInvalid())
11033 return ExprError();
11034 SmallVector<UnresolvedSet<8>, 4> Lookups;
11035 if (S) {
11036 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11037 Lookup.suppressDiagnostics();
11038 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011039 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011040 do {
11041 S = S->getParent();
11042 } while (S && !S->isDeclScope(D));
11043 if (S)
11044 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000011045 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011046 Lookups.back().append(Lookup.begin(), Lookup.end());
11047 Lookup.clear();
11048 }
11049 } else if (auto *ULE =
11050 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
11051 Lookups.push_back(UnresolvedSet<8>());
11052 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011053 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011054 if (D == PrevD)
11055 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000011056 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011057 Lookups.back().addDecl(DRD);
11058 PrevD = D;
11059 }
11060 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000011061 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
11062 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011063 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000011064 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011065 return !D->isInvalidDecl() &&
11066 (D->getType()->isDependentType() ||
11067 D->getType()->isInstantiationDependentType() ||
11068 D->getType()->containsUnexpandedParameterPack());
11069 })) {
11070 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000011071 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000011072 if (Set.empty())
11073 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011074 ResSet.append(Set.begin(), Set.end());
11075 // The last item marks the end of all declarations at the specified scope.
11076 ResSet.addDecl(Set[Set.size() - 1]);
11077 }
11078 return UnresolvedLookupExpr::Create(
11079 SemaRef.Context, /*NamingClass=*/nullptr,
11080 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
11081 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
11082 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000011083 // Lookup inside the classes.
11084 // C++ [over.match.oper]p3:
11085 // For a unary operator @ with an operand of a type whose
11086 // cv-unqualified version is T1, and for a binary operator @ with
11087 // a left operand of a type whose cv-unqualified version is T1 and
11088 // a right operand of a type whose cv-unqualified version is T2,
11089 // three sets of candidate functions, designated member
11090 // candidates, non-member candidates and built-in candidates, are
11091 // constructed as follows:
11092 // -- If T1 is a complete class type or a class currently being
11093 // defined, the set of member candidates is the result of the
11094 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
11095 // the set of member candidates is empty.
11096 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11097 Lookup.suppressDiagnostics();
11098 if (const auto *TyRec = Ty->getAs<RecordType>()) {
11099 // Complete the type if it can be completed.
11100 // If the type is neither complete nor being defined, bail out now.
11101 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
11102 TyRec->getDecl()->getDefinition()) {
11103 Lookup.clear();
11104 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
11105 if (Lookup.empty()) {
11106 Lookups.emplace_back();
11107 Lookups.back().append(Lookup.begin(), Lookup.end());
11108 }
11109 }
11110 }
11111 // Perform ADL.
Alexey Bataev74a04e82019-03-13 19:31:34 +000011112 if (SemaRef.getLangOpts().CPlusPlus) {
11113 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
11114 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11115 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
11116 if (!D->isInvalidDecl() &&
11117 SemaRef.Context.hasSameType(D->getType(), Ty))
11118 return D;
11119 return nullptr;
11120 }))
11121 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
11122 VK_LValue, Loc);
11123 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11124 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
11125 if (!D->isInvalidDecl() &&
11126 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
11127 !Ty.isMoreQualifiedThan(D->getType()))
11128 return D;
11129 return nullptr;
11130 })) {
11131 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
11132 /*DetectVirtual=*/false);
11133 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
11134 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
11135 VD->getType().getUnqualifiedType()))) {
11136 if (SemaRef.CheckBaseClassAccess(
11137 Loc, VD->getType(), Ty, Paths.front(),
11138 /*DiagID=*/0) != Sema::AR_inaccessible) {
11139 SemaRef.BuildBasePathArray(Paths, BasePath);
11140 return SemaRef.BuildDeclRefExpr(
11141 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
11142 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011143 }
11144 }
11145 }
11146 }
11147 if (ReductionIdScopeSpec.isSet()) {
11148 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
11149 return ExprError();
11150 }
11151 return ExprEmpty();
11152}
11153
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011154namespace {
11155/// Data for the reduction-based clauses.
11156struct ReductionData {
11157 /// List of original reduction items.
11158 SmallVector<Expr *, 8> Vars;
11159 /// List of private copies of the reduction items.
11160 SmallVector<Expr *, 8> Privates;
11161 /// LHS expressions for the reduction_op expressions.
11162 SmallVector<Expr *, 8> LHSs;
11163 /// RHS expressions for the reduction_op expressions.
11164 SmallVector<Expr *, 8> RHSs;
11165 /// Reduction operation expression.
11166 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000011167 /// Taskgroup descriptors for the corresponding reduction items in
11168 /// in_reduction clauses.
11169 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011170 /// List of captures for clause.
11171 SmallVector<Decl *, 4> ExprCaptures;
11172 /// List of postupdate expressions.
11173 SmallVector<Expr *, 4> ExprPostUpdates;
11174 ReductionData() = delete;
11175 /// Reserves required memory for the reduction data.
11176 ReductionData(unsigned Size) {
11177 Vars.reserve(Size);
11178 Privates.reserve(Size);
11179 LHSs.reserve(Size);
11180 RHSs.reserve(Size);
11181 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000011182 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011183 ExprCaptures.reserve(Size);
11184 ExprPostUpdates.reserve(Size);
11185 }
11186 /// Stores reduction item and reduction operation only (required for dependent
11187 /// reduction item).
11188 void push(Expr *Item, Expr *ReductionOp) {
11189 Vars.emplace_back(Item);
11190 Privates.emplace_back(nullptr);
11191 LHSs.emplace_back(nullptr);
11192 RHSs.emplace_back(nullptr);
11193 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011194 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011195 }
11196 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000011197 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
11198 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011199 Vars.emplace_back(Item);
11200 Privates.emplace_back(Private);
11201 LHSs.emplace_back(LHS);
11202 RHSs.emplace_back(RHS);
11203 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011204 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011205 }
11206};
11207} // namespace
11208
Alexey Bataeve3727102018-04-18 15:57:46 +000011209static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011210 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
11211 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
11212 const Expr *Length = OASE->getLength();
11213 if (Length == nullptr) {
11214 // For array sections of the form [1:] or [:], we would need to analyze
11215 // the lower bound...
11216 if (OASE->getColonLoc().isValid())
11217 return false;
11218
11219 // This is an array subscript which has implicit length 1!
11220 SingleElement = true;
11221 ArraySizes.push_back(llvm::APSInt::get(1));
11222 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011223 Expr::EvalResult Result;
11224 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011225 return false;
11226
Fangrui Song407659a2018-11-30 23:41:18 +000011227 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011228 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
11229 ArraySizes.push_back(ConstantLengthValue);
11230 }
11231
11232 // Get the base of this array section and walk up from there.
11233 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
11234
11235 // We require length = 1 for all array sections except the right-most to
11236 // guarantee that the memory region is contiguous and has no holes in it.
11237 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
11238 Length = TempOASE->getLength();
11239 if (Length == nullptr) {
11240 // For array sections of the form [1:] or [:], we would need to analyze
11241 // the lower bound...
11242 if (OASE->getColonLoc().isValid())
11243 return false;
11244
11245 // This is an array subscript which has implicit length 1!
11246 ArraySizes.push_back(llvm::APSInt::get(1));
11247 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011248 Expr::EvalResult Result;
11249 if (!Length->EvaluateAsInt(Result, Context))
11250 return false;
11251
11252 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
11253 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011254 return false;
11255
11256 ArraySizes.push_back(ConstantLengthValue);
11257 }
11258 Base = TempOASE->getBase()->IgnoreParenImpCasts();
11259 }
11260
11261 // If we have a single element, we don't need to add the implicit lengths.
11262 if (!SingleElement) {
11263 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
11264 // Has implicit length 1!
11265 ArraySizes.push_back(llvm::APSInt::get(1));
11266 Base = TempASE->getBase()->IgnoreParenImpCasts();
11267 }
11268 }
11269
11270 // This array section can be privatized as a single value or as a constant
11271 // sized array.
11272 return true;
11273}
11274
Alexey Bataeve3727102018-04-18 15:57:46 +000011275static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000011276 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
11277 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11278 SourceLocation ColonLoc, SourceLocation EndLoc,
11279 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011280 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011281 DeclarationName DN = ReductionId.getName();
11282 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011283 BinaryOperatorKind BOK = BO_Comma;
11284
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011285 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011286 // OpenMP [2.14.3.6, reduction clause]
11287 // C
11288 // reduction-identifier is either an identifier or one of the following
11289 // operators: +, -, *, &, |, ^, && and ||
11290 // C++
11291 // reduction-identifier is either an id-expression or one of the following
11292 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000011293 switch (OOK) {
11294 case OO_Plus:
11295 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011296 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011297 break;
11298 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011299 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011300 break;
11301 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011302 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011303 break;
11304 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011305 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011306 break;
11307 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011308 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011309 break;
11310 case OO_AmpAmp:
11311 BOK = BO_LAnd;
11312 break;
11313 case OO_PipePipe:
11314 BOK = BO_LOr;
11315 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011316 case OO_New:
11317 case OO_Delete:
11318 case OO_Array_New:
11319 case OO_Array_Delete:
11320 case OO_Slash:
11321 case OO_Percent:
11322 case OO_Tilde:
11323 case OO_Exclaim:
11324 case OO_Equal:
11325 case OO_Less:
11326 case OO_Greater:
11327 case OO_LessEqual:
11328 case OO_GreaterEqual:
11329 case OO_PlusEqual:
11330 case OO_MinusEqual:
11331 case OO_StarEqual:
11332 case OO_SlashEqual:
11333 case OO_PercentEqual:
11334 case OO_CaretEqual:
11335 case OO_AmpEqual:
11336 case OO_PipeEqual:
11337 case OO_LessLess:
11338 case OO_GreaterGreater:
11339 case OO_LessLessEqual:
11340 case OO_GreaterGreaterEqual:
11341 case OO_EqualEqual:
11342 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000011343 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011344 case OO_PlusPlus:
11345 case OO_MinusMinus:
11346 case OO_Comma:
11347 case OO_ArrowStar:
11348 case OO_Arrow:
11349 case OO_Call:
11350 case OO_Subscript:
11351 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000011352 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011353 case NUM_OVERLOADED_OPERATORS:
11354 llvm_unreachable("Unexpected reduction identifier");
11355 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000011356 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011357 if (II->isStr("max"))
11358 BOK = BO_GT;
11359 else if (II->isStr("min"))
11360 BOK = BO_LT;
11361 }
11362 break;
11363 }
11364 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011365 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000011366 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011367 else
11368 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011369 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011370
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011371 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11372 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000011373 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011374 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000011375 // OpenMP [2.1, C/C++]
11376 // A list item is a variable or array section, subject to the restrictions
11377 // specified in Section 2.4 on page 42 and in each of the sections
11378 // describing clauses and directives for which a list appears.
11379 // OpenMP [2.14.3.3, Restrictions, p.1]
11380 // A variable that is part of another variable (as an array or
11381 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011382 if (!FirstIter && IR != ER)
11383 ++IR;
11384 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011385 SourceLocation ELoc;
11386 SourceRange ERange;
11387 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011388 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000011389 /*AllowArraySection=*/true);
11390 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011391 // Try to find 'declare reduction' corresponding construct before using
11392 // builtin/overloaded operators.
11393 QualType Type = Context.DependentTy;
11394 CXXCastPath BasePath;
11395 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011396 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011397 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011398 Expr *ReductionOp = nullptr;
11399 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011400 (DeclareReductionRef.isUnset() ||
11401 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011402 ReductionOp = DeclareReductionRef.get();
11403 // It will be analyzed later.
11404 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011405 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011406 ValueDecl *D = Res.first;
11407 if (!D)
11408 continue;
11409
Alexey Bataev88202be2017-07-27 13:20:36 +000011410 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000011411 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011412 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11413 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000011414 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000011415 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011416 } else if (OASE) {
11417 QualType BaseType =
11418 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11419 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000011420 Type = ATy->getElementType();
11421 else
11422 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000011423 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011424 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011425 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000011426 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011427 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000011428
Alexey Bataevc5e02582014-06-16 07:08:35 +000011429 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11430 // A variable that appears in a private clause must not have an incomplete
11431 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000011432 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011433 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011434 continue;
11435 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000011436 // A list item that appears in a reduction clause must not be
11437 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011438 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11439 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011440 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000011441
11442 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011443 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11444 // If a list-item is a reference type then it must bind to the same object
11445 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000011446 if (!ASE && !OASE) {
11447 if (VD) {
11448 VarDecl *VDDef = VD->getDefinition();
11449 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11450 DSARefChecker Check(Stack);
11451 if (Check.Visit(VDDef->getInit())) {
11452 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11453 << getOpenMPClauseName(ClauseKind) << ERange;
11454 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11455 continue;
11456 }
Alexey Bataeva1764212015-09-30 09:22:36 +000011457 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000011458 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011459
Alexey Bataevbc529672018-09-28 19:33:14 +000011460 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11461 // in a Construct]
11462 // Variables with the predetermined data-sharing attributes may not be
11463 // listed in data-sharing attributes clauses, except for the cases
11464 // listed below. For these exceptions only, listing a predetermined
11465 // variable in a data-sharing attribute clause is allowed and overrides
11466 // the variable's predetermined data-sharing attributes.
11467 // OpenMP [2.14.3.6, Restrictions, p.3]
11468 // Any number of reduction clauses can be specified on the directive,
11469 // but a list item can appear only once in the reduction clauses for that
11470 // directive.
11471 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11472 if (DVar.CKind == OMPC_reduction) {
11473 S.Diag(ELoc, diag::err_omp_once_referenced)
11474 << getOpenMPClauseName(ClauseKind);
11475 if (DVar.RefExpr)
11476 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
11477 continue;
11478 }
11479 if (DVar.CKind != OMPC_unknown) {
11480 S.Diag(ELoc, diag::err_omp_wrong_dsa)
11481 << getOpenMPClauseName(DVar.CKind)
11482 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000011483 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011484 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000011485 }
Alexey Bataevbc529672018-09-28 19:33:14 +000011486
11487 // OpenMP [2.14.3.6, Restrictions, p.1]
11488 // A list item that appears in a reduction clause of a worksharing
11489 // construct must be shared in the parallel regions to which any of the
11490 // worksharing regions arising from the worksharing construct bind.
11491 if (isOpenMPWorksharingDirective(CurrDir) &&
11492 !isOpenMPParallelDirective(CurrDir) &&
11493 !isOpenMPTeamsDirective(CurrDir)) {
11494 DVar = Stack->getImplicitDSA(D, true);
11495 if (DVar.CKind != OMPC_shared) {
11496 S.Diag(ELoc, diag::err_omp_required_access)
11497 << getOpenMPClauseName(OMPC_reduction)
11498 << getOpenMPClauseName(OMPC_shared);
11499 reportOriginalDsa(S, Stack, D, DVar);
11500 continue;
11501 }
11502 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000011503 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011504
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011505 // Try to find 'declare reduction' corresponding construct before using
11506 // builtin/overloaded operators.
11507 CXXCastPath BasePath;
11508 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011509 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011510 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11511 if (DeclareReductionRef.isInvalid())
11512 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011513 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011514 (DeclareReductionRef.isUnset() ||
11515 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011516 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011517 continue;
11518 }
11519 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
11520 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011521 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011522 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011523 << Type << ReductionIdRange;
11524 continue;
11525 }
11526
11527 // OpenMP [2.14.3.6, reduction clause, Restrictions]
11528 // The type of a list item that appears in a reduction clause must be valid
11529 // for the reduction-identifier. For a max or min reduction in C, the type
11530 // of the list item must be an allowed arithmetic data type: char, int,
11531 // float, double, or _Bool, possibly modified with long, short, signed, or
11532 // unsigned. For a max or min reduction in C++, the type of the list item
11533 // must be an allowed arithmetic data type: char, wchar_t, int, float,
11534 // double, or bool, possibly modified with long, short, signed, or unsigned.
11535 if (DeclareReductionRef.isUnset()) {
11536 if ((BOK == BO_GT || BOK == BO_LT) &&
11537 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011538 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
11539 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000011540 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011541 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011542 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11543 VarDecl::DeclarationOnly;
11544 S.Diag(D->getLocation(),
11545 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011546 << D;
11547 }
11548 continue;
11549 }
11550 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011551 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000011552 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11553 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011554 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011555 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11556 VarDecl::DeclarationOnly;
11557 S.Diag(D->getLocation(),
11558 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011559 << D;
11560 }
11561 continue;
11562 }
11563 }
11564
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011565 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011566 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
11567 D->hasAttrs() ? &D->getAttrs() : nullptr);
11568 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
11569 D->hasAttrs() ? &D->getAttrs() : nullptr);
11570 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011571
11572 // Try if we can determine constant lengths for all array sections and avoid
11573 // the VLA.
11574 bool ConstantLengthOASE = false;
11575 if (OASE) {
11576 bool SingleElement;
11577 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000011578 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011579 Context, OASE, SingleElement, ArraySizes);
11580
11581 // If we don't have a single element, we must emit a constant array type.
11582 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011583 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011584 PrivateTy = Context.getConstantArrayType(
11585 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011586 }
11587 }
11588
11589 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000011590 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000011591 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000011592 if (!Context.getTargetInfo().isVLASupported() &&
11593 S.shouldDiagnoseTargetSupportFromOpenMP()) {
11594 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
11595 S.Diag(ELoc, diag::note_vla_unsupported);
11596 continue;
11597 }
David Majnemer9d168222016-08-05 17:44:54 +000011598 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011599 // Create pseudo array type for private copy. The size for this array will
11600 // be generated during codegen.
11601 // For array subscripts or single variables Private Ty is the same as Type
11602 // (type of the variable or single array element).
11603 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011604 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000011605 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011606 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000011607 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000011608 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011609 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011610 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011611 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000011612 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011613 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
11614 D->hasAttrs() ? &D->getAttrs() : nullptr,
11615 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011616 // Add initializer for private variable.
11617 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011618 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
11619 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011620 if (DeclareReductionRef.isUsable()) {
11621 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
11622 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
11623 if (DRD->getInitializer()) {
11624 Init = DRDRef;
11625 RHSVD->setInit(DRDRef);
11626 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011627 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011628 } else {
11629 switch (BOK) {
11630 case BO_Add:
11631 case BO_Xor:
11632 case BO_Or:
11633 case BO_LOr:
11634 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
11635 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011636 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011637 break;
11638 case BO_Mul:
11639 case BO_LAnd:
11640 if (Type->isScalarType() || Type->isAnyComplexType()) {
11641 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011642 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011643 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011644 break;
11645 case BO_And: {
11646 // '&' reduction op - initializer is '~0'.
11647 QualType OrigType = Type;
11648 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
11649 Type = ComplexTy->getElementType();
11650 if (Type->isRealFloatingType()) {
11651 llvm::APFloat InitValue =
11652 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
11653 /*isIEEE=*/true);
11654 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11655 Type, ELoc);
11656 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011657 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011658 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11659 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11660 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11661 }
11662 if (Init && OrigType->isAnyComplexType()) {
11663 // Init = 0xFFFF + 0xFFFFi;
11664 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011665 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011666 }
11667 Type = OrigType;
11668 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011669 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011670 case BO_LT:
11671 case BO_GT: {
11672 // 'min' reduction op - initializer is 'Largest representable number in
11673 // the reduction list item type'.
11674 // 'max' reduction op - initializer is 'Least representable number in
11675 // the reduction list item type'.
11676 if (Type->isIntegerType() || Type->isPointerType()) {
11677 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000011678 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011679 QualType IntTy =
11680 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
11681 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011682 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
11683 : llvm::APInt::getMinValue(Size)
11684 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
11685 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011686 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11687 if (Type->isPointerType()) {
11688 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000011689 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000011690 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011691 if (CastExpr.isInvalid())
11692 continue;
11693 Init = CastExpr.get();
11694 }
11695 } else if (Type->isRealFloatingType()) {
11696 llvm::APFloat InitValue = llvm::APFloat::getLargest(
11697 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
11698 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11699 Type, ELoc);
11700 }
11701 break;
11702 }
11703 case BO_PtrMemD:
11704 case BO_PtrMemI:
11705 case BO_MulAssign:
11706 case BO_Div:
11707 case BO_Rem:
11708 case BO_Sub:
11709 case BO_Shl:
11710 case BO_Shr:
11711 case BO_LE:
11712 case BO_GE:
11713 case BO_EQ:
11714 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000011715 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011716 case BO_AndAssign:
11717 case BO_XorAssign:
11718 case BO_OrAssign:
11719 case BO_Assign:
11720 case BO_AddAssign:
11721 case BO_SubAssign:
11722 case BO_DivAssign:
11723 case BO_RemAssign:
11724 case BO_ShlAssign:
11725 case BO_ShrAssign:
11726 case BO_Comma:
11727 llvm_unreachable("Unexpected reduction operation");
11728 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011729 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011730 if (Init && DeclareReductionRef.isUnset())
11731 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
11732 else if (!Init)
11733 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011734 if (RHSVD->isInvalidDecl())
11735 continue;
11736 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011737 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
11738 << Type << ReductionIdRange;
11739 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11740 VarDecl::DeclarationOnly;
11741 S.Diag(D->getLocation(),
11742 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000011743 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011744 continue;
11745 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011746 // Store initializer for single element in private copy. Will be used during
11747 // codegen.
11748 PrivateVD->setInit(RHSVD->getInit());
11749 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000011750 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011751 ExprResult ReductionOp;
11752 if (DeclareReductionRef.isUsable()) {
11753 QualType RedTy = DeclareReductionRef.get()->getType();
11754 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011755 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
11756 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011757 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011758 LHS = S.DefaultLvalueConversion(LHS.get());
11759 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011760 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11761 CK_UncheckedDerivedToBase, LHS.get(),
11762 &BasePath, LHS.get()->getValueKind());
11763 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11764 CK_UncheckedDerivedToBase, RHS.get(),
11765 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011766 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011767 FunctionProtoType::ExtProtoInfo EPI;
11768 QualType Params[] = {PtrRedTy, PtrRedTy};
11769 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
11770 auto *OVE = new (Context) OpaqueValueExpr(
11771 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011772 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011773 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000011774 ReductionOp =
11775 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011776 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011777 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011778 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011779 if (ReductionOp.isUsable()) {
11780 if (BOK != BO_LT && BOK != BO_GT) {
11781 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011782 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011783 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011784 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000011785 auto *ConditionalOp = new (Context)
11786 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
11787 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011788 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011789 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011790 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011791 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011792 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011793 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
11794 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011795 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011796 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011797 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011798 }
11799
Alexey Bataevfa312f32017-07-21 18:48:21 +000011800 // OpenMP [2.15.4.6, Restrictions, p.2]
11801 // A list item that appears in an in_reduction clause of a task construct
11802 // must appear in a task_reduction clause of a construct associated with a
11803 // taskgroup region that includes the participating task in its taskgroup
11804 // set. The construct associated with the innermost region that meets this
11805 // condition must specify the same reduction-identifier as the in_reduction
11806 // clause.
11807 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000011808 SourceRange ParentSR;
11809 BinaryOperatorKind ParentBOK;
11810 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000011811 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000011812 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011813 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
11814 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011815 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011816 Stack->getTopMostTaskgroupReductionData(
11817 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011818 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
11819 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
11820 if (!IsParentBOK && !IsParentReductionOp) {
11821 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
11822 continue;
11823 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000011824 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
11825 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
11826 IsParentReductionOp) {
11827 bool EmitError = true;
11828 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
11829 llvm::FoldingSetNodeID RedId, ParentRedId;
11830 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
11831 DeclareReductionRef.get()->Profile(RedId, Context,
11832 /*Canonical=*/true);
11833 EmitError = RedId != ParentRedId;
11834 }
11835 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011836 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000011837 diag::err_omp_reduction_identifier_mismatch)
11838 << ReductionIdRange << RefExpr->getSourceRange();
11839 S.Diag(ParentSR.getBegin(),
11840 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000011841 << ParentSR
11842 << (IsParentBOK ? ParentBOKDSA.RefExpr
11843 : ParentReductionOpDSA.RefExpr)
11844 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000011845 continue;
11846 }
11847 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011848 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
11849 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000011850 }
11851
Alexey Bataev60da77e2016-02-29 05:54:20 +000011852 DeclRefExpr *Ref = nullptr;
11853 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011854 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011855 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011856 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000011857 VarsExpr =
11858 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
11859 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000011860 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011861 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011862 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011863 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011864 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011865 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011866 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011867 if (!RefRes.isUsable())
11868 continue;
11869 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011870 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11871 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011872 if (!PostUpdateRes.isUsable())
11873 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011874 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
11875 Stack->getCurrentDirective() == OMPD_taskgroup) {
11876 S.Diag(RefExpr->getExprLoc(),
11877 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000011878 << RefExpr->getSourceRange();
11879 continue;
11880 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011881 RD.ExprPostUpdates.emplace_back(
11882 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000011883 }
11884 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011885 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000011886 // All reduction items are still marked as reduction (to do not increase
11887 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011888 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011889 if (CurrDir == OMPD_taskgroup) {
11890 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011891 Stack->addTaskgroupReductionData(D, ReductionIdRange,
11892 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000011893 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011894 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011895 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011896 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
11897 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011898 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011899 return RD.Vars.empty();
11900}
Alexey Bataevc5e02582014-06-16 07:08:35 +000011901
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011902OMPClause *Sema::ActOnOpenMPReductionClause(
11903 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11904 SourceLocation ColonLoc, SourceLocation EndLoc,
11905 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11906 ArrayRef<Expr *> UnresolvedReductions) {
11907 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011908 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011909 StartLoc, LParenLoc, ColonLoc, EndLoc,
11910 ReductionIdScopeSpec, ReductionId,
11911 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011912 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000011913
Alexey Bataevc5e02582014-06-16 07:08:35 +000011914 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011915 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11916 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11917 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11918 buildPreInits(Context, RD.ExprCaptures),
11919 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000011920}
11921
Alexey Bataev169d96a2017-07-18 20:17:46 +000011922OMPClause *Sema::ActOnOpenMPTaskReductionClause(
11923 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11924 SourceLocation ColonLoc, SourceLocation EndLoc,
11925 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11926 ArrayRef<Expr *> UnresolvedReductions) {
11927 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011928 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
11929 StartLoc, LParenLoc, ColonLoc, EndLoc,
11930 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011931 UnresolvedReductions, RD))
11932 return nullptr;
11933
11934 return OMPTaskReductionClause::Create(
11935 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11936 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11937 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11938 buildPreInits(Context, RD.ExprCaptures),
11939 buildPostUpdate(*this, RD.ExprPostUpdates));
11940}
11941
Alexey Bataevfa312f32017-07-21 18:48:21 +000011942OMPClause *Sema::ActOnOpenMPInReductionClause(
11943 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11944 SourceLocation ColonLoc, SourceLocation EndLoc,
11945 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11946 ArrayRef<Expr *> UnresolvedReductions) {
11947 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011948 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011949 StartLoc, LParenLoc, ColonLoc, EndLoc,
11950 ReductionIdScopeSpec, ReductionId,
11951 UnresolvedReductions, RD))
11952 return nullptr;
11953
11954 return OMPInReductionClause::Create(
11955 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11956 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000011957 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011958 buildPreInits(Context, RD.ExprCaptures),
11959 buildPostUpdate(*this, RD.ExprPostUpdates));
11960}
11961
Alexey Bataevecba70f2016-04-12 11:02:11 +000011962bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11963 SourceLocation LinLoc) {
11964 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
11965 LinKind == OMPC_LINEAR_unknown) {
11966 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
11967 return true;
11968 }
11969 return false;
11970}
11971
Alexey Bataeve3727102018-04-18 15:57:46 +000011972bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000011973 OpenMPLinearClauseKind LinKind,
11974 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011975 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000011976 // A variable must not have an incomplete type or a reference type.
11977 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
11978 return true;
11979 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
11980 !Type->isReferenceType()) {
11981 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
11982 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
11983 return true;
11984 }
11985 Type = Type.getNonReferenceType();
11986
Joel E. Dennybae586f2019-01-04 22:12:13 +000011987 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11988 // A variable that is privatized must not have a const-qualified type
11989 // unless it is of class type with a mutable member. This restriction does
11990 // not apply to the firstprivate clause.
11991 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000011992 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011993
11994 // A list item must be of integral or pointer type.
11995 Type = Type.getUnqualifiedType().getCanonicalType();
11996 const auto *Ty = Type.getTypePtrOrNull();
11997 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
11998 !Ty->isPointerType())) {
11999 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
12000 if (D) {
12001 bool IsDecl =
12002 !VD ||
12003 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12004 Diag(D->getLocation(),
12005 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12006 << D;
12007 }
12008 return true;
12009 }
12010 return false;
12011}
12012
Alexey Bataev182227b2015-08-20 10:54:39 +000012013OMPClause *Sema::ActOnOpenMPLinearClause(
12014 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
12015 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
12016 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012017 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012018 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000012019 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000012020 SmallVector<Decl *, 4> ExprCaptures;
12021 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012022 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000012023 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000012024 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012025 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012026 SourceLocation ELoc;
12027 SourceRange ERange;
12028 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012029 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012030 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012031 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012032 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012033 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000012034 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000012035 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012036 ValueDecl *D = Res.first;
12037 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000012038 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000012039
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012040 QualType Type = D->getType();
12041 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000012042
12043 // OpenMP [2.14.3.7, linear clause]
12044 // A list-item cannot appear in more than one linear clause.
12045 // A list-item that appears in a linear clause cannot appear in any
12046 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012047 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000012048 if (DVar.RefExpr) {
12049 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12050 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000012051 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000012052 continue;
12053 }
12054
Alexey Bataevecba70f2016-04-12 11:02:11 +000012055 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000012056 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012057 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000012058
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012059 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000012060 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012061 buildVarDecl(*this, ELoc, Type, D->getName(),
12062 D->hasAttrs() ? &D->getAttrs() : nullptr,
12063 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012064 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012065 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012066 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012067 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012068 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012069 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012070 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012071 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012072 ExprCaptures.push_back(Ref->getDecl());
12073 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
12074 ExprResult RefRes = DefaultLvalueConversion(Ref);
12075 if (!RefRes.isUsable())
12076 continue;
12077 ExprResult PostUpdateRes =
12078 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
12079 SimpleRefExpr, RefRes.get());
12080 if (!PostUpdateRes.isUsable())
12081 continue;
12082 ExprPostUpdates.push_back(
12083 IgnoredValueConversions(PostUpdateRes.get()).get());
12084 }
12085 }
12086 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012087 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012088 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012089 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012090 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012091 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012092 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012093 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012094
12095 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012096 Vars.push_back((VD || CurContext->isDependentContext())
12097 ? RefExpr->IgnoreParens()
12098 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012099 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000012100 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000012101 }
12102
12103 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012104 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012105
12106 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000012107 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012108 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
12109 !Step->isInstantiationDependent() &&
12110 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012111 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000012112 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000012113 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012114 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012115 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000012116
Alexander Musman3276a272015-03-21 10:12:56 +000012117 // Build var to save the step value.
12118 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012119 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000012120 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012121 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012122 ExprResult CalcStep =
12123 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012124 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012125
Alexander Musman8dba6642014-04-22 13:09:42 +000012126 // Warn about zero linear step (it would be probably better specified as
12127 // making corresponding variables 'const').
12128 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000012129 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
12130 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000012131 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
12132 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000012133 if (!IsConstant && CalcStep.isUsable()) {
12134 // Calculate the step beforehand instead of doing this on each iteration.
12135 // (This is not used if the number of iterations may be kfold-ed).
12136 CalcStepExpr = CalcStep.get();
12137 }
Alexander Musman8dba6642014-04-22 13:09:42 +000012138 }
12139
Alexey Bataev182227b2015-08-20 10:54:39 +000012140 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
12141 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012142 StepExpr, CalcStepExpr,
12143 buildPreInits(Context, ExprCaptures),
12144 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000012145}
12146
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012147static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
12148 Expr *NumIterations, Sema &SemaRef,
12149 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000012150 // Walk the vars and build update/final expressions for the CodeGen.
12151 SmallVector<Expr *, 8> Updates;
12152 SmallVector<Expr *, 8> Finals;
12153 Expr *Step = Clause.getStep();
12154 Expr *CalcStep = Clause.getCalcStep();
12155 // OpenMP [2.14.3.7, linear clause]
12156 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000012157 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000012158 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012159 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000012160 Step = cast<BinaryOperator>(CalcStep)->getLHS();
12161 bool HasErrors = false;
12162 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012163 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000012164 OpenMPLinearClauseKind LinKind = Clause.getModifier();
12165 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012166 SourceLocation ELoc;
12167 SourceRange ERange;
12168 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012169 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012170 ValueDecl *D = Res.first;
12171 if (Res.second || !D) {
12172 Updates.push_back(nullptr);
12173 Finals.push_back(nullptr);
12174 HasErrors = true;
12175 continue;
12176 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012177 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000012178 // OpenMP [2.15.11, distribute simd Construct]
12179 // A list item may not appear in a linear clause, unless it is the loop
12180 // iteration variable.
12181 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
12182 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
12183 SemaRef.Diag(ELoc,
12184 diag::err_omp_linear_distribute_var_non_loop_iteration);
12185 Updates.push_back(nullptr);
12186 Finals.push_back(nullptr);
12187 HasErrors = true;
12188 continue;
12189 }
Alexander Musman3276a272015-03-21 10:12:56 +000012190 Expr *InitExpr = *CurInit;
12191
12192 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000012193 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012194 Expr *CapturedRef;
12195 if (LinKind == OMPC_LINEAR_uval)
12196 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
12197 else
12198 CapturedRef =
12199 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
12200 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
12201 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000012202
12203 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012204 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000012205 if (!Info.first)
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012206 Update =
Alexey Bataeve3727102018-04-18 15:57:46 +000012207 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012208 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012209 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012210 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012211 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012212 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012213
12214 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012215 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000012216 if (!Info.first)
12217 Final =
12218 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
12219 InitExpr, NumIterations, Step, /*Subtract=*/false);
12220 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012221 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012222 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012223 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012224
Alexander Musman3276a272015-03-21 10:12:56 +000012225 if (!Update.isUsable() || !Final.isUsable()) {
12226 Updates.push_back(nullptr);
12227 Finals.push_back(nullptr);
12228 HasErrors = true;
12229 } else {
12230 Updates.push_back(Update.get());
12231 Finals.push_back(Final.get());
12232 }
Richard Trieucc3949d2016-02-18 22:34:54 +000012233 ++CurInit;
12234 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000012235 }
12236 Clause.setUpdates(Updates);
12237 Clause.setFinals(Finals);
12238 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000012239}
12240
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012241OMPClause *Sema::ActOnOpenMPAlignedClause(
12242 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
12243 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012244 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012245 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000012246 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12247 SourceLocation ELoc;
12248 SourceRange ERange;
12249 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012250 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000012251 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012252 // It will be analyzed later.
12253 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012254 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000012255 ValueDecl *D = Res.first;
12256 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012257 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012258
Alexey Bataev1efd1662016-03-29 10:59:56 +000012259 QualType QType = D->getType();
12260 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012261
12262 // OpenMP [2.8.1, simd construct, Restrictions]
12263 // The type of list items appearing in the aligned clause must be
12264 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012265 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012266 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000012267 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012268 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012269 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012270 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000012271 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012272 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000012273 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012274 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012275 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012276 continue;
12277 }
12278
12279 // OpenMP [2.8.1, simd construct, Restrictions]
12280 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012281 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000012282 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012283 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
12284 << getOpenMPClauseName(OMPC_aligned);
12285 continue;
12286 }
12287
Alexey Bataev1efd1662016-03-29 10:59:56 +000012288 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012289 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000012290 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12291 Vars.push_back(DefaultFunctionArrayConversion(
12292 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
12293 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012294 }
12295
12296 // OpenMP [2.8.1, simd construct, Description]
12297 // The parameter of the aligned clause, alignment, must be a constant
12298 // positive integer expression.
12299 // If no optional parameter is specified, implementation-defined default
12300 // alignments for SIMD instructions on the target platforms are assumed.
12301 if (Alignment != nullptr) {
12302 ExprResult AlignResult =
12303 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
12304 if (AlignResult.isInvalid())
12305 return nullptr;
12306 Alignment = AlignResult.get();
12307 }
12308 if (Vars.empty())
12309 return nullptr;
12310
12311 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
12312 EndLoc, Vars, Alignment);
12313}
12314
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012315OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12316 SourceLocation StartLoc,
12317 SourceLocation LParenLoc,
12318 SourceLocation EndLoc) {
12319 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012320 SmallVector<Expr *, 8> SrcExprs;
12321 SmallVector<Expr *, 8> DstExprs;
12322 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012323 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012324 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
12325 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012326 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012327 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012328 SrcExprs.push_back(nullptr);
12329 DstExprs.push_back(nullptr);
12330 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012331 continue;
12332 }
12333
Alexey Bataeved09d242014-05-28 05:53:51 +000012334 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012335 // OpenMP [2.1, C/C++]
12336 // A list item is a variable name.
12337 // OpenMP [2.14.4.1, Restrictions, p.1]
12338 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000012339 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012340 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012341 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
12342 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012343 continue;
12344 }
12345
12346 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000012347 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012348
12349 QualType Type = VD->getType();
12350 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
12351 // It will be analyzed later.
12352 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012353 SrcExprs.push_back(nullptr);
12354 DstExprs.push_back(nullptr);
12355 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012356 continue;
12357 }
12358
12359 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
12360 // A list item that appears in a copyin clause must be threadprivate.
12361 if (!DSAStack->isThreadPrivate(VD)) {
12362 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000012363 << getOpenMPClauseName(OMPC_copyin)
12364 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012365 continue;
12366 }
12367
12368 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12369 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000012370 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012371 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012372 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12373 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012374 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012375 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012376 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012377 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000012378 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012379 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012380 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012381 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012382 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012383 // For arrays generate assignment operation for single element and replace
12384 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012385 ExprResult AssignmentOp =
12386 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12387 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012388 if (AssignmentOp.isInvalid())
12389 continue;
12390 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012391 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012392 if (AssignmentOp.isInvalid())
12393 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012394
12395 DSAStack->addDSA(VD, DE, OMPC_copyin);
12396 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012397 SrcExprs.push_back(PseudoSrcExpr);
12398 DstExprs.push_back(PseudoDstExpr);
12399 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012400 }
12401
Alexey Bataeved09d242014-05-28 05:53:51 +000012402 if (Vars.empty())
12403 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012404
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012405 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12406 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012407}
12408
Alexey Bataevbae9a792014-06-27 10:37:06 +000012409OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12410 SourceLocation StartLoc,
12411 SourceLocation LParenLoc,
12412 SourceLocation EndLoc) {
12413 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000012414 SmallVector<Expr *, 8> SrcExprs;
12415 SmallVector<Expr *, 8> DstExprs;
12416 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012417 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012418 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12419 SourceLocation ELoc;
12420 SourceRange ERange;
12421 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012422 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000012423 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012424 // It will be analyzed later.
12425 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012426 SrcExprs.push_back(nullptr);
12427 DstExprs.push_back(nullptr);
12428 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012429 }
Alexey Bataeve122da12016-03-17 10:50:17 +000012430 ValueDecl *D = Res.first;
12431 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000012432 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012433
Alexey Bataeve122da12016-03-17 10:50:17 +000012434 QualType Type = D->getType();
12435 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012436
12437 // OpenMP [2.14.4.2, Restrictions, p.2]
12438 // A list item that appears in a copyprivate clause may not appear in a
12439 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000012440 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012441 DSAStackTy::DSAVarData DVar =
12442 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012443 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12444 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012445 Diag(ELoc, diag::err_omp_wrong_dsa)
12446 << getOpenMPClauseName(DVar.CKind)
12447 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012448 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012449 continue;
12450 }
12451
12452 // OpenMP [2.11.4.2, Restrictions, p.1]
12453 // All list items that appear in a copyprivate clause must be either
12454 // threadprivate or private in the enclosing context.
12455 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012456 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012457 if (DVar.CKind == OMPC_shared) {
12458 Diag(ELoc, diag::err_omp_required_access)
12459 << getOpenMPClauseName(OMPC_copyprivate)
12460 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000012461 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012462 continue;
12463 }
12464 }
12465 }
12466
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012467 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012468 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012469 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012470 << getOpenMPClauseName(OMPC_copyprivate) << Type
12471 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012472 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000012473 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012474 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000012475 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012476 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000012477 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012478 continue;
12479 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012480
Alexey Bataevbae9a792014-06-27 10:37:06 +000012481 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12482 // A variable of class type (or array thereof) that appears in a
12483 // copyin clause requires an accessible, unambiguous copy assignment
12484 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012485 Type = Context.getBaseElementType(Type.getNonReferenceType())
12486 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012487 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012488 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000012489 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012490 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
12491 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012492 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000012493 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012494 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
12495 ExprResult AssignmentOp = BuildBinOp(
12496 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012497 if (AssignmentOp.isInvalid())
12498 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012499 AssignmentOp =
12500 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012501 if (AssignmentOp.isInvalid())
12502 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012503
12504 // No need to mark vars as copyprivate, they are already threadprivate or
12505 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000012506 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000012507 Vars.push_back(
12508 VD ? RefExpr->IgnoreParens()
12509 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000012510 SrcExprs.push_back(PseudoSrcExpr);
12511 DstExprs.push_back(PseudoDstExpr);
12512 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000012513 }
12514
12515 if (Vars.empty())
12516 return nullptr;
12517
Alexey Bataeva63048e2015-03-23 06:18:07 +000012518 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12519 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012520}
12521
Alexey Bataev6125da92014-07-21 11:26:11 +000012522OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12523 SourceLocation StartLoc,
12524 SourceLocation LParenLoc,
12525 SourceLocation EndLoc) {
12526 if (VarList.empty())
12527 return nullptr;
12528
12529 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
12530}
Alexey Bataevdea47612014-07-23 07:46:59 +000012531
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012532OMPClause *
12533Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12534 SourceLocation DepLoc, SourceLocation ColonLoc,
12535 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12536 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012537 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012538 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012539 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012540 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000012541 return nullptr;
12542 }
12543 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012544 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12545 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000012546 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012547 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012548 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12549 /*Last=*/OMPC_DEPEND_unknown, Except)
12550 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012551 return nullptr;
12552 }
12553 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000012554 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012555 llvm::APSInt DepCounter(/*BitWidth=*/32);
12556 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000012557 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12558 if (const Expr *OrderedCountExpr =
12559 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012560 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
12561 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012562 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012563 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012564 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000012565 assert(RefExpr && "NULL expr in OpenMP shared clause.");
12566 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12567 // It will be analyzed later.
12568 Vars.push_back(RefExpr);
12569 continue;
12570 }
12571
12572 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000012573 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000012574 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000012575 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012576 DepCounter >= TotalDepCount) {
12577 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
12578 continue;
12579 }
12580 ++DepCounter;
12581 // OpenMP [2.13.9, Summary]
12582 // depend(dependence-type : vec), where dependence-type is:
12583 // 'sink' and where vec is the iteration vector, which has the form:
12584 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
12585 // where n is the value specified by the ordered clause in the loop
12586 // directive, xi denotes the loop iteration variable of the i-th nested
12587 // loop associated with the loop directive, and di is a constant
12588 // non-negative integer.
12589 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012590 // It will be analyzed later.
12591 Vars.push_back(RefExpr);
12592 continue;
12593 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012594 SimpleExpr = SimpleExpr->IgnoreImplicit();
12595 OverloadedOperatorKind OOK = OO_None;
12596 SourceLocation OOLoc;
12597 Expr *LHS = SimpleExpr;
12598 Expr *RHS = nullptr;
12599 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
12600 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
12601 OOLoc = BO->getOperatorLoc();
12602 LHS = BO->getLHS()->IgnoreParenImpCasts();
12603 RHS = BO->getRHS()->IgnoreParenImpCasts();
12604 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
12605 OOK = OCE->getOperator();
12606 OOLoc = OCE->getOperatorLoc();
12607 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12608 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
12609 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
12610 OOK = MCE->getMethodDecl()
12611 ->getNameInfo()
12612 .getName()
12613 .getCXXOverloadedOperator();
12614 OOLoc = MCE->getCallee()->getExprLoc();
12615 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
12616 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012617 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012618 SourceLocation ELoc;
12619 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000012620 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012621 if (Res.second) {
12622 // It will be analyzed later.
12623 Vars.push_back(RefExpr);
12624 }
12625 ValueDecl *D = Res.first;
12626 if (!D)
12627 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012628
Alexey Bataev17daedf2018-02-15 22:42:57 +000012629 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
12630 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
12631 continue;
12632 }
12633 if (RHS) {
12634 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
12635 RHS, OMPC_depend, /*StrictlyPositive=*/false);
12636 if (RHSRes.isInvalid())
12637 continue;
12638 }
12639 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012640 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012641 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012642 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000012643 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000012644 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000012645 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
12646 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000012647 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000012648 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000012649 continue;
12650 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012651 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012652 } else {
12653 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12654 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12655 (ASE &&
12656 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12657 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12658 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12659 << RefExpr->getSourceRange();
12660 continue;
12661 }
12662 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12663 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12664 ExprResult Res =
12665 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12666 getDiagnostics().setSuppressAllDiagnostics(Suppress);
12667 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12668 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12669 << RefExpr->getSourceRange();
12670 continue;
12671 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012672 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012673 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012674 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012675
12676 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
12677 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012678 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012679 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
12680 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
12681 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
12682 }
12683 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
12684 Vars.empty())
12685 return nullptr;
12686
Alexey Bataev8b427062016-05-25 12:36:08 +000012687 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000012688 DepKind, DepLoc, ColonLoc, Vars,
12689 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000012690 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
12691 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000012692 DSAStack->addDoacrossDependClause(C, OpsOffs);
12693 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012694}
Michael Wonge710d542015-08-07 16:16:36 +000012695
12696OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
12697 SourceLocation LParenLoc,
12698 SourceLocation EndLoc) {
12699 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012700 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000012701
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012702 // OpenMP [2.9.1, Restrictions]
12703 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000012704 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000012705 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012706 return nullptr;
12707
Alexey Bataev931e19b2017-10-02 16:32:39 +000012708 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012709 OpenMPDirectiveKind CaptureRegion =
12710 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
12711 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012712 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012713 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012714 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12715 HelperValStmt = buildPreInits(Context, Captures);
12716 }
12717
Alexey Bataev8451efa2018-01-15 19:06:12 +000012718 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
12719 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000012720}
Kelvin Li0bff7af2015-11-23 05:32:03 +000012721
Alexey Bataeve3727102018-04-18 15:57:46 +000012722static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000012723 DSAStackTy *Stack, QualType QTy,
12724 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000012725 NamedDecl *ND;
12726 if (QTy->isIncompleteType(&ND)) {
12727 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
12728 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012729 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000012730 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
12731 !QTy.isTrivialType(SemaRef.Context))
12732 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012733 return true;
12734}
12735
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012736/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012737/// (array section or array subscript) does NOT specify the whole size of the
12738/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012739static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012740 const Expr *E,
12741 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012742 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012743
12744 // If this is an array subscript, it refers to the whole size if the size of
12745 // the dimension is constant and equals 1. Also, an array section assumes the
12746 // format of an array subscript if no colon is used.
12747 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012748 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012749 return ATy->getSize().getSExtValue() != 1;
12750 // Size can't be evaluated statically.
12751 return false;
12752 }
12753
12754 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012755 const Expr *LowerBound = OASE->getLowerBound();
12756 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012757
12758 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000012759 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012760 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000012761 Expr::EvalResult Result;
12762 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012763 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000012764
12765 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012766 if (ConstLowerBound.getSExtValue())
12767 return true;
12768 }
12769
12770 // If we don't have a length we covering the whole dimension.
12771 if (!Length)
12772 return false;
12773
12774 // If the base is a pointer, we don't have a way to get the size of the
12775 // pointee.
12776 if (BaseQTy->isPointerType())
12777 return false;
12778
12779 // We can only check if the length is the same as the size of the dimension
12780 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000012781 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012782 if (!CATy)
12783 return false;
12784
Fangrui Song407659a2018-11-30 23:41:18 +000012785 Expr::EvalResult Result;
12786 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012787 return false; // Can't get the integer value as a constant.
12788
Fangrui Song407659a2018-11-30 23:41:18 +000012789 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012790 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
12791}
12792
12793// Return true if it can be proven that the provided array expression (array
12794// section or array subscript) does NOT specify a single element of the array
12795// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012796static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000012797 const Expr *E,
12798 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012799 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012800
12801 // An array subscript always refer to a single element. Also, an array section
12802 // assumes the format of an array subscript if no colon is used.
12803 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
12804 return false;
12805
12806 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012807 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012808
12809 // If we don't have a length we have to check if the array has unitary size
12810 // for this dimension. Also, we should always expect a length if the base type
12811 // is pointer.
12812 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012813 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012814 return ATy->getSize().getSExtValue() != 1;
12815 // We cannot assume anything.
12816 return false;
12817 }
12818
12819 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000012820 Expr::EvalResult Result;
12821 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012822 return false; // Can't get the integer value as a constant.
12823
Fangrui Song407659a2018-11-30 23:41:18 +000012824 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012825 return ConstLength.getSExtValue() != 1;
12826}
12827
Samuel Antao661c0902016-05-26 17:39:58 +000012828// Return the expression of the base of the mappable expression or null if it
12829// cannot be determined and do all the necessary checks to see if the expression
12830// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000012831// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000012832static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000012833 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000012834 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012835 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012836 SourceLocation ELoc = E->getExprLoc();
12837 SourceRange ERange = E->getSourceRange();
12838
12839 // The base of elements of list in a map clause have to be either:
12840 // - a reference to variable or field.
12841 // - a member expression.
12842 // - an array expression.
12843 //
12844 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
12845 // reference to 'r'.
12846 //
12847 // If we have:
12848 //
12849 // struct SS {
12850 // Bla S;
12851 // foo() {
12852 // #pragma omp target map (S.Arr[:12]);
12853 // }
12854 // }
12855 //
12856 // We want to retrieve the member expression 'this->S';
12857
Alexey Bataeve3727102018-04-18 15:57:46 +000012858 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012859
Samuel Antao5de996e2016-01-22 20:21:36 +000012860 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
12861 // If a list item is an array section, it must specify contiguous storage.
12862 //
12863 // For this restriction it is sufficient that we make sure only references
12864 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012865 // exist except in the rightmost expression (unless they cover the whole
12866 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000012867 //
12868 // r.ArrS[3:5].Arr[6:7]
12869 //
12870 // r.ArrS[3:5].x
12871 //
12872 // but these would be valid:
12873 // r.ArrS[3].Arr[6:7]
12874 //
12875 // r.ArrS[3].x
12876
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012877 bool AllowUnitySizeArraySection = true;
12878 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012879
Dmitry Polukhin644a9252016-03-11 07:58:34 +000012880 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012881 E = E->IgnoreParenImpCasts();
12882
12883 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
12884 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000012885 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012886
12887 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012888
12889 // If we got a reference to a declaration, we should not expect any array
12890 // section before that.
12891 AllowUnitySizeArraySection = false;
12892 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012893
12894 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012895 CurComponents.emplace_back(CurE, CurE->getDecl());
12896 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012897 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000012898
12899 if (isa<CXXThisExpr>(BaseE))
12900 // We found a base expression: this->Val.
12901 RelevantExpr = CurE;
12902 else
12903 E = BaseE;
12904
12905 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012906 if (!NoDiagnose) {
12907 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
12908 << CurE->getSourceRange();
12909 return nullptr;
12910 }
12911 if (RelevantExpr)
12912 return nullptr;
12913 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012914 }
12915
12916 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
12917
12918 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
12919 // A bit-field cannot appear in a map clause.
12920 //
12921 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012922 if (!NoDiagnose) {
12923 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
12924 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
12925 return nullptr;
12926 }
12927 if (RelevantExpr)
12928 return nullptr;
12929 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012930 }
12931
12932 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12933 // If the type of a list item is a reference to a type T then the type
12934 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012935 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012936
12937 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
12938 // A list item cannot be a variable that is a member of a structure with
12939 // a union type.
12940 //
Alexey Bataeve3727102018-04-18 15:57:46 +000012941 if (CurType->isUnionType()) {
12942 if (!NoDiagnose) {
12943 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
12944 << CurE->getSourceRange();
12945 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012946 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012947 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012948 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012949
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012950 // If we got a member expression, we should not expect any array section
12951 // before that:
12952 //
12953 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
12954 // If a list item is an element of a structure, only the rightmost symbol
12955 // of the variable reference can be an array section.
12956 //
12957 AllowUnitySizeArraySection = false;
12958 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012959
12960 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012961 CurComponents.emplace_back(CurE, FD);
12962 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012963 E = CurE->getBase()->IgnoreParenImpCasts();
12964
12965 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012966 if (!NoDiagnose) {
12967 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12968 << 0 << CurE->getSourceRange();
12969 return nullptr;
12970 }
12971 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012972 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012973
12974 // If we got an array subscript that express the whole dimension we
12975 // can have any array expressions before. If it only expressing part of
12976 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000012977 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012978 E->getType()))
12979 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012980
Patrick Lystere13b1e32019-01-02 19:28:48 +000012981 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12982 Expr::EvalResult Result;
12983 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
12984 if (!Result.Val.getInt().isNullValue()) {
12985 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12986 diag::err_omp_invalid_map_this_expr);
12987 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12988 diag::note_omp_invalid_subscript_on_this_ptr_map);
12989 }
12990 }
12991 RelevantExpr = TE;
12992 }
12993
Samuel Antao90927002016-04-26 14:54:23 +000012994 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012995 CurComponents.emplace_back(CurE, nullptr);
12996 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012997 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000012998 E = CurE->getBase()->IgnoreParenImpCasts();
12999
Alexey Bataev27041fa2017-12-05 15:22:49 +000013000 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013001 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13002
Samuel Antao5de996e2016-01-22 20:21:36 +000013003 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13004 // If the type of a list item is a reference to a type T then the type
13005 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000013006 if (CurType->isReferenceType())
13007 CurType = CurType->getPointeeType();
13008
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013009 bool IsPointer = CurType->isAnyPointerType();
13010
13011 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013012 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13013 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013014 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013015 }
13016
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013017 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000013018 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013019 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000013020 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013021
Samuel Antaodab51bb2016-07-18 23:22:11 +000013022 if (AllowWholeSizeArraySection) {
13023 // Any array section is currently allowed. Allowing a whole size array
13024 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013025 //
13026 // If this array section refers to the whole dimension we can still
13027 // accept other array sections before this one, except if the base is a
13028 // pointer. Otherwise, only unitary sections are accepted.
13029 if (NotWhole || IsPointer)
13030 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000013031 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013032 // A unity or whole array section is not allowed and that is not
13033 // compatible with the properties of the current array section.
13034 SemaRef.Diag(
13035 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
13036 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013037 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013038 }
Samuel Antao90927002016-04-26 14:54:23 +000013039
Patrick Lystere13b1e32019-01-02 19:28:48 +000013040 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13041 Expr::EvalResult ResultR;
13042 Expr::EvalResult ResultL;
13043 if (CurE->getLength()->EvaluateAsInt(ResultR,
13044 SemaRef.getASTContext())) {
13045 if (!ResultR.Val.getInt().isOneValue()) {
13046 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13047 diag::err_omp_invalid_map_this_expr);
13048 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13049 diag::note_omp_invalid_length_on_this_ptr_mapping);
13050 }
13051 }
13052 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
13053 ResultL, SemaRef.getASTContext())) {
13054 if (!ResultL.Val.getInt().isNullValue()) {
13055 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13056 diag::err_omp_invalid_map_this_expr);
13057 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13058 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
13059 }
13060 }
13061 RelevantExpr = TE;
13062 }
13063
Samuel Antao90927002016-04-26 14:54:23 +000013064 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013065 CurComponents.emplace_back(CurE, nullptr);
13066 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013067 if (!NoDiagnose) {
13068 // If nothing else worked, this is not a valid map clause expression.
13069 SemaRef.Diag(
13070 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
13071 << ERange;
13072 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000013073 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013074 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013075 }
13076
13077 return RelevantExpr;
13078}
13079
13080// Return true if expression E associated with value VD has conflicts with other
13081// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000013082static bool checkMapConflicts(
13083 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000013084 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000013085 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
13086 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013087 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000013088 SourceLocation ELoc = E->getExprLoc();
13089 SourceRange ERange = E->getSourceRange();
13090
13091 // In order to easily check the conflicts we need to match each component of
13092 // the expression under test with the components of the expressions that are
13093 // already in the stack.
13094
Samuel Antao5de996e2016-01-22 20:21:36 +000013095 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013096 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013097 "Map clause expression with unexpected base!");
13098
13099 // Variables to help detecting enclosing problems in data environment nests.
13100 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000013101 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013102
Samuel Antao90927002016-04-26 14:54:23 +000013103 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
13104 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000013105 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
13106 ERange, CKind, &EnclosingExpr,
13107 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
13108 StackComponents,
13109 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013110 assert(!StackComponents.empty() &&
13111 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013112 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013113 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000013114 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013115
Samuel Antao90927002016-04-26 14:54:23 +000013116 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000013117 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000013118
Samuel Antao5de996e2016-01-22 20:21:36 +000013119 // Expressions must start from the same base. Here we detect at which
13120 // point both expressions diverge from each other and see if we can
13121 // detect if the memory referred to both expressions is contiguous and
13122 // do not overlap.
13123 auto CI = CurComponents.rbegin();
13124 auto CE = CurComponents.rend();
13125 auto SI = StackComponents.rbegin();
13126 auto SE = StackComponents.rend();
13127 for (; CI != CE && SI != SE; ++CI, ++SI) {
13128
13129 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
13130 // At most one list item can be an array item derived from a given
13131 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000013132 if (CurrentRegionOnly &&
13133 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
13134 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
13135 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
13136 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
13137 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000013138 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000013139 << CI->getAssociatedExpression()->getSourceRange();
13140 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
13141 diag::note_used_here)
13142 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000013143 return true;
13144 }
13145
13146 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000013147 if (CI->getAssociatedExpression()->getStmtClass() !=
13148 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000013149 break;
13150
13151 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000013152 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000013153 break;
13154 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000013155 // Check if the extra components of the expressions in the enclosing
13156 // data environment are redundant for the current base declaration.
13157 // If they are, the maps completely overlap, which is legal.
13158 for (; SI != SE; ++SI) {
13159 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000013160 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000013161 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000013162 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013163 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000013164 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013165 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000013166 Type =
13167 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13168 }
13169 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013170 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000013171 SemaRef, SI->getAssociatedExpression(), Type))
13172 break;
13173 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013174
13175 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13176 // List items of map clauses in the same construct must not share
13177 // original storage.
13178 //
13179 // If the expressions are exactly the same or one is a subset of the
13180 // other, it means they are sharing storage.
13181 if (CI == CE && SI == SE) {
13182 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013183 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000013184 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013185 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013186 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013187 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13188 << ERange;
13189 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013190 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13191 << RE->getSourceRange();
13192 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013193 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013194 // If we find the same expression in the enclosing data environment,
13195 // that is legal.
13196 IsEnclosedByDataEnvironmentExpr = true;
13197 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000013198 }
13199
Samuel Antao90927002016-04-26 14:54:23 +000013200 QualType DerivedType =
13201 std::prev(CI)->getAssociatedDeclaration()->getType();
13202 SourceLocation DerivedLoc =
13203 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000013204
13205 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13206 // If the type of a list item is a reference to a type T then the type
13207 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000013208 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013209
13210 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
13211 // A variable for which the type is pointer and an array section
13212 // derived from that variable must not appear as list items of map
13213 // clauses of the same construct.
13214 //
13215 // Also, cover one of the cases in:
13216 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13217 // If any part of the original storage of a list item has corresponding
13218 // storage in the device data environment, all of the original storage
13219 // must have corresponding storage in the device data environment.
13220 //
13221 if (DerivedType->isAnyPointerType()) {
13222 if (CI == CE || SI == SE) {
13223 SemaRef.Diag(
13224 DerivedLoc,
13225 diag::err_omp_pointer_mapped_along_with_derived_section)
13226 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013227 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13228 << RE->getSourceRange();
13229 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013230 }
13231 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000013232 SI->getAssociatedExpression()->getStmtClass() ||
13233 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
13234 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013235 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000013236 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000013237 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013238 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13239 << RE->getSourceRange();
13240 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013241 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013242 }
13243
13244 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13245 // List items of map clauses in the same construct must not share
13246 // original storage.
13247 //
13248 // An expression is a subset of the other.
13249 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013250 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000013251 if (CI != CE || SI != SE) {
13252 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
13253 // a pointer.
13254 auto Begin =
13255 CI != CE ? CurComponents.begin() : StackComponents.begin();
13256 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
13257 auto It = Begin;
13258 while (It != End && !It->getAssociatedDeclaration())
13259 std::advance(It, 1);
13260 assert(It != End &&
13261 "Expected at least one component with the declaration.");
13262 if (It != Begin && It->getAssociatedDeclaration()
13263 ->getType()
13264 .getCanonicalType()
13265 ->isAnyPointerType()) {
13266 IsEnclosedByDataEnvironmentExpr = false;
13267 EnclosingExpr = nullptr;
13268 return false;
13269 }
13270 }
Samuel Antao661c0902016-05-26 17:39:58 +000013271 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013272 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013273 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013274 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13275 << ERange;
13276 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013277 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13278 << RE->getSourceRange();
13279 return true;
13280 }
13281
13282 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000013283 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000013284 if (!CurrentRegionOnly && SI != SE)
13285 EnclosingExpr = RE;
13286
13287 // The current expression is a subset of the expression in the data
13288 // environment.
13289 IsEnclosedByDataEnvironmentExpr |=
13290 (!CurrentRegionOnly && CI != CE && SI == SE);
13291
13292 return false;
13293 });
13294
13295 if (CurrentRegionOnly)
13296 return FoundError;
13297
13298 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13299 // If any part of the original storage of a list item has corresponding
13300 // storage in the device data environment, all of the original storage must
13301 // have corresponding storage in the device data environment.
13302 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
13303 // If a list item is an element of a structure, and a different element of
13304 // the structure has a corresponding list item in the device data environment
13305 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000013306 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000013307 // data environment prior to the task encountering the construct.
13308 //
13309 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
13310 SemaRef.Diag(ELoc,
13311 diag::err_omp_original_storage_is_shared_and_does_not_contain)
13312 << ERange;
13313 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
13314 << EnclosingExpr->getSourceRange();
13315 return true;
13316 }
13317
13318 return FoundError;
13319}
13320
Michael Kruse4304e9d2019-02-19 16:38:20 +000013321// Look up the user-defined mapper given the mapper name and mapped type, and
13322// build a reference to it.
13323ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
13324 CXXScopeSpec &MapperIdScopeSpec,
13325 const DeclarationNameInfo &MapperId,
13326 QualType Type, Expr *UnresolvedMapper) {
13327 if (MapperIdScopeSpec.isInvalid())
13328 return ExprError();
13329 // Find all user-defined mappers with the given MapperId.
13330 SmallVector<UnresolvedSet<8>, 4> Lookups;
13331 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
13332 Lookup.suppressDiagnostics();
13333 if (S) {
13334 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
13335 NamedDecl *D = Lookup.getRepresentativeDecl();
13336 while (S && !S->isDeclScope(D))
13337 S = S->getParent();
13338 if (S)
13339 S = S->getParent();
13340 Lookups.emplace_back();
13341 Lookups.back().append(Lookup.begin(), Lookup.end());
13342 Lookup.clear();
13343 }
13344 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
13345 // Extract the user-defined mappers with the given MapperId.
13346 Lookups.push_back(UnresolvedSet<8>());
13347 for (NamedDecl *D : ULE->decls()) {
13348 auto *DMD = cast<OMPDeclareMapperDecl>(D);
13349 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
13350 Lookups.back().addDecl(DMD);
13351 }
13352 }
13353 // Defer the lookup for dependent types. The results will be passed through
13354 // UnresolvedMapper on instantiation.
13355 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
13356 Type->isInstantiationDependentType() ||
13357 Type->containsUnexpandedParameterPack() ||
13358 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
13359 return !D->isInvalidDecl() &&
13360 (D->getType()->isDependentType() ||
13361 D->getType()->isInstantiationDependentType() ||
13362 D->getType()->containsUnexpandedParameterPack());
13363 })) {
13364 UnresolvedSet<8> URS;
13365 for (const UnresolvedSet<8> &Set : Lookups) {
13366 if (Set.empty())
13367 continue;
13368 URS.append(Set.begin(), Set.end());
13369 }
13370 return UnresolvedLookupExpr::Create(
13371 SemaRef.Context, /*NamingClass=*/nullptr,
13372 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
13373 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
13374 }
13375 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13376 // The type must be of struct, union or class type in C and C++
13377 if (!Type->isStructureOrClassType() && !Type->isUnionType())
13378 return ExprEmpty();
13379 SourceLocation Loc = MapperId.getLoc();
13380 // Perform argument dependent lookup.
13381 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
13382 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
13383 // Return the first user-defined mapper with the desired type.
13384 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13385 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
13386 if (!D->isInvalidDecl() &&
13387 SemaRef.Context.hasSameType(D->getType(), Type))
13388 return D;
13389 return nullptr;
13390 }))
13391 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13392 // Find the first user-defined mapper with a type derived from the desired
13393 // type.
13394 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13395 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
13396 if (!D->isInvalidDecl() &&
13397 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
13398 !Type.isMoreQualifiedThan(D->getType()))
13399 return D;
13400 return nullptr;
13401 })) {
13402 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13403 /*DetectVirtual=*/false);
13404 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
13405 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13406 VD->getType().getUnqualifiedType()))) {
13407 if (SemaRef.CheckBaseClassAccess(
13408 Loc, VD->getType(), Type, Paths.front(),
13409 /*DiagID=*/0) != Sema::AR_inaccessible) {
13410 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13411 }
13412 }
13413 }
13414 }
13415 // Report error if a mapper is specified, but cannot be found.
13416 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
13417 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
13418 << Type << MapperId.getName();
13419 return ExprError();
13420 }
13421 return ExprEmpty();
13422}
13423
Samuel Antao661c0902016-05-26 17:39:58 +000013424namespace {
13425// Utility struct that gathers all the related lists associated with a mappable
13426// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013427struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000013428 // The list of expressions.
13429 ArrayRef<Expr *> VarList;
13430 // The list of processed expressions.
13431 SmallVector<Expr *, 16> ProcessedVarList;
13432 // The mappble components for each expression.
13433 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
13434 // The base declaration of the variable.
13435 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000013436 // The reference to the user-defined mapper associated with every expression.
13437 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000013438
13439 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
13440 // We have a list of components and base declarations for each entry in the
13441 // variable list.
13442 VarComponents.reserve(VarList.size());
13443 VarBaseDeclarations.reserve(VarList.size());
13444 }
13445};
13446}
13447
13448// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000013449// \a CKind. In the check process the valid expressions, mappable expression
13450// components, variables, and user-defined mappers are extracted and used to
13451// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
13452// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
13453// and \a MapperId are expected to be valid if the clause kind is 'map'.
13454static void checkMappableExpressionList(
13455 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
13456 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013457 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
13458 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000013459 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000013460 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013461 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
13462 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000013463 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000013464
13465 // If the identifier of user-defined mapper is not specified, it is "default".
13466 // We do not change the actual name in this clause to distinguish whether a
13467 // mapper is specified explicitly, i.e., it is not explicitly specified when
13468 // MapperId.getName() is empty.
13469 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
13470 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
13471 MapperId.setName(DeclNames.getIdentifier(
13472 &SemaRef.getASTContext().Idents.get("default")));
13473 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013474
13475 // Iterators to find the current unresolved mapper expression.
13476 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
13477 bool UpdateUMIt = false;
13478 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013479
Samuel Antao90927002016-04-26 14:54:23 +000013480 // Keep track of the mappable components and base declarations in this clause.
13481 // Each entry in the list is going to have a list of components associated. We
13482 // record each set of the components so that we can build the clause later on.
13483 // In the end we should have the same amount of declarations and component
13484 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000013485
Alexey Bataeve3727102018-04-18 15:57:46 +000013486 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013487 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013488 SourceLocation ELoc = RE->getExprLoc();
13489
Michael Kruse4304e9d2019-02-19 16:38:20 +000013490 // Find the current unresolved mapper expression.
13491 if (UpdateUMIt && UMIt != UMEnd) {
13492 UMIt++;
13493 assert(
13494 UMIt != UMEnd &&
13495 "Expect the size of UnresolvedMappers to match with that of VarList");
13496 }
13497 UpdateUMIt = true;
13498 if (UMIt != UMEnd)
13499 UnresolvedMapper = *UMIt;
13500
Alexey Bataeve3727102018-04-18 15:57:46 +000013501 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013502
13503 if (VE->isValueDependent() || VE->isTypeDependent() ||
13504 VE->isInstantiationDependent() ||
13505 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000013506 // Try to find the associated user-defined mapper.
13507 ExprResult ER = buildUserDefinedMapperRef(
13508 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13509 VE->getType().getCanonicalType(), UnresolvedMapper);
13510 if (ER.isInvalid())
13511 continue;
13512 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000013513 // We can only analyze this information once the missing information is
13514 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000013515 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013516 continue;
13517 }
13518
Alexey Bataeve3727102018-04-18 15:57:46 +000013519 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013520
Samuel Antao5de996e2016-01-22 20:21:36 +000013521 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000013522 SemaRef.Diag(ELoc,
13523 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000013524 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013525 continue;
13526 }
13527
Samuel Antao90927002016-04-26 14:54:23 +000013528 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
13529 ValueDecl *CurDeclaration = nullptr;
13530
13531 // Obtain the array or member expression bases if required. Also, fill the
13532 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000013533 const Expr *BE = checkMapClauseExpressionBase(
13534 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000013535 if (!BE)
13536 continue;
13537
Samuel Antao90927002016-04-26 14:54:23 +000013538 assert(!CurComponents.empty() &&
13539 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013540
Patrick Lystere13b1e32019-01-02 19:28:48 +000013541 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
13542 // Add store "this" pointer to class in DSAStackTy for future checking
13543 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000013544 // Try to find the associated user-defined mapper.
13545 ExprResult ER = buildUserDefinedMapperRef(
13546 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13547 VE->getType().getCanonicalType(), UnresolvedMapper);
13548 if (ER.isInvalid())
13549 continue;
13550 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000013551 // Skip restriction checking for variable or field declarations
13552 MVLI.ProcessedVarList.push_back(RE);
13553 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13554 MVLI.VarComponents.back().append(CurComponents.begin(),
13555 CurComponents.end());
13556 MVLI.VarBaseDeclarations.push_back(nullptr);
13557 continue;
13558 }
13559
Samuel Antao90927002016-04-26 14:54:23 +000013560 // For the following checks, we rely on the base declaration which is
13561 // expected to be associated with the last component. The declaration is
13562 // expected to be a variable or a field (if 'this' is being mapped).
13563 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
13564 assert(CurDeclaration && "Null decl on map clause.");
13565 assert(
13566 CurDeclaration->isCanonicalDecl() &&
13567 "Expecting components to have associated only canonical declarations.");
13568
13569 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000013570 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000013571
13572 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000013573 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013574
13575 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000013576 // threadprivate variables cannot appear in a map clause.
13577 // OpenMP 4.5 [2.10.5, target update Construct]
13578 // threadprivate variables cannot appear in a from clause.
13579 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013580 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013581 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
13582 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000013583 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013584 continue;
13585 }
13586
Samuel Antao5de996e2016-01-22 20:21:36 +000013587 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13588 // A list item cannot appear in both a map clause and a data-sharing
13589 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000013590
Samuel Antao5de996e2016-01-22 20:21:36 +000013591 // Check conflicts with other map clause expressions. We check the conflicts
13592 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000013593 // environment, because the restrictions are different. We only have to
13594 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000013595 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013596 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013597 break;
Samuel Antao661c0902016-05-26 17:39:58 +000013598 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013599 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013600 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013601 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013602
Samuel Antao661c0902016-05-26 17:39:58 +000013603 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000013604 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13605 // If the type of a list item is a reference to a type T then the type will
13606 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000013607 auto I = llvm::find_if(
13608 CurComponents,
13609 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
13610 return MC.getAssociatedDeclaration();
13611 });
13612 assert(I != CurComponents.end() && "Null decl on map clause.");
13613 QualType Type =
13614 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013615
Samuel Antao661c0902016-05-26 17:39:58 +000013616 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
13617 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000013618 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000013619 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013620 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000013621 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000013622 continue;
13623
Samuel Antao661c0902016-05-26 17:39:58 +000013624 if (CKind == OMPC_map) {
13625 // target enter data
13626 // OpenMP [2.10.2, Restrictions, p. 99]
13627 // A map-type must be specified in all map clauses and must be either
13628 // to or alloc.
13629 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
13630 if (DKind == OMPD_target_enter_data &&
13631 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
13632 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13633 << (IsMapTypeImplicit ? 1 : 0)
13634 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13635 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013636 continue;
13637 }
Samuel Antao661c0902016-05-26 17:39:58 +000013638
13639 // target exit_data
13640 // OpenMP [2.10.3, Restrictions, p. 102]
13641 // A map-type must be specified in all map clauses and must be either
13642 // from, release, or delete.
13643 if (DKind == OMPD_target_exit_data &&
13644 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
13645 MapType == OMPC_MAP_delete)) {
13646 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13647 << (IsMapTypeImplicit ? 1 : 0)
13648 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13649 << getOpenMPDirectiveName(DKind);
13650 continue;
13651 }
13652
13653 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13654 // A list item cannot appear in both a map clause and a data-sharing
13655 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000013656 if (VD && isOpenMPTargetExecutionDirective(DKind)) {
13657 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013658 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000013659 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000013660 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000013661 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000013662 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000013663 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000013664 continue;
13665 }
13666 }
Michael Kruse01f670d2019-02-22 22:29:42 +000013667 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013668
Michael Kruse01f670d2019-02-22 22:29:42 +000013669 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000013670 ExprResult ER = buildUserDefinedMapperRef(
13671 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13672 Type.getCanonicalType(), UnresolvedMapper);
13673 if (ER.isInvalid())
13674 continue;
13675 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013676
Samuel Antao90927002016-04-26 14:54:23 +000013677 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000013678 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000013679
13680 // Store the components in the stack so that they can be used to check
13681 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000013682 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
13683 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000013684
13685 // Save the components and declaration to create the clause. For purposes of
13686 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000013687 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000013688 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13689 MVLI.VarComponents.back().append(CurComponents.begin(),
13690 CurComponents.end());
13691 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
13692 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013693 }
Samuel Antao661c0902016-05-26 17:39:58 +000013694}
13695
Michael Kruse4304e9d2019-02-19 16:38:20 +000013696OMPClause *Sema::ActOnOpenMPMapClause(
13697 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13698 ArrayRef<SourceLocation> MapTypeModifiersLoc,
13699 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
13700 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
13701 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
13702 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
13703 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
13704 OMPC_MAP_MODIFIER_unknown,
13705 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000013706 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
13707
13708 // Process map-type-modifiers, flag errors for duplicate modifiers.
13709 unsigned Count = 0;
13710 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
13711 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
13712 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
13713 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
13714 continue;
13715 }
13716 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000013717 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000013718 Modifiers[Count] = MapTypeModifiers[I];
13719 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
13720 ++Count;
13721 }
13722
Michael Kruse4304e9d2019-02-19 16:38:20 +000013723 MappableVarListInfo MVLI(VarList);
13724 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013725 MapperIdScopeSpec, MapperId, UnresolvedMappers,
13726 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000013727
Samuel Antao5de996e2016-01-22 20:21:36 +000013728 // We need to produce a map clause even if we don't have variables so that
13729 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000013730 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
13731 MVLI.VarBaseDeclarations, MVLI.VarComponents,
13732 MVLI.UDMapperList, Modifiers, ModifiersLoc,
13733 MapperIdScopeSpec.getWithLocInContext(Context),
13734 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013735}
Kelvin Li099bb8c2015-11-24 20:50:12 +000013736
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013737QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
13738 TypeResult ParsedType) {
13739 assert(ParsedType.isUsable());
13740
13741 QualType ReductionType = GetTypeFromParser(ParsedType.get());
13742 if (ReductionType.isNull())
13743 return QualType();
13744
13745 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
13746 // A type name in a declare reduction directive cannot be a function type, an
13747 // array type, a reference type, or a type qualified with const, volatile or
13748 // restrict.
13749 if (ReductionType.hasQualifiers()) {
13750 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
13751 return QualType();
13752 }
13753
13754 if (ReductionType->isFunctionType()) {
13755 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
13756 return QualType();
13757 }
13758 if (ReductionType->isReferenceType()) {
13759 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
13760 return QualType();
13761 }
13762 if (ReductionType->isArrayType()) {
13763 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
13764 return QualType();
13765 }
13766 return ReductionType;
13767}
13768
13769Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
13770 Scope *S, DeclContext *DC, DeclarationName Name,
13771 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
13772 AccessSpecifier AS, Decl *PrevDeclInScope) {
13773 SmallVector<Decl *, 8> Decls;
13774 Decls.reserve(ReductionTypes.size());
13775
13776 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000013777 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013778 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
13779 // A reduction-identifier may not be re-declared in the current scope for the
13780 // same type or for a type that is compatible according to the base language
13781 // rules.
13782 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13783 OMPDeclareReductionDecl *PrevDRD = nullptr;
13784 bool InCompoundScope = true;
13785 if (S != nullptr) {
13786 // Find previous declaration with the same name not referenced in other
13787 // declarations.
13788 FunctionScopeInfo *ParentFn = getEnclosingFunction();
13789 InCompoundScope =
13790 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13791 LookupName(Lookup, S);
13792 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13793 /*AllowInlineNamespace=*/false);
13794 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000013795 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013796 while (Filter.hasNext()) {
13797 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
13798 if (InCompoundScope) {
13799 auto I = UsedAsPrevious.find(PrevDecl);
13800 if (I == UsedAsPrevious.end())
13801 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000013802 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013803 UsedAsPrevious[D] = true;
13804 }
13805 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13806 PrevDecl->getLocation();
13807 }
13808 Filter.done();
13809 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013810 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013811 if (!PrevData.second) {
13812 PrevDRD = PrevData.first;
13813 break;
13814 }
13815 }
13816 }
13817 } else if (PrevDeclInScope != nullptr) {
13818 auto *PrevDRDInScope = PrevDRD =
13819 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
13820 do {
13821 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
13822 PrevDRDInScope->getLocation();
13823 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
13824 } while (PrevDRDInScope != nullptr);
13825 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013826 for (const auto &TyData : ReductionTypes) {
13827 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013828 bool Invalid = false;
13829 if (I != PreviousRedeclTypes.end()) {
13830 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
13831 << TyData.first;
13832 Diag(I->second, diag::note_previous_definition);
13833 Invalid = true;
13834 }
13835 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
13836 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
13837 Name, TyData.first, PrevDRD);
13838 DC->addDecl(DRD);
13839 DRD->setAccess(AS);
13840 Decls.push_back(DRD);
13841 if (Invalid)
13842 DRD->setInvalidDecl();
13843 else
13844 PrevDRD = DRD;
13845 }
13846
13847 return DeclGroupPtrTy::make(
13848 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
13849}
13850
13851void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
13852 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13853
13854 // Enter new function scope.
13855 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013856 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013857 getCurFunction()->setHasOMPDeclareReductionCombiner();
13858
13859 if (S != nullptr)
13860 PushDeclContext(S, DRD);
13861 else
13862 CurContext = DRD;
13863
Faisal Valid143a0c2017-04-01 21:30:49 +000013864 PushExpressionEvaluationContext(
13865 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013866
13867 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013868 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
13869 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
13870 // uses semantics of argument handles by value, but it should be passed by
13871 // reference. C lang does not support references, so pass all parameters as
13872 // pointers.
13873 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013874 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013875 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013876 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
13877 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
13878 // uses semantics of argument handles by value, but it should be passed by
13879 // reference. C lang does not support references, so pass all parameters as
13880 // pointers.
13881 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013882 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013883 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
13884 if (S != nullptr) {
13885 PushOnScopeChains(OmpInParm, S);
13886 PushOnScopeChains(OmpOutParm, S);
13887 } else {
13888 DRD->addDecl(OmpInParm);
13889 DRD->addDecl(OmpOutParm);
13890 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013891 Expr *InE =
13892 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
13893 Expr *OutE =
13894 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
13895 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013896}
13897
13898void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
13899 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13900 DiscardCleanupsInEvaluationContext();
13901 PopExpressionEvaluationContext();
13902
13903 PopDeclContext();
13904 PopFunctionScopeInfo();
13905
13906 if (Combiner != nullptr)
13907 DRD->setCombiner(Combiner);
13908 else
13909 DRD->setInvalidDecl();
13910}
13911
Alexey Bataev070f43a2017-09-06 14:49:58 +000013912VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013913 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13914
13915 // Enter new function scope.
13916 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013917 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013918
13919 if (S != nullptr)
13920 PushDeclContext(S, DRD);
13921 else
13922 CurContext = DRD;
13923
Faisal Valid143a0c2017-04-01 21:30:49 +000013924 PushExpressionEvaluationContext(
13925 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013926
13927 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013928 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
13929 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
13930 // uses semantics of argument handles by value, but it should be passed by
13931 // reference. C lang does not support references, so pass all parameters as
13932 // pointers.
13933 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013934 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013935 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013936 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
13937 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
13938 // uses semantics of argument handles by value, but it should be passed by
13939 // reference. C lang does not support references, so pass all parameters as
13940 // pointers.
13941 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013942 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013943 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013944 if (S != nullptr) {
13945 PushOnScopeChains(OmpPrivParm, S);
13946 PushOnScopeChains(OmpOrigParm, S);
13947 } else {
13948 DRD->addDecl(OmpPrivParm);
13949 DRD->addDecl(OmpOrigParm);
13950 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013951 Expr *OrigE =
13952 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
13953 Expr *PrivE =
13954 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
13955 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000013956 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013957}
13958
Alexey Bataev070f43a2017-09-06 14:49:58 +000013959void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
13960 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013961 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13962 DiscardCleanupsInEvaluationContext();
13963 PopExpressionEvaluationContext();
13964
13965 PopDeclContext();
13966 PopFunctionScopeInfo();
13967
Alexey Bataev070f43a2017-09-06 14:49:58 +000013968 if (Initializer != nullptr) {
13969 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
13970 } else if (OmpPrivParm->hasInit()) {
13971 DRD->setInitializer(OmpPrivParm->getInit(),
13972 OmpPrivParm->isDirectInit()
13973 ? OMPDeclareReductionDecl::DirectInit
13974 : OMPDeclareReductionDecl::CopyInit);
13975 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013976 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000013977 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013978}
13979
13980Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
13981 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013982 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013983 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013984 if (S)
13985 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
13986 /*AddToContext=*/false);
13987 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013988 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000013989 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013990 }
13991 return DeclReductions;
13992}
13993
Michael Kruse251e1482019-02-01 20:25:04 +000013994TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
13995 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13996 QualType T = TInfo->getType();
13997 if (D.isInvalidType())
13998 return true;
13999
14000 if (getLangOpts().CPlusPlus) {
14001 // Check that there are no default arguments (C++ only).
14002 CheckExtraCXXDefaultArguments(D);
14003 }
14004
14005 return CreateParsedType(T, TInfo);
14006}
14007
14008QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
14009 TypeResult ParsedType) {
14010 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
14011
14012 QualType MapperType = GetTypeFromParser(ParsedType.get());
14013 assert(!MapperType.isNull() && "Expect valid mapper type");
14014
14015 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14016 // The type must be of struct, union or class type in C and C++
14017 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
14018 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
14019 return QualType();
14020 }
14021 return MapperType;
14022}
14023
14024OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
14025 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
14026 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
14027 Decl *PrevDeclInScope) {
14028 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
14029 forRedeclarationInCurContext());
14030 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14031 // A mapper-identifier may not be redeclared in the current scope for the
14032 // same type or for a type that is compatible according to the base language
14033 // rules.
14034 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
14035 OMPDeclareMapperDecl *PrevDMD = nullptr;
14036 bool InCompoundScope = true;
14037 if (S != nullptr) {
14038 // Find previous declaration with the same name not referenced in other
14039 // declarations.
14040 FunctionScopeInfo *ParentFn = getEnclosingFunction();
14041 InCompoundScope =
14042 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
14043 LookupName(Lookup, S);
14044 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14045 /*AllowInlineNamespace=*/false);
14046 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
14047 LookupResult::Filter Filter = Lookup.makeFilter();
14048 while (Filter.hasNext()) {
14049 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
14050 if (InCompoundScope) {
14051 auto I = UsedAsPrevious.find(PrevDecl);
14052 if (I == UsedAsPrevious.end())
14053 UsedAsPrevious[PrevDecl] = false;
14054 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
14055 UsedAsPrevious[D] = true;
14056 }
14057 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14058 PrevDecl->getLocation();
14059 }
14060 Filter.done();
14061 if (InCompoundScope) {
14062 for (const auto &PrevData : UsedAsPrevious) {
14063 if (!PrevData.second) {
14064 PrevDMD = PrevData.first;
14065 break;
14066 }
14067 }
14068 }
14069 } else if (PrevDeclInScope) {
14070 auto *PrevDMDInScope = PrevDMD =
14071 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
14072 do {
14073 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
14074 PrevDMDInScope->getLocation();
14075 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
14076 } while (PrevDMDInScope != nullptr);
14077 }
14078 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
14079 bool Invalid = false;
14080 if (I != PreviousRedeclTypes.end()) {
14081 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
14082 << MapperType << Name;
14083 Diag(I->second, diag::note_previous_definition);
14084 Invalid = true;
14085 }
14086 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
14087 MapperType, VN, PrevDMD);
14088 DC->addDecl(DMD);
14089 DMD->setAccess(AS);
14090 if (Invalid)
14091 DMD->setInvalidDecl();
14092
14093 // Enter new function scope.
14094 PushFunctionScope();
14095 setFunctionHasBranchProtectedScope();
14096
14097 CurContext = DMD;
14098
14099 return DMD;
14100}
14101
14102void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
14103 Scope *S,
14104 QualType MapperType,
14105 SourceLocation StartLoc,
14106 DeclarationName VN) {
14107 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
14108 if (S)
14109 PushOnScopeChains(VD, S);
14110 else
14111 DMD->addDecl(VD);
14112 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
14113 DMD->setMapperVarRef(MapperVarRefExpr);
14114}
14115
14116Sema::DeclGroupPtrTy
14117Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
14118 ArrayRef<OMPClause *> ClauseList) {
14119 PopDeclContext();
14120 PopFunctionScopeInfo();
14121
14122 if (D) {
14123 if (S)
14124 PushOnScopeChains(D, S, /*AddToContext=*/false);
14125 D->CreateClauses(Context, ClauseList);
14126 }
14127
14128 return DeclGroupPtrTy::make(DeclGroupRef(D));
14129}
14130
David Majnemer9d168222016-08-05 17:44:54 +000014131OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000014132 SourceLocation StartLoc,
14133 SourceLocation LParenLoc,
14134 SourceLocation EndLoc) {
14135 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014136 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014137
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014138 // OpenMP [teams Constrcut, Restrictions]
14139 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014140 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000014141 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014142 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014143
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014144 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014145 OpenMPDirectiveKind CaptureRegion =
14146 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
14147 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014148 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014149 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014150 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14151 HelperValStmt = buildPreInits(Context, Captures);
14152 }
14153
14154 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
14155 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000014156}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014157
14158OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
14159 SourceLocation StartLoc,
14160 SourceLocation LParenLoc,
14161 SourceLocation EndLoc) {
14162 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014163 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014164
14165 // OpenMP [teams Constrcut, Restrictions]
14166 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014167 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000014168 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014169 return nullptr;
14170
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014171 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014172 OpenMPDirectiveKind CaptureRegion =
14173 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
14174 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014175 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014176 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014177 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14178 HelperValStmt = buildPreInits(Context, Captures);
14179 }
14180
14181 return new (Context) OMPThreadLimitClause(
14182 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014183}
Alexey Bataeva0569352015-12-01 10:17:31 +000014184
14185OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
14186 SourceLocation StartLoc,
14187 SourceLocation LParenLoc,
14188 SourceLocation EndLoc) {
14189 Expr *ValExpr = Priority;
14190
14191 // OpenMP [2.9.1, task Constrcut]
14192 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014193 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000014194 /*StrictlyPositive=*/false))
14195 return nullptr;
14196
14197 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14198}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014199
14200OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
14201 SourceLocation StartLoc,
14202 SourceLocation LParenLoc,
14203 SourceLocation EndLoc) {
14204 Expr *ValExpr = Grainsize;
14205
14206 // OpenMP [2.9.2, taskloop Constrcut]
14207 // The parameter of the grainsize clause must be a positive integer
14208 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014209 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014210 /*StrictlyPositive=*/true))
14211 return nullptr;
14212
14213 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14214}
Alexey Bataev382967a2015-12-08 12:06:20 +000014215
14216OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
14217 SourceLocation StartLoc,
14218 SourceLocation LParenLoc,
14219 SourceLocation EndLoc) {
14220 Expr *ValExpr = NumTasks;
14221
14222 // OpenMP [2.9.2, taskloop Constrcut]
14223 // The parameter of the num_tasks clause must be a positive integer
14224 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014225 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000014226 /*StrictlyPositive=*/true))
14227 return nullptr;
14228
14229 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14230}
14231
Alexey Bataev28c75412015-12-15 08:19:24 +000014232OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
14233 SourceLocation LParenLoc,
14234 SourceLocation EndLoc) {
14235 // OpenMP [2.13.2, critical construct, Description]
14236 // ... where hint-expression is an integer constant expression that evaluates
14237 // to a valid lock hint.
14238 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
14239 if (HintExpr.isInvalid())
14240 return nullptr;
14241 return new (Context)
14242 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
14243}
14244
Carlo Bertollib4adf552016-01-15 18:50:31 +000014245OMPClause *Sema::ActOnOpenMPDistScheduleClause(
14246 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14247 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
14248 SourceLocation EndLoc) {
14249 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
14250 std::string Values;
14251 Values += "'";
14252 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
14253 Values += "'";
14254 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14255 << Values << getOpenMPClauseName(OMPC_dist_schedule);
14256 return nullptr;
14257 }
14258 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000014259 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000014260 if (ChunkSize) {
14261 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14262 !ChunkSize->isInstantiationDependent() &&
14263 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014264 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000014265 ExprResult Val =
14266 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14267 if (Val.isInvalid())
14268 return nullptr;
14269
14270 ValExpr = Val.get();
14271
14272 // OpenMP [2.7.1, Restrictions]
14273 // chunk_size must be a loop invariant integer expression with a positive
14274 // value.
14275 llvm::APSInt Result;
14276 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
14277 if (Result.isSigned() && !Result.isStrictlyPositive()) {
14278 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14279 << "dist_schedule" << ChunkSize->getSourceRange();
14280 return nullptr;
14281 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000014282 } else if (getOpenMPCaptureRegionForClause(
14283 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
14284 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000014285 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014286 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014287 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000014288 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14289 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014290 }
14291 }
14292 }
14293
14294 return new (Context)
14295 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000014296 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014297}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014298
14299OMPClause *Sema::ActOnOpenMPDefaultmapClause(
14300 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
14301 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
14302 SourceLocation KindLoc, SourceLocation EndLoc) {
14303 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000014304 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014305 std::string Value;
14306 SourceLocation Loc;
14307 Value += "'";
14308 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
14309 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014310 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014311 Loc = MLoc;
14312 } else {
14313 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014314 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014315 Loc = KindLoc;
14316 }
14317 Value += "'";
14318 Diag(Loc, diag::err_omp_unexpected_clause_value)
14319 << Value << getOpenMPClauseName(OMPC_defaultmap);
14320 return nullptr;
14321 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000014322 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014323
14324 return new (Context)
14325 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
14326}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014327
14328bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
14329 DeclContext *CurLexicalContext = getCurLexicalContext();
14330 if (!CurLexicalContext->isFileContext() &&
14331 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000014332 !CurLexicalContext->isExternCXXContext() &&
14333 !isa<CXXRecordDecl>(CurLexicalContext) &&
14334 !isa<ClassTemplateDecl>(CurLexicalContext) &&
14335 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
14336 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014337 Diag(Loc, diag::err_omp_region_not_file_context);
14338 return false;
14339 }
Kelvin Libc38e632018-09-10 02:07:09 +000014340 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014341 return true;
14342}
14343
14344void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000014345 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014346 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000014347 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014348}
14349
David Majnemer9d168222016-08-05 17:44:54 +000014350void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
14351 CXXScopeSpec &ScopeSpec,
14352 const DeclarationNameInfo &Id,
14353 OMPDeclareTargetDeclAttr::MapTypeTy MT,
14354 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014355 LookupResult Lookup(*this, Id, LookupOrdinaryName);
14356 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
14357
14358 if (Lookup.isAmbiguous())
14359 return;
14360 Lookup.suppressDiagnostics();
14361
14362 if (!Lookup.isSingleResult()) {
14363 if (TypoCorrection Corrected =
14364 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
14365 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
14366 CTK_ErrorRecovery)) {
14367 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
14368 << Id.getName());
14369 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
14370 return;
14371 }
14372
14373 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
14374 return;
14375 }
14376
14377 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev30a78212018-09-11 13:59:10 +000014378 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
14379 isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014380 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
14381 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
Alexey Bataev30a78212018-09-11 13:59:10 +000014382 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14383 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
14384 cast<ValueDecl>(ND));
14385 if (!Res) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014386 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014387 ND->addAttr(A);
14388 if (ASTMutationListener *ML = Context.getASTMutationListener())
14389 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000014390 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Alexey Bataev30a78212018-09-11 13:59:10 +000014391 } else if (*Res != MT) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014392 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
14393 << Id.getName();
14394 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014395 } else {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014396 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataeve3727102018-04-18 15:57:46 +000014397 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014398}
14399
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014400static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
14401 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014402 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014403 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000014404 auto *VD = cast<VarDecl>(D);
14405 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
14406 return;
14407 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
14408 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014409}
14410
14411static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
14412 Sema &SemaRef, DSAStackTy *Stack,
14413 ValueDecl *VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014414 return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14415 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
14416 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014417}
14418
Kelvin Li1ce87c72017-12-12 20:08:12 +000014419void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
14420 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014421 if (!D || D->isInvalidDecl())
14422 return;
14423 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014424 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014425 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000014426 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000014427 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
14428 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000014429 return;
14430 // 2.10.6: threadprivate variable cannot appear in a declare target
14431 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014432 if (DSAStack->isThreadPrivate(VD)) {
14433 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000014434 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014435 return;
14436 }
14437 }
Alexey Bataev97b72212018-08-14 18:31:20 +000014438 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
14439 D = FTD->getTemplatedDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014440 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014441 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14442 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
14443 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000014444 assert(IdLoc.isValid() && "Source location is expected");
14445 Diag(IdLoc, diag::err_omp_function_in_link_clause);
14446 Diag(FD->getLocation(), diag::note_defined_here) << FD;
14447 return;
14448 }
14449 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014450 if (auto *VD = dyn_cast<ValueDecl>(D)) {
14451 // Problem if any with var declared with incomplete type will be reported
14452 // as normal, so no need to check it here.
14453 if ((E || !VD->getType()->isIncompleteType()) &&
14454 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
14455 return;
14456 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
14457 // Checking declaration inside declare target region.
14458 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
14459 isa<FunctionTemplateDecl>(D)) {
14460 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
14461 Context, OMPDeclareTargetDeclAttr::MT_To);
14462 D->addAttr(A);
14463 if (ASTMutationListener *ML = Context.getASTMutationListener())
14464 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
14465 }
14466 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014467 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014468 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014469 if (!E)
14470 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014471 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
14472}
Samuel Antao661c0902016-05-26 17:39:58 +000014473
14474OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000014475 CXXScopeSpec &MapperIdScopeSpec,
14476 DeclarationNameInfo &MapperId,
14477 const OMPVarListLocTy &Locs,
14478 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000014479 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014480 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
14481 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000014482 if (MVLI.ProcessedVarList.empty())
14483 return nullptr;
14484
Michael Kruse01f670d2019-02-22 22:29:42 +000014485 return OMPToClause::Create(
14486 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14487 MVLI.VarComponents, MVLI.UDMapperList,
14488 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000014489}
Samuel Antaoec172c62016-05-26 17:49:04 +000014490
14491OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000014492 CXXScopeSpec &MapperIdScopeSpec,
14493 DeclarationNameInfo &MapperId,
14494 const OMPVarListLocTy &Locs,
14495 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014496 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014497 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
14498 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000014499 if (MVLI.ProcessedVarList.empty())
14500 return nullptr;
14501
Michael Kruse0336c752019-02-25 20:34:15 +000014502 return OMPFromClause::Create(
14503 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14504 MVLI.VarComponents, MVLI.UDMapperList,
14505 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000014506}
Carlo Bertolli2404b172016-07-13 15:37:16 +000014507
14508OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014509 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000014510 MappableVarListInfo MVLI(VarList);
14511 SmallVector<Expr *, 8> PrivateCopies;
14512 SmallVector<Expr *, 8> Inits;
14513
Alexey Bataeve3727102018-04-18 15:57:46 +000014514 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014515 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
14516 SourceLocation ELoc;
14517 SourceRange ERange;
14518 Expr *SimpleRefExpr = RefExpr;
14519 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14520 if (Res.second) {
14521 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000014522 MVLI.ProcessedVarList.push_back(RefExpr);
14523 PrivateCopies.push_back(nullptr);
14524 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014525 }
14526 ValueDecl *D = Res.first;
14527 if (!D)
14528 continue;
14529
14530 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000014531 Type = Type.getNonReferenceType().getUnqualifiedType();
14532
14533 auto *VD = dyn_cast<VarDecl>(D);
14534
14535 // Item should be a pointer or reference to pointer.
14536 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014537 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
14538 << 0 << RefExpr->getSourceRange();
14539 continue;
14540 }
Samuel Antaocc10b852016-07-28 14:23:26 +000014541
14542 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014543 auto VDPrivate =
14544 buildVarDecl(*this, ELoc, Type, D->getName(),
14545 D->hasAttrs() ? &D->getAttrs() : nullptr,
14546 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000014547 if (VDPrivate->isInvalidDecl())
14548 continue;
14549
14550 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014551 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000014552 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
14553
14554 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000014555 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000014556 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000014557 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
14558 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000014559 AddInitializerToDecl(VDPrivate,
14560 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014561 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000014562
14563 // If required, build a capture to implement the privatization initialized
14564 // with the current list item value.
14565 DeclRefExpr *Ref = nullptr;
14566 if (!VD)
14567 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14568 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
14569 PrivateCopies.push_back(VDPrivateRefExpr);
14570 Inits.push_back(VDInitRefExpr);
14571
14572 // We need to add a data sharing attribute for this variable to make sure it
14573 // is correctly captured. A variable that shows up in a use_device_ptr has
14574 // similar properties of a first private variable.
14575 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
14576
14577 // Create a mappable component for the list item. List items in this clause
14578 // only need a component.
14579 MVLI.VarBaseDeclarations.push_back(D);
14580 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14581 MVLI.VarComponents.back().push_back(
14582 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000014583 }
14584
Samuel Antaocc10b852016-07-28 14:23:26 +000014585 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000014586 return nullptr;
14587
Samuel Antaocc10b852016-07-28 14:23:26 +000014588 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000014589 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
14590 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014591}
Carlo Bertolli70594e92016-07-13 17:16:49 +000014592
14593OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014594 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000014595 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000014596 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000014597 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000014598 SourceLocation ELoc;
14599 SourceRange ERange;
14600 Expr *SimpleRefExpr = RefExpr;
14601 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14602 if (Res.second) {
14603 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000014604 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014605 }
14606 ValueDecl *D = Res.first;
14607 if (!D)
14608 continue;
14609
14610 QualType Type = D->getType();
14611 // item should be a pointer or array or reference to pointer or array
14612 if (!Type.getNonReferenceType()->isPointerType() &&
14613 !Type.getNonReferenceType()->isArrayType()) {
14614 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
14615 << 0 << RefExpr->getSourceRange();
14616 continue;
14617 }
Samuel Antao6890b092016-07-28 14:25:09 +000014618
14619 // Check if the declaration in the clause does not show up in any data
14620 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000014621 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000014622 if (isOpenMPPrivate(DVar.CKind)) {
14623 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
14624 << getOpenMPClauseName(DVar.CKind)
14625 << getOpenMPClauseName(OMPC_is_device_ptr)
14626 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000014627 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000014628 continue;
14629 }
14630
Alexey Bataeve3727102018-04-18 15:57:46 +000014631 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000014632 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000014633 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000014634 [&ConflictExpr](
14635 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
14636 OpenMPClauseKind) -> bool {
14637 ConflictExpr = R.front().getAssociatedExpression();
14638 return true;
14639 })) {
14640 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
14641 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
14642 << ConflictExpr->getSourceRange();
14643 continue;
14644 }
14645
14646 // Store the components in the stack so that they can be used to check
14647 // against other clauses later on.
14648 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
14649 DSAStack->addMappableExpressionComponents(
14650 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
14651
14652 // Record the expression we've just processed.
14653 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
14654
14655 // Create a mappable component for the list item. List items in this clause
14656 // only need a component. We use a null declaration to signal fields in
14657 // 'this'.
14658 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
14659 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
14660 "Unexpected device pointer expression!");
14661 MVLI.VarBaseDeclarations.push_back(
14662 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
14663 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14664 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014665 }
14666
Samuel Antao6890b092016-07-28 14:25:09 +000014667 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000014668 return nullptr;
14669
Michael Kruse4304e9d2019-02-19 16:38:20 +000014670 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
14671 MVLI.VarBaseDeclarations,
14672 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014673}