blob: 51e0dafbbc55221eefdcc46e894fd295d1e9a513 [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
Alexey Bataev318f431b2019-03-22 15:25:12 +0000425 /// Checks if the defined 'requires' directive has specified type of clause.
426 template <typename ClauseType>
427 bool hasRequiresDeclWithClause() {
428 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
429 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
430 return isa<ClauseType>(C);
431 });
432 });
433 }
434
Kelvin Li1408f912018-09-26 04:28:39 +0000435 /// Checks for a duplicate clause amongst previously declared requires
436 /// directives
437 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
438 bool IsDuplicate = false;
439 for (OMPClause *CNew : ClauseList) {
440 for (const OMPRequiresDecl *D : RequiresDecls) {
441 for (const OMPClause *CPrev : D->clauselists()) {
442 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
443 SemaRef.Diag(CNew->getBeginLoc(),
444 diag::err_omp_requires_clause_redeclaration)
445 << getOpenMPClauseName(CNew->getClauseKind());
446 SemaRef.Diag(CPrev->getBeginLoc(),
447 diag::note_omp_requires_previous_clause)
448 << getOpenMPClauseName(CPrev->getClauseKind());
449 IsDuplicate = true;
450 }
451 }
452 }
453 }
454 return IsDuplicate;
455 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000456
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000457 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000458 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000459 assert(!isStackEmpty());
460 Stack.back().first.back().DefaultAttr = DSA_none;
461 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000462 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000463 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000464 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000465 assert(!isStackEmpty());
466 Stack.back().first.back().DefaultAttr = DSA_shared;
467 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000468 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000469 /// Set default data mapping attribute to 'tofrom:scalar'.
470 void setDefaultDMAToFromScalar(SourceLocation Loc) {
471 assert(!isStackEmpty());
472 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
473 Stack.back().first.back().DefaultMapAttrLoc = Loc;
474 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000475
476 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000477 return isStackEmpty() ? DSA_unspecified
478 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000479 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000480 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000481 return isStackEmpty() ? SourceLocation()
482 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000483 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000484 DefaultMapAttributes getDefaultDMA() const {
485 return isStackEmpty() ? DMA_unspecified
486 : Stack.back().first.back().DefaultMapAttr;
487 }
488 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
489 return Stack.back().first[Level].DefaultMapAttr;
490 }
491 SourceLocation getDefaultDMALocation() const {
492 return isStackEmpty() ? SourceLocation()
493 : Stack.back().first.back().DefaultMapAttrLoc;
494 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000495
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000496 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000497 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000498 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000499 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000500 }
501
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000502 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000503 void setOrderedRegion(bool IsOrdered, const Expr *Param,
504 OMPOrderedClause *Clause) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000505 assert(!isStackEmpty());
Alexey Bataevf138fda2018-08-13 19:04:24 +0000506 if (IsOrdered)
507 Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
508 else
509 Stack.back().first.back().OrderedRegion.reset();
510 }
511 /// Returns true, if region is ordered (has associated 'ordered' clause),
512 /// false - otherwise.
513 bool isOrderedRegion() const {
514 if (isStackEmpty())
515 return false;
516 return Stack.back().first.rbegin()->OrderedRegion.hasValue();
517 }
518 /// Returns optional parameter for the ordered region.
519 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
520 if (isStackEmpty() ||
521 !Stack.back().first.rbegin()->OrderedRegion.hasValue())
522 return std::make_pair(nullptr, nullptr);
523 return Stack.back().first.rbegin()->OrderedRegion.getValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000524 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000525 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000526 /// 'ordered' clause), false - otherwise.
527 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000528 if (isStackEmpty() || Stack.back().first.size() == 1)
529 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000530 return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000531 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000532 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000533 std::pair<const Expr *, OMPOrderedClause *>
534 getParentOrderedRegionParam() const {
535 if (isStackEmpty() || Stack.back().first.size() == 1 ||
536 !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
537 return std::make_pair(nullptr, nullptr);
538 return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
Alexey Bataev346265e2015-09-25 10:37:12 +0000539 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000540 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000541 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000542 assert(!isStackEmpty());
543 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000544 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000545 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000546 /// 'nowait' clause), false - otherwise.
547 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000548 if (isStackEmpty() || Stack.back().first.size() == 1)
549 return false;
550 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000551 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000552 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000553 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000554 if (!isStackEmpty() && Stack.back().first.size() > 1) {
555 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
556 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
557 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000558 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000559 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000560 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000561 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000562 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000563
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000564 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000565 void setAssociatedLoops(unsigned Val) {
566 assert(!isStackEmpty());
567 Stack.back().first.back().AssociatedLoops = Val;
568 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000569 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000570 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000571 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000572 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000573
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000574 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000575 /// region.
576 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000577 if (!isStackEmpty() && Stack.back().first.size() > 1) {
578 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
579 TeamsRegionLoc;
580 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000581 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000582 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000583 bool hasInnerTeamsRegion() const {
584 return getInnerTeamsRegionLoc().isValid();
585 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000586 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000587 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000588 return isStackEmpty() ? SourceLocation()
589 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000590 }
591
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000592 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000593 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000594 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000595 SourceLocation getConstructLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000596 return isStackEmpty() ? SourceLocation()
597 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000598 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000599
Samuel Antao4c8035b2016-12-12 18:00:20 +0000600 /// Do the check specified in \a Check to all component lists and return true
601 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000602 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000603 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000604 const llvm::function_ref<
605 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000606 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000607 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000608 if (isStackEmpty())
609 return false;
610 auto SI = Stack.back().first.rbegin();
611 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000612
613 if (SI == SE)
614 return false;
615
Alexey Bataeve3727102018-04-18 15:57:46 +0000616 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000617 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000618 else
619 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000620
621 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000622 auto MI = SI->MappedExprComponents.find(VD);
623 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000624 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
625 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000626 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000627 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000628 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000629 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000630 }
631
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000632 /// Do the check specified in \a Check to all component lists at a given level
633 /// and return true if any issue is found.
634 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000635 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000636 const llvm::function_ref<
637 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000638 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000639 Check) const {
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000640 if (isStackEmpty())
641 return false;
642
643 auto StartI = Stack.back().first.begin();
644 auto EndI = Stack.back().first.end();
645 if (std::distance(StartI, EndI) <= (int)Level)
646 return false;
647 std::advance(StartI, Level);
648
649 auto MI = StartI->MappedExprComponents.find(VD);
650 if (MI != StartI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000651 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
652 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000653 if (Check(L, MI->second.Kind))
654 return true;
655 return false;
656 }
657
Samuel Antao4c8035b2016-12-12 18:00:20 +0000658 /// Create a new mappable expression component list associated with a given
659 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000660 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000661 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000662 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
663 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000664 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000665 "Not expecting to retrieve components from a empty stack!");
Alexey Bataeve3727102018-04-18 15:57:46 +0000666 MappedExprComponentTy &MEC =
667 Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000668 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000669 MEC.Components.resize(MEC.Components.size() + 1);
670 MEC.Components.back().append(Components.begin(), Components.end());
671 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000672 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000673
674 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000675 assert(!isStackEmpty());
676 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000677 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000678 void addDoacrossDependClause(OMPDependClause *C,
679 const OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000680 assert(!isStackEmpty() && Stack.back().first.size() > 1);
Alexey Bataeve3727102018-04-18 15:57:46 +0000681 SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000682 assert(isOpenMPWorksharingDirective(StackElem.Directive));
Alexey Bataeve3727102018-04-18 15:57:46 +0000683 StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000684 }
685 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
686 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000687 assert(!isStackEmpty());
Alexey Bataeve3727102018-04-18 15:57:46 +0000688 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000689 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000690 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000691 return llvm::make_range(Ref.begin(), Ref.end());
692 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000693 return llvm::make_range(StackElem.DoacrossDepends.end(),
694 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000695 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000696
697 // Store types of classes which have been explicitly mapped
698 void addMappedClassesQualTypes(QualType QT) {
699 SharingMapTy &StackElem = Stack.back().first.back();
700 StackElem.MappedClassesQualTypes.insert(QT);
701 }
702
703 // Return set of mapped classes types
704 bool isClassPreviouslyMapped(QualType QT) const {
705 const SharingMapTy &StackElem = Stack.back().first.back();
706 return StackElem.MappedClassesQualTypes.count(QT) != 0;
707 }
708
Alexey Bataeva495c642019-03-11 19:51:42 +0000709 /// Adds global declare target to the parent target region.
710 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
711 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
712 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
713 "Expected declare target link global.");
714 if (isStackEmpty())
715 return;
716 auto It = Stack.back().first.rbegin();
717 while (It != Stack.back().first.rend() &&
718 !isOpenMPTargetExecutionDirective(It->Directive))
719 ++It;
720 if (It != Stack.back().first.rend()) {
721 assert(isOpenMPTargetExecutionDirective(It->Directive) &&
722 "Expected target executable directive.");
723 It->DeclareTargetLinkVarDecls.push_back(E);
724 }
725 }
726
727 /// Returns the list of globals with declare target link if current directive
728 /// is target.
729 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
730 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
731 "Expected target executable directive.");
732 return Stack.back().first.back().DeclareTargetLinkVarDecls;
733 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000734};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000735
736bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
737 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
738}
739
740bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
741 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000742}
Alexey Bataeve3727102018-04-18 15:57:46 +0000743
Alexey Bataeved09d242014-05-28 05:53:51 +0000744} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000745
Alexey Bataeve3727102018-04-18 15:57:46 +0000746static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000747 if (const auto *FE = dyn_cast<FullExpr>(E))
748 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000749
Alexey Bataeve3727102018-04-18 15:57:46 +0000750 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000751 E = MTE->GetTemporaryExpr();
752
Alexey Bataeve3727102018-04-18 15:57:46 +0000753 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000754 E = Binder->getSubExpr();
755
Alexey Bataeve3727102018-04-18 15:57:46 +0000756 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000757 E = ICE->getSubExprAsWritten();
758 return E->IgnoreParens();
759}
760
Alexey Bataeve3727102018-04-18 15:57:46 +0000761static Expr *getExprAsWritten(Expr *E) {
762 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
763}
764
765static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
766 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
767 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000768 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000769 const auto *VD = dyn_cast<VarDecl>(D);
770 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000771 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000772 VD = VD->getCanonicalDecl();
773 D = VD;
774 } else {
775 assert(FD);
776 FD = FD->getCanonicalDecl();
777 D = FD;
778 }
779 return D;
780}
781
Alexey Bataeve3727102018-04-18 15:57:46 +0000782static ValueDecl *getCanonicalDecl(ValueDecl *D) {
783 return const_cast<ValueDecl *>(
784 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
785}
786
787DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
788 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000789 D = getCanonicalDecl(D);
790 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000791 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000792 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000793 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000794 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
795 // in a region but not in construct]
796 // File-scope or namespace-scope variables referenced in called routines
797 // in the region are shared unless they appear in a threadprivate
798 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000799 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000800 DVar.CKind = OMPC_shared;
801
802 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
803 // in a region but not in construct]
804 // Variables with static storage duration that are declared in called
805 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000806 if (VD && VD->hasGlobalStorage())
807 DVar.CKind = OMPC_shared;
808
809 // Non-static data members are shared by default.
810 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000811 DVar.CKind = OMPC_shared;
812
Alexey Bataev758e55e2013-09-06 18:03:48 +0000813 return DVar;
814 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000815
Alexey Bataevec3da872014-01-31 05:15:34 +0000816 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
817 // in a Construct, C/C++, predetermined, p.1]
818 // Variables with automatic storage duration that are declared in a scope
819 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000820 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
821 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000822 DVar.CKind = OMPC_private;
823 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000824 }
825
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000826 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000827 // Explicitly specified attributes and local variables with predetermined
828 // attributes.
829 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000830 const DSAInfo &Data = Iter->SharingMap.lookup(D);
831 DVar.RefExpr = Data.RefExpr.getPointer();
832 DVar.PrivateCopy = Data.PrivateCopy;
833 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000834 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000835 return DVar;
836 }
837
838 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
839 // in a Construct, C/C++, implicitly determined, p.1]
840 // In a parallel or task construct, the data-sharing attributes of these
841 // variables are determined by the default clause, if present.
842 switch (Iter->DefaultAttr) {
843 case DSA_shared:
844 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000845 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000846 return DVar;
847 case DSA_none:
848 return DVar;
849 case DSA_unspecified:
850 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
851 // in a Construct, implicitly determined, p.2]
852 // In a parallel construct, if no default clause is present, these
853 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000854 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000855 if (isOpenMPParallelDirective(DVar.DKind) ||
856 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000857 DVar.CKind = OMPC_shared;
858 return DVar;
859 }
860
861 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
862 // in a Construct, implicitly determined, p.4]
863 // In a task construct, if no default clause is present, a variable that in
864 // the enclosing context is determined to be shared by all implicit tasks
865 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000866 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000867 DSAVarData DVarTemp;
Alexey Bataeve3727102018-04-18 15:57:46 +0000868 iterator I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000869 do {
870 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000871 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000872 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000873 // In a task construct, if no default clause is present, a variable
874 // whose data-sharing attribute is not determined by the rules above is
875 // firstprivate.
876 DVarTemp = getDSA(I, D);
877 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000878 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000879 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000880 return DVar;
881 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000882 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000883 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000884 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000885 return DVar;
886 }
887 }
888 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
889 // in a Construct, implicitly determined, p.3]
890 // For constructs other than task, if no default clause is present, these
891 // variables inherit their data-sharing attributes from the enclosing
892 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000893 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000894}
895
Alexey Bataeve3727102018-04-18 15:57:46 +0000896const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
897 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000898 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000899 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000900 SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000901 auto It = StackElem.AlignedMap.find(D);
902 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000903 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000904 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000905 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000906 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000907 assert(It->second && "Unexpected nullptr expr in the aligned map");
908 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000909}
910
Alexey Bataeve3727102018-04-18 15:57:46 +0000911void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000912 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000913 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000914 SharingMapTy &StackElem = Stack.back().first.back();
915 StackElem.LCVMap.try_emplace(
916 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +0000917}
918
Alexey Bataeve3727102018-04-18 15:57:46 +0000919const DSAStackTy::LCDeclInfo
920DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000921 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000922 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000923 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000924 auto It = StackElem.LCVMap.find(D);
925 if (It != StackElem.LCVMap.end())
926 return It->second;
927 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000928}
929
Alexey Bataeve3727102018-04-18 15:57:46 +0000930const DSAStackTy::LCDeclInfo
931DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000932 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
933 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000934 D = getCanonicalDecl(D);
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 auto It = StackElem.LCVMap.find(D);
937 if (It != StackElem.LCVMap.end())
938 return It->second;
939 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000940}
941
Alexey Bataeve3727102018-04-18 15:57:46 +0000942const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000943 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
944 "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000945 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000946 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000947 return nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +0000948 for (const auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000949 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000950 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000951 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000952}
953
Alexey Bataeve3727102018-04-18 15:57:46 +0000954void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000955 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000956 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000957 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000958 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000959 Data.Attributes = A;
960 Data.RefExpr.setPointer(E);
961 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000962 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000963 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000964 DSAInfo &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000965 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
966 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
967 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
968 (isLoopControlVariable(D).first && A == OMPC_private));
969 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
970 Data.RefExpr.setInt(/*IntVal=*/true);
971 return;
972 }
973 const bool IsLastprivate =
974 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
975 Data.Attributes = A;
976 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
977 Data.PrivateCopy = PrivateCopy;
978 if (PrivateCopy) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000979 DSAInfo &Data =
980 Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000981 Data.Attributes = A;
982 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
983 Data.PrivateCopy = nullptr;
984 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000985 }
986}
987
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000988/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000989static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000990 StringRef Name, const AttrVec *Attrs = nullptr,
991 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000992 DeclContext *DC = SemaRef.CurContext;
993 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
994 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +0000995 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000996 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
997 if (Attrs) {
998 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
999 I != E; ++I)
1000 Decl->addAttr(*I);
1001 }
1002 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001003 if (OrigRef) {
1004 Decl->addAttr(
1005 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1006 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001007 return Decl;
1008}
1009
1010static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1011 SourceLocation Loc,
1012 bool RefersToCapture = false) {
1013 D->setReferenced();
1014 D->markUsed(S.Context);
1015 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1016 SourceLocation(), D, RefersToCapture, Loc, Ty,
1017 VK_LValue);
1018}
1019
Alexey Bataeve3727102018-04-18 15:57:46 +00001020void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001021 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001022 D = getCanonicalDecl(D);
1023 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001024 assert(
Richard Trieu09f14112017-07-21 21:29:35 +00001025 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001026 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +00001027 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001028 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001029 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001030 "Additional reduction info may be specified only once for reduction "
1031 "items.");
1032 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001033 Expr *&TaskgroupReductionRef =
1034 Stack.back().first.back().TaskgroupReductionRef;
1035 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001036 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1037 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001038 TaskgroupReductionRef =
1039 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001040 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001041}
1042
Alexey Bataeve3727102018-04-18 15:57:46 +00001043void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001044 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001045 D = getCanonicalDecl(D);
1046 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001047 assert(
Richard Trieu09f14112017-07-21 21:29:35 +00001048 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001049 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +00001050 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001051 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001052 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001053 "Additional reduction info may be specified only once for reduction "
1054 "items.");
1055 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001056 Expr *&TaskgroupReductionRef =
1057 Stack.back().first.back().TaskgroupReductionRef;
1058 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001059 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1060 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001061 TaskgroupReductionRef =
1062 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001063 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001064}
1065
Alexey Bataeve3727102018-04-18 15:57:46 +00001066const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1067 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1068 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001069 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001070 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1071 if (Stack.back().first.empty())
1072 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001073 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1074 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001075 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001076 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001077 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001078 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001079 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001080 if (!ReductionData.ReductionOp ||
1081 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001082 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001083 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001084 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001085 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1086 "expression for the descriptor is not "
1087 "set.");
1088 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001089 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1090 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001091 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001092 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001093}
1094
Alexey Bataeve3727102018-04-18 15:57:46 +00001095const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1096 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1097 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001098 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001099 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1100 if (Stack.back().first.empty())
1101 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001102 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1103 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001104 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001105 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001106 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001107 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001108 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001109 if (!ReductionData.ReductionOp ||
1110 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001111 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001112 SR = ReductionData.ReductionRange;
1113 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001114 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1115 "expression for the descriptor is not "
1116 "set.");
1117 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001118 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1119 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001120 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001121 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001122}
1123
Alexey Bataeve3727102018-04-18 15:57:46 +00001124bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001125 D = D->getCanonicalDecl();
Alexey Bataev852525d2018-03-02 17:17:12 +00001126 if (!isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001127 iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001128 Scope *TopScope = nullptr;
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001129 while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) &&
Alexey Bataev852525d2018-03-02 17:17:12 +00001130 !isOpenMPTargetExecutionDirective(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +00001131 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +00001132 if (I == E)
1133 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001134 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001135 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001136 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +00001137 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +00001138 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001139 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001140 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001141}
1142
Joel E. Dennyd2649292019-01-04 22:11:56 +00001143static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1144 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001145 bool *IsClassType = nullptr) {
1146 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001147 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001148 bool IsConstant = Type.isConstant(Context);
1149 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001150 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1151 ? Type->getAsCXXRecordDecl()
1152 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001153 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1154 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1155 RD = CTD->getTemplatedDecl();
1156 if (IsClassType)
1157 *IsClassType = RD;
1158 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1159 RD->hasDefinition() && RD->hasMutableFields());
1160}
1161
Joel E. Dennyd2649292019-01-04 22:11:56 +00001162static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1163 QualType Type, OpenMPClauseKind CKind,
1164 SourceLocation ELoc,
1165 bool AcceptIfMutable = true,
1166 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001167 ASTContext &Context = SemaRef.getASTContext();
1168 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001169 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1170 unsigned Diag = ListItemNotVar
1171 ? diag::err_omp_const_list_item
1172 : IsClassType ? diag::err_omp_const_not_mutable_variable
1173 : diag::err_omp_const_variable;
1174 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1175 if (!ListItemNotVar && D) {
1176 const VarDecl *VD = dyn_cast<VarDecl>(D);
1177 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1178 VarDecl::DeclarationOnly;
1179 SemaRef.Diag(D->getLocation(),
1180 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1181 << D;
1182 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001183 return true;
1184 }
1185 return false;
1186}
1187
Alexey Bataeve3727102018-04-18 15:57:46 +00001188const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1189 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001190 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001191 DSAVarData DVar;
1192
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001193 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001194 auto TI = Threadprivates.find(D);
1195 if (TI != Threadprivates.end()) {
1196 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001197 DVar.CKind = OMPC_threadprivate;
1198 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001199 }
1200 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001201 DVar.RefExpr = buildDeclRefExpr(
1202 SemaRef, VD, D->getType().getNonReferenceType(),
1203 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1204 DVar.CKind = OMPC_threadprivate;
1205 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001206 return DVar;
1207 }
1208 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1209 // in a Construct, C/C++, predetermined, p.1]
1210 // Variables appearing in threadprivate directives are threadprivate.
1211 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1212 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1213 SemaRef.getLangOpts().OpenMPUseTLS &&
1214 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1215 (VD && VD->getStorageClass() == SC_Register &&
1216 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1217 DVar.RefExpr = buildDeclRefExpr(
1218 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1219 DVar.CKind = OMPC_threadprivate;
1220 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1221 return DVar;
1222 }
1223 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1224 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1225 !isLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001226 iterator IterTarget =
Alexey Bataev852525d2018-03-02 17:17:12 +00001227 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
1228 [](const SharingMapTy &Data) {
1229 return isOpenMPTargetExecutionDirective(Data.Directive);
1230 });
1231 if (IterTarget != Stack.back().first.rend()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001232 iterator ParentIterTarget = std::next(IterTarget, 1);
1233 for (iterator Iter = Stack.back().first.rbegin();
1234 Iter != ParentIterTarget; std::advance(Iter, 1)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001235 if (isOpenMPLocal(VD, Iter)) {
1236 DVar.RefExpr =
1237 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1238 D->getLocation());
1239 DVar.CKind = OMPC_threadprivate;
1240 return DVar;
1241 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001242 }
1243 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1244 auto DSAIter = IterTarget->SharingMap.find(D);
1245 if (DSAIter != IterTarget->SharingMap.end() &&
1246 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1247 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1248 DVar.CKind = OMPC_threadprivate;
1249 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001250 }
1251 iterator End = Stack.back().first.rend();
1252 if (!SemaRef.isOpenMPCapturedByRef(
1253 D, std::distance(ParentIterTarget, End))) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001254 DVar.RefExpr =
1255 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1256 IterTarget->ConstructLoc);
1257 DVar.CKind = OMPC_threadprivate;
1258 return DVar;
1259 }
1260 }
1261 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001262 }
1263
Alexey Bataev4b465392017-04-26 15:06:24 +00001264 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001265 // Not in OpenMP execution region and top scope was already checked.
1266 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001267
Alexey Bataev758e55e2013-09-06 18:03:48 +00001268 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001269 // in a Construct, C/C++, predetermined, p.4]
1270 // Static data members are shared.
1271 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1272 // in a Construct, C/C++, predetermined, p.7]
1273 // Variables with static storage duration that are declared in a scope
1274 // inside the construct are shared.
Alexey Bataeve3727102018-04-18 15:57:46 +00001275 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001276 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001277 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001278 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +00001279 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001280
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001281 DVar.CKind = OMPC_shared;
1282 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001283 }
1284
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001285 // The predetermined shared attribute for const-qualified types having no
1286 // mutable members was removed after OpenMP 3.1.
1287 if (SemaRef.LangOpts.OpenMP <= 31) {
1288 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1289 // in a Construct, C/C++, predetermined, p.6]
1290 // Variables with const qualified type having no mutable member are
1291 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001292 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001293 // Variables with const-qualified type having no mutable member may be
1294 // listed in a firstprivate clause, even if they are static data members.
1295 DSAVarData DVarTemp = hasInnermostDSA(
1296 D,
1297 [](OpenMPClauseKind C) {
1298 return C == OMPC_firstprivate || C == OMPC_shared;
1299 },
1300 MatchesAlways, FromParent);
1301 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1302 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001303
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001304 DVar.CKind = OMPC_shared;
1305 return DVar;
1306 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001307 }
1308
Alexey Bataev758e55e2013-09-06 18:03:48 +00001309 // Explicitly specified attributes and local variables with predetermined
1310 // attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +00001311 iterator I = Stack.back().first.rbegin();
1312 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001313 if (FromParent && I != EndI)
1314 std::advance(I, 1);
Alexey Bataeve3727102018-04-18 15:57:46 +00001315 auto It = I->SharingMap.find(D);
1316 if (It != I->SharingMap.end()) {
1317 const DSAInfo &Data = It->getSecond();
1318 DVar.RefExpr = Data.RefExpr.getPointer();
1319 DVar.PrivateCopy = Data.PrivateCopy;
1320 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001321 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001322 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001323 }
1324
1325 return DVar;
1326}
1327
Alexey Bataeve3727102018-04-18 15:57:46 +00001328const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1329 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001330 if (isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001331 iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001332 return getDSA(I, D);
1333 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001334 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001335 iterator StartI = Stack.back().first.rbegin();
1336 iterator EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001337 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001338 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001339 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001340}
1341
Alexey Bataeve3727102018-04-18 15:57:46 +00001342const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001343DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001344 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1345 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001346 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001347 if (isStackEmpty())
1348 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001349 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001350 iterator I = Stack.back().first.rbegin();
1351 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001352 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001353 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001354 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001355 if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001356 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001357 iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001358 DSAVarData DVar = getDSA(NewI, D);
1359 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001360 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001361 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001362 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001363}
1364
Alexey Bataeve3727102018-04-18 15:57:46 +00001365const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001366 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1367 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001368 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001369 if (isStackEmpty())
1370 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001371 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001372 iterator StartI = Stack.back().first.rbegin();
1373 iterator EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001374 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001375 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001376 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001377 return {};
Alexey Bataeve3727102018-04-18 15:57:46 +00001378 iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001379 DSAVarData DVar = getDSA(NewI, D);
1380 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001381}
1382
Alexey Bataevaac108a2015-06-23 04:51:00 +00001383bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001384 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1385 unsigned Level, bool NotLastprivate) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001386 if (isStackEmpty())
1387 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001388 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001389 auto StartI = Stack.back().first.begin();
1390 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001391 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001392 return false;
1393 std::advance(StartI, Level);
Alexey Bataeve3727102018-04-18 15:57:46 +00001394 auto I = StartI->SharingMap.find(D);
Alexey Bataev92b33652018-11-21 19:41:10 +00001395 if ((I != StartI->SharingMap.end()) &&
Alexey Bataeve3727102018-04-18 15:57:46 +00001396 I->getSecond().RefExpr.getPointer() &&
1397 CPred(I->getSecond().Attributes) &&
Alexey Bataev92b33652018-11-21 19:41:10 +00001398 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1399 return true;
1400 // Check predetermined rules for the loop control variables.
1401 auto LI = StartI->LCVMap.find(D);
1402 if (LI != StartI->LCVMap.end())
1403 return CPred(OMPC_private);
1404 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001405}
1406
Samuel Antao4be30e92015-10-02 17:14:03 +00001407bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001408 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1409 unsigned Level) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001410 if (isStackEmpty())
1411 return false;
1412 auto StartI = Stack.back().first.begin();
1413 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001414 if (std::distance(StartI, EndI) <= (int)Level)
1415 return false;
1416 std::advance(StartI, Level);
1417 return DPred(StartI->Directive);
1418}
1419
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001420bool DSAStackTy::hasDirective(
1421 const llvm::function_ref<bool(OpenMPDirectiveKind,
1422 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001423 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001424 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001425 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001426 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001427 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001428 auto StartI = std::next(Stack.back().first.rbegin());
1429 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001430 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001431 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001432 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1433 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1434 return true;
1435 }
1436 return false;
1437}
1438
Alexey Bataev758e55e2013-09-06 18:03:48 +00001439void Sema::InitDataSharingAttributesStack() {
1440 VarDataSharingAttributesStack = new DSAStackTy(*this);
1441}
1442
1443#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1444
Alexey Bataev4b465392017-04-26 15:06:24 +00001445void Sema::pushOpenMPFunctionRegion() {
1446 DSAStack->pushFunction();
1447}
1448
1449void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1450 DSAStack->popFunction(OldFSI);
1451}
1452
Alexey Bataevc416e642019-02-08 18:02:25 +00001453static bool isOpenMPDeviceDelayedContext(Sema &S) {
1454 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1455 "Expected OpenMP device compilation.");
1456 return !S.isInOpenMPTargetExecutionDirective() &&
1457 !S.isInOpenMPDeclareTargetContext();
1458}
1459
1460/// Do we know that we will eventually codegen the given function?
1461static bool isKnownEmitted(Sema &S, FunctionDecl *FD) {
1462 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1463 "Expected OpenMP device compilation.");
1464 // Templates are emitted when they're instantiated.
1465 if (FD->isDependentContext())
1466 return false;
1467
1468 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1469 FD->getCanonicalDecl()))
1470 return true;
1471
1472 // Otherwise, the function is known-emitted if it's in our set of
1473 // known-emitted functions.
1474 return S.DeviceKnownEmittedFns.count(FD) > 0;
1475}
1476
1477Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1478 unsigned DiagID) {
1479 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1480 "Expected OpenMP device compilation.");
1481 return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) &&
1482 !isKnownEmitted(*this, getCurFunctionDecl()))
1483 ? DeviceDiagBuilder::K_Deferred
1484 : DeviceDiagBuilder::K_Immediate,
1485 Loc, DiagID, getCurFunctionDecl(), *this);
1486}
1487
1488void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) {
1489 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1490 "Expected OpenMP device compilation.");
1491 assert(Callee && "Callee may not be null.");
1492 FunctionDecl *Caller = getCurFunctionDecl();
1493
1494 // If the caller is known-emitted, mark the callee as known-emitted.
1495 // Otherwise, mark the call in our call graph so we can traverse it later.
1496 if (!isOpenMPDeviceDelayedContext(*this) ||
1497 (Caller && isKnownEmitted(*this, Caller)))
1498 markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted);
1499 else if (Caller)
1500 DeviceCallGraph[Caller].insert({Callee, Loc});
1501}
1502
Alexey Bataev123ad192019-02-27 20:29:45 +00001503void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1504 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1505 "OpenMP device compilation mode is expected.");
1506 QualType Ty = E->getType();
1507 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
1508 (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
1509 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1510 !Context.getTargetInfo().hasInt128Type()))
1511 targetDiag(E->getExprLoc(), diag::err_type_unsupported)
1512 << Ty << E->getSourceRange();
1513}
1514
Alexey Bataeve3727102018-04-18 15:57:46 +00001515bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001516 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1517
Alexey Bataeve3727102018-04-18 15:57:46 +00001518 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001519 bool IsByRef = true;
1520
1521 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001522 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001523 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001524
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001525 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001526 // This table summarizes how a given variable should be passed to the device
1527 // given its type and the clauses where it appears. This table is based on
1528 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1529 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1530 //
1531 // =========================================================================
1532 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1533 // | |(tofrom:scalar)| | pvt | | | |
1534 // =========================================================================
1535 // | scl | | | | - | | bycopy|
1536 // | scl | | - | x | - | - | bycopy|
1537 // | scl | | x | - | - | - | null |
1538 // | scl | x | | | - | | byref |
1539 // | scl | x | - | x | - | - | bycopy|
1540 // | scl | x | x | - | - | - | null |
1541 // | scl | | - | - | - | x | byref |
1542 // | scl | x | - | - | - | x | byref |
1543 //
1544 // | agg | n.a. | | | - | | byref |
1545 // | agg | n.a. | - | x | - | - | byref |
1546 // | agg | n.a. | x | - | - | - | null |
1547 // | agg | n.a. | - | - | - | x | byref |
1548 // | agg | n.a. | - | - | - | x[] | byref |
1549 //
1550 // | ptr | n.a. | | | - | | bycopy|
1551 // | ptr | n.a. | - | x | - | - | bycopy|
1552 // | ptr | n.a. | x | - | - | - | null |
1553 // | ptr | n.a. | - | - | - | x | byref |
1554 // | ptr | n.a. | - | - | - | x[] | bycopy|
1555 // | ptr | n.a. | - | - | x | | bycopy|
1556 // | ptr | n.a. | - | - | x | x | bycopy|
1557 // | ptr | n.a. | - | - | x | x[] | bycopy|
1558 // =========================================================================
1559 // Legend:
1560 // scl - scalar
1561 // ptr - pointer
1562 // agg - aggregate
1563 // x - applies
1564 // - - invalid in this combination
1565 // [] - mapped with an array section
1566 // byref - should be mapped by reference
1567 // byval - should be mapped by value
1568 // null - initialize a local variable to null on the device
1569 //
1570 // Observations:
1571 // - All scalar declarations that show up in a map clause have to be passed
1572 // by reference, because they may have been mapped in the enclosing data
1573 // environment.
1574 // - If the scalar value does not fit the size of uintptr, it has to be
1575 // passed by reference, regardless the result in the table above.
1576 // - For pointers mapped by value that have either an implicit map or an
1577 // array section, the runtime library may pass the NULL value to the
1578 // device instead of the value passed to it by the compiler.
1579
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001580 if (Ty->isReferenceType())
1581 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001582
1583 // Locate map clauses and see if the variable being captured is referred to
1584 // in any of those clauses. Here we only care about variables, not fields,
1585 // because fields are part of aggregates.
1586 bool IsVariableUsedInMapClause = false;
1587 bool IsVariableAssociatedWithSection = false;
1588
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001589 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001590 D, Level,
1591 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1592 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001593 MapExprComponents,
1594 OpenMPClauseKind WhereFoundClauseKind) {
1595 // Only the map clause information influences how a variable is
1596 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001597 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001598 if (WhereFoundClauseKind != OMPC_map)
1599 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001600
1601 auto EI = MapExprComponents.rbegin();
1602 auto EE = MapExprComponents.rend();
1603
1604 assert(EI != EE && "Invalid map expression!");
1605
1606 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1607 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1608
1609 ++EI;
1610 if (EI == EE)
1611 return false;
1612
1613 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1614 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1615 isa<MemberExpr>(EI->getAssociatedExpression())) {
1616 IsVariableAssociatedWithSection = true;
1617 // There is nothing more we need to know about this variable.
1618 return true;
1619 }
1620
1621 // Keep looking for more map info.
1622 return false;
1623 });
1624
1625 if (IsVariableUsedInMapClause) {
1626 // If variable is identified in a map clause it is always captured by
1627 // reference except if it is a pointer that is dereferenced somehow.
1628 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1629 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001630 // By default, all the data that has a scalar type is mapped by copy
1631 // (except for reduction variables).
1632 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001633 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1634 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001635 !Ty->isScalarType() ||
1636 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1637 DSAStack->hasExplicitDSA(
1638 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001639 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001640 }
1641
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001642 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001643 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001644 ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1645 !Ty->isAnyPointerType()) ||
1646 !DSAStack->hasExplicitDSA(
1647 D,
1648 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1649 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001650 // If the variable is artificial and must be captured by value - try to
1651 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001652 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1653 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001654 }
1655
Samuel Antao86ace552016-04-27 22:40:57 +00001656 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001657 // and alignment, because the runtime library only deals with uintptr types.
1658 // If it does not fit the uintptr size, we need to pass the data by reference
1659 // instead.
1660 if (!IsByRef &&
1661 (Ctx.getTypeSizeInChars(Ty) >
1662 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001663 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001664 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001665 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001666
1667 return IsByRef;
1668}
1669
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001670unsigned Sema::getOpenMPNestingLevel() const {
1671 assert(getLangOpts().OpenMP);
1672 return DSAStack->getNestingLevel();
1673}
1674
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001675bool Sema::isInOpenMPTargetExecutionDirective() const {
1676 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1677 !DSAStack->isClauseParsingMode()) ||
1678 DSAStack->hasDirective(
1679 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1680 SourceLocation) -> bool {
1681 return isOpenMPTargetExecutionDirective(K);
1682 },
1683 false);
1684}
1685
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001686VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001687 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001688 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001689
1690 // If we are attempting to capture a global variable in a directive with
1691 // 'target' we return true so that this global is also mapped to the device.
1692 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001693 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001694 if (VD && !VD->hasLocalStorage()) {
1695 if (isInOpenMPDeclareTargetContext() &&
1696 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1697 // Try to mark variable as declare target if it is used in capturing
1698 // regions.
Alexey Bataev97b72212018-08-14 18:31:20 +00001699 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001700 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001701 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001702 } else if (isInOpenMPTargetExecutionDirective()) {
1703 // If the declaration is enclosed in a 'declare target' directive,
1704 // then it should not be captured.
1705 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001706 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001707 return nullptr;
1708 return VD;
1709 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001710 }
Alexey Bataev60705422018-10-30 15:50:12 +00001711 // Capture variables captured by reference in lambdas for target-based
1712 // directives.
1713 if (VD && !DSAStack->isClauseParsingMode()) {
1714 if (const auto *RD = VD->getType()
1715 .getCanonicalType()
1716 .getNonReferenceType()
1717 ->getAsCXXRecordDecl()) {
1718 bool SavedForceCaptureByReferenceInTargetExecutable =
1719 DSAStack->isForceCaptureByReferenceInTargetExecutable();
1720 DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
Alexey Bataevd1840e52018-11-16 21:13:33 +00001721 if (RD->isLambda()) {
1722 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
1723 FieldDecl *ThisCapture;
1724 RD->getCaptureFields(Captures, ThisCapture);
Alexey Bataev60705422018-10-30 15:50:12 +00001725 for (const LambdaCapture &LC : RD->captures()) {
1726 if (LC.getCaptureKind() == LCK_ByRef) {
1727 VarDecl *VD = LC.getCapturedVar();
1728 DeclContext *VDC = VD->getDeclContext();
1729 if (!VDC->Encloses(CurContext))
1730 continue;
1731 DSAStackTy::DSAVarData DVarPrivate =
1732 DSAStack->getTopDSA(VD, /*FromParent=*/false);
1733 // Do not capture already captured variables.
1734 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
1735 DVarPrivate.CKind == OMPC_unknown &&
1736 !DSAStack->checkMappableExprComponentListsForDecl(
1737 D, /*CurrentRegionOnly=*/true,
1738 [](OMPClauseMappableExprCommon::
1739 MappableExprComponentListRef,
1740 OpenMPClauseKind) { return true; }))
1741 MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
1742 } else if (LC.getCaptureKind() == LCK_This) {
Alexey Bataevd1840e52018-11-16 21:13:33 +00001743 QualType ThisTy = getCurrentThisType();
1744 if (!ThisTy.isNull() &&
1745 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
1746 CheckCXXThisCapture(LC.getLocation());
Alexey Bataev60705422018-10-30 15:50:12 +00001747 }
1748 }
Alexey Bataevd1840e52018-11-16 21:13:33 +00001749 }
Alexey Bataev60705422018-10-30 15:50:12 +00001750 DSAStack->setForceCaptureByReferenceInTargetExecutable(
1751 SavedForceCaptureByReferenceInTargetExecutable);
1752 }
1753 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001754
Alexey Bataev48977c32015-08-04 08:10:48 +00001755 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1756 (!DSAStack->isClauseParsingMode() ||
1757 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001758 auto &&Info = DSAStack->isLoopControlVariable(D);
1759 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001760 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001761 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001762 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001763 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001764 DSAStackTy::DSAVarData DVarPrivate =
1765 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001766 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001767 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001768 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1769 [](OpenMPDirectiveKind) { return true; },
1770 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001771 if (DVarPrivate.CKind != OMPC_unknown)
1772 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001773 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001774 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001775}
1776
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001777void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1778 unsigned Level) const {
1779 SmallVector<OpenMPDirectiveKind, 4> Regions;
1780 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1781 FunctionScopesIndex -= Regions.size();
1782}
1783
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001784void Sema::startOpenMPLoop() {
1785 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1786 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1787 DSAStack->loopInit();
1788}
1789
Alexey Bataeve3727102018-04-18 15:57:46 +00001790bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001791 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001792 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1793 if (DSAStack->getAssociatedLoops() > 0 &&
1794 !DSAStack->isLoopStarted()) {
1795 DSAStack->resetPossibleLoopCounter(D);
1796 DSAStack->loopStart();
1797 return true;
1798 }
1799 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1800 DSAStack->isLoopControlVariable(D).first) &&
1801 !DSAStack->hasExplicitDSA(
1802 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1803 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
1804 return true;
1805 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00001806 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001807 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001808 (DSAStack->isClauseParsingMode() &&
1809 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001810 // Consider taskgroup reduction descriptor variable a private to avoid
1811 // possible capture in the region.
1812 (DSAStack->hasExplicitDirective(
1813 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1814 Level) &&
1815 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001816}
1817
Alexey Bataeve3727102018-04-18 15:57:46 +00001818void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1819 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001820 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1821 D = getCanonicalDecl(D);
1822 OpenMPClauseKind OMPC = OMPC_unknown;
1823 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1824 const unsigned NewLevel = I - 1;
1825 if (DSAStack->hasExplicitDSA(D,
1826 [&OMPC](const OpenMPClauseKind K) {
1827 if (isOpenMPPrivate(K)) {
1828 OMPC = K;
1829 return true;
1830 }
1831 return false;
1832 },
1833 NewLevel))
1834 break;
1835 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1836 D, NewLevel,
1837 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1838 OpenMPClauseKind) { return true; })) {
1839 OMPC = OMPC_map;
1840 break;
1841 }
1842 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1843 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001844 OMPC = OMPC_map;
1845 if (D->getType()->isScalarType() &&
1846 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1847 DefaultMapAttributes::DMA_tofrom_scalar)
1848 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001849 break;
1850 }
1851 }
1852 if (OMPC != OMPC_unknown)
1853 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1854}
1855
Alexey Bataeve3727102018-04-18 15:57:46 +00001856bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1857 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00001858 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1859 // Return true if the current level is no longer enclosed in a target region.
1860
Alexey Bataeve3727102018-04-18 15:57:46 +00001861 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001862 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001863 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1864 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001865}
1866
Alexey Bataeved09d242014-05-28 05:53:51 +00001867void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001868
1869void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1870 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001871 Scope *CurScope, SourceLocation Loc) {
1872 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001873 PushExpressionEvaluationContext(
1874 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001875}
1876
Alexey Bataevaac108a2015-06-23 04:51:00 +00001877void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1878 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001879}
1880
Alexey Bataevaac108a2015-06-23 04:51:00 +00001881void Sema::EndOpenMPClause() {
1882 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001883}
1884
Alexey Bataev758e55e2013-09-06 18:03:48 +00001885void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001886 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1887 // A variable of class type (or array thereof) that appears in a lastprivate
1888 // clause requires an accessible, unambiguous default constructor for the
1889 // class type, unless the list item is also specified in a firstprivate
1890 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001891 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1892 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001893 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1894 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00001895 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001896 if (DE->isValueDependent() || DE->isTypeDependent()) {
1897 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001898 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001899 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001900 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00001901 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00001902 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00001903 const DSAStackTy::DSAVarData DVar =
1904 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001905 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001906 // Generate helper private variable and initialize it with the
1907 // default value. The address of the original variable is replaced
1908 // by the address of the new private variable in CodeGen. This new
1909 // variable is not added to IdResolver, so the code in the OpenMP
1910 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00001911 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001912 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001913 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00001914 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001915 if (VDPrivate->isInvalidDecl())
1916 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001917 PrivateCopies.push_back(buildDeclRefExpr(
1918 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001919 } else {
1920 // The variable is also a firstprivate, so initialization sequence
1921 // for private copy is generated already.
1922 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001923 }
1924 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001925 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001926 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001927 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001928 }
1929 }
1930 }
1931
Alexey Bataev758e55e2013-09-06 18:03:48 +00001932 DSAStack->pop();
1933 DiscardCleanupsInEvaluationContext();
1934 PopExpressionEvaluationContext();
1935}
1936
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001937static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1938 Expr *NumIterations, Sema &SemaRef,
1939 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001940
Alexey Bataeva769e072013-03-22 06:34:35 +00001941namespace {
1942
Alexey Bataeve3727102018-04-18 15:57:46 +00001943class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001944private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001945 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001946
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001947public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001948 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001949 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001950 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00001951 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001952 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001953 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1954 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001955 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001956 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001957 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001958};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001959
Alexey Bataeve3727102018-04-18 15:57:46 +00001960class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001961private:
1962 Sema &SemaRef;
1963
1964public:
1965 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1966 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1967 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001968 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
1969 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001970 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1971 SemaRef.getCurScope());
1972 }
1973 return false;
1974 }
1975};
1976
Alexey Bataeved09d242014-05-28 05:53:51 +00001977} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001978
1979ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1980 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001981 const DeclarationNameInfo &Id,
1982 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001983 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1984 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1985
1986 if (Lookup.isAmbiguous())
1987 return ExprError();
1988
1989 VarDecl *VD;
1990 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001991 if (TypoCorrection Corrected = CorrectTypo(
1992 Id, LookupOrdinaryName, CurScope, nullptr,
1993 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001994 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001995 PDiag(Lookup.empty()
1996 ? diag::err_undeclared_var_use_suggest
1997 : diag::err_omp_expected_var_arg_suggest)
1998 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001999 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002000 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002001 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2002 : diag::err_omp_expected_var_arg)
2003 << Id.getName();
2004 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002005 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002006 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2007 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2008 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2009 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002010 }
2011 Lookup.suppressDiagnostics();
2012
2013 // OpenMP [2.9.2, Syntax, C/C++]
2014 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002015 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002016 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002017 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002018 bool IsDecl =
2019 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002020 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002021 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2022 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002023 return ExprError();
2024 }
2025
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002026 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002027 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002028 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2029 // A threadprivate directive for file-scope variables must appear outside
2030 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002031 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2032 !getCurLexicalContext()->isTranslationUnit()) {
2033 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002034 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002035 bool IsDecl =
2036 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2037 Diag(VD->getLocation(),
2038 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2039 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002040 return ExprError();
2041 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002042 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2043 // A threadprivate directive for static class member variables must appear
2044 // in the class definition, in the same scope in which the member
2045 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002046 if (CanonicalVD->isStaticDataMember() &&
2047 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2048 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002049 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002050 bool IsDecl =
2051 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2052 Diag(VD->getLocation(),
2053 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2054 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002055 return ExprError();
2056 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002057 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2058 // A threadprivate directive for namespace-scope variables must appear
2059 // outside any definition or declaration other than the namespace
2060 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002061 if (CanonicalVD->getDeclContext()->isNamespace() &&
2062 (!getCurLexicalContext()->isFileContext() ||
2063 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2064 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002065 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002066 bool IsDecl =
2067 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2068 Diag(VD->getLocation(),
2069 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2070 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002071 return ExprError();
2072 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002073 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2074 // A threadprivate directive for static block-scope variables must appear
2075 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002076 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002077 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002078 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002079 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002080 bool IsDecl =
2081 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2082 Diag(VD->getLocation(),
2083 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2084 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002085 return ExprError();
2086 }
2087
2088 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2089 // A threadprivate directive must lexically precede all references to any
2090 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002091 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2092 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002093 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002094 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002095 return ExprError();
2096 }
2097
2098 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002099 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2100 SourceLocation(), VD,
2101 /*RefersToEnclosingVariableOrCapture=*/false,
2102 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002103}
2104
Alexey Bataeved09d242014-05-28 05:53:51 +00002105Sema::DeclGroupPtrTy
2106Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2107 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002108 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002109 CurContext->addDecl(D);
2110 return DeclGroupPtrTy::make(DeclGroupRef(D));
2111 }
David Blaikie0403cb12016-01-15 23:43:25 +00002112 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002113}
2114
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002115namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002116class LocalVarRefChecker final
2117 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002118 Sema &SemaRef;
2119
2120public:
2121 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002122 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002123 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002124 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002125 diag::err_omp_local_var_in_threadprivate_init)
2126 << E->getSourceRange();
2127 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2128 << VD << VD->getSourceRange();
2129 return true;
2130 }
2131 }
2132 return false;
2133 }
2134 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002135 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002136 if (Child && Visit(Child))
2137 return true;
2138 }
2139 return false;
2140 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002141 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002142};
2143} // namespace
2144
Alexey Bataeved09d242014-05-28 05:53:51 +00002145OMPThreadPrivateDecl *
2146Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002147 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002148 for (Expr *RefExpr : VarList) {
2149 auto *DE = cast<DeclRefExpr>(RefExpr);
2150 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002151 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002152
Alexey Bataev376b4a42016-02-09 09:41:09 +00002153 // Mark variable as used.
2154 VD->setReferenced();
2155 VD->markUsed(Context);
2156
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002157 QualType QType = VD->getType();
2158 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2159 // It will be analyzed later.
2160 Vars.push_back(DE);
2161 continue;
2162 }
2163
Alexey Bataeva769e072013-03-22 06:34:35 +00002164 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2165 // A threadprivate variable must not have an incomplete type.
2166 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002167 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002168 continue;
2169 }
2170
2171 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2172 // A threadprivate variable must not have a reference type.
2173 if (VD->getType()->isReferenceType()) {
2174 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002175 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2176 bool IsDecl =
2177 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2178 Diag(VD->getLocation(),
2179 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2180 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002181 continue;
2182 }
2183
Samuel Antaof8b50122015-07-13 22:54:53 +00002184 // Check if this is a TLS variable. If TLS is not being supported, produce
2185 // the corresponding diagnostic.
2186 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2187 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2188 getLangOpts().OpenMPUseTLS &&
2189 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002190 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2191 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002192 Diag(ILoc, diag::err_omp_var_thread_local)
2193 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002194 bool IsDecl =
2195 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2196 Diag(VD->getLocation(),
2197 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2198 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002199 continue;
2200 }
2201
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002202 // Check if initial value of threadprivate variable reference variable with
2203 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002204 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002205 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002206 if (Checker.Visit(Init))
2207 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002208 }
2209
Alexey Bataeved09d242014-05-28 05:53:51 +00002210 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002211 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002212 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2213 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002214 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002215 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002216 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002217 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002218 if (!Vars.empty()) {
2219 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2220 Vars);
2221 D->setAccess(AS_public);
2222 }
2223 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002224}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002225
Alexey Bataev27ef9512019-03-20 20:14:22 +00002226static OMPAllocateDeclAttr::AllocatorTypeTy
2227getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2228 if (!Allocator)
2229 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2230 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2231 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002232 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002233 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002234 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
2235 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2236 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2237 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
2238 Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002239 const Expr *AE = Allocator->IgnoreParenImpCasts();
2240 llvm::FoldingSetNodeID AEId, DAEId;
2241 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2242 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2243 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002244 AllocatorKindRes = AllocatorKind;
2245 break;
2246 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002247 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002248 return AllocatorKindRes;
2249}
2250
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002251Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2252 SourceLocation Loc, ArrayRef<Expr *> VarList,
2253 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2254 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2255 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002256 if (Clauses.empty()) {
Alexey Bataev318f431b2019-03-22 15:25:12 +00002257 if (LangOpts.OpenMPIsDevice &&
2258 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002259 targetDiag(Loc, diag::err_expected_allocator_clause);
2260 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002261 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002262 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002263 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2264 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002265 SmallVector<Expr *, 8> Vars;
2266 for (Expr *RefExpr : VarList) {
2267 auto *DE = cast<DeclRefExpr>(RefExpr);
2268 auto *VD = cast<VarDecl>(DE->getDecl());
2269
2270 // Check if this is a TLS variable or global register.
2271 if (VD->getTLSKind() != VarDecl::TLS_None ||
2272 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2273 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2274 !VD->isLocalVarDecl()))
2275 continue;
2276 // Do not apply for parameters.
2277 if (isa<ParmVarDecl>(VD))
2278 continue;
2279
Alexey Bataev282555a2019-03-19 20:33:44 +00002280 // If the used several times in the allocate directive, the same allocator
2281 // must be used.
2282 if (VD->hasAttr<OMPAllocateDeclAttr>()) {
2283 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002284 Expr *PrevAllocator = A->getAllocator();
2285 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2286 getAllocatorKind(*this, DSAStack, PrevAllocator);
2287 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2288 if (AllocatorsMatch && Allocator && PrevAllocator) {
Alexey Bataev282555a2019-03-19 20:33:44 +00002289 const Expr *AE = Allocator->IgnoreParenImpCasts();
2290 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2291 llvm::FoldingSetNodeID AEId, PAEId;
2292 AE->Profile(AEId, Context, /*Canonical=*/true);
2293 PAE->Profile(PAEId, Context, /*Canonical=*/true);
2294 AllocatorsMatch = AEId == PAEId;
Alexey Bataev282555a2019-03-19 20:33:44 +00002295 }
2296 if (!AllocatorsMatch) {
2297 SmallString<256> AllocatorBuffer;
2298 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2299 if (Allocator)
2300 Allocator->printPretty(AllocatorStream, nullptr, getPrintingPolicy());
2301 SmallString<256> PrevAllocatorBuffer;
2302 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2303 if (PrevAllocator)
2304 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2305 getPrintingPolicy());
2306
2307 SourceLocation AllocatorLoc =
2308 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2309 SourceRange AllocatorRange =
2310 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2311 SourceLocation PrevAllocatorLoc =
2312 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2313 SourceRange PrevAllocatorRange =
2314 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2315 Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2316 << (Allocator ? 1 : 0) << AllocatorStream.str()
2317 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2318 << AllocatorRange;
2319 Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2320 << PrevAllocatorRange;
2321 continue;
2322 }
2323 }
2324
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002325 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2326 // If a list item has a static storage type, the allocator expression in the
2327 // allocator clause must be a constant expression that evaluates to one of
2328 // the predefined memory allocator values.
2329 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002330 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002331 Diag(Allocator->getExprLoc(),
2332 diag::err_omp_expected_predefined_allocator)
2333 << Allocator->getSourceRange();
2334 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2335 VarDecl::DeclarationOnly;
2336 Diag(VD->getLocation(),
2337 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2338 << VD;
2339 continue;
2340 }
2341 }
2342
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002343 Vars.push_back(RefExpr);
Alexey Bataev282555a2019-03-19 20:33:44 +00002344 if ((!Allocator || (Allocator && !Allocator->isTypeDependent() &&
2345 !Allocator->isValueDependent() &&
2346 !Allocator->isInstantiationDependent() &&
2347 !Allocator->containsUnexpandedParameterPack())) &&
2348 !VD->hasAttr<OMPAllocateDeclAttr>()) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002349 Attr *A = OMPAllocateDeclAttr::CreateImplicit(
2350 Context, AllocatorKind, Allocator, DE->getSourceRange());
Alexey Bataev282555a2019-03-19 20:33:44 +00002351 VD->addAttr(A);
2352 if (ASTMutationListener *ML = Context.getASTMutationListener())
2353 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2354 }
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002355 }
2356 if (Vars.empty())
2357 return nullptr;
2358 if (!Owner)
2359 Owner = getCurLexicalContext();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002360 OMPAllocateDecl *D =
2361 OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002362 D->setAccess(AS_public);
2363 Owner->addDecl(D);
2364 return DeclGroupPtrTy::make(DeclGroupRef(D));
2365}
2366
2367Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002368Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2369 ArrayRef<OMPClause *> ClauseList) {
2370 OMPRequiresDecl *D = nullptr;
2371 if (!CurContext->isFileContext()) {
2372 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2373 } else {
2374 D = CheckOMPRequiresDecl(Loc, ClauseList);
2375 if (D) {
2376 CurContext->addDecl(D);
2377 DSAStack->addRequiresDecl(D);
2378 }
2379 }
2380 return DeclGroupPtrTy::make(DeclGroupRef(D));
2381}
2382
2383OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2384 ArrayRef<OMPClause *> ClauseList) {
2385 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2386 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2387 ClauseList);
2388 return nullptr;
2389}
2390
Alexey Bataeve3727102018-04-18 15:57:46 +00002391static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2392 const ValueDecl *D,
2393 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002394 bool IsLoopIterVar = false) {
2395 if (DVar.RefExpr) {
2396 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2397 << getOpenMPClauseName(DVar.CKind);
2398 return;
2399 }
2400 enum {
2401 PDSA_StaticMemberShared,
2402 PDSA_StaticLocalVarShared,
2403 PDSA_LoopIterVarPrivate,
2404 PDSA_LoopIterVarLinear,
2405 PDSA_LoopIterVarLastprivate,
2406 PDSA_ConstVarShared,
2407 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002408 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002409 PDSA_LocalVarPrivate,
2410 PDSA_Implicit
2411 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002412 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002413 auto ReportLoc = D->getLocation();
2414 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002415 if (IsLoopIterVar) {
2416 if (DVar.CKind == OMPC_private)
2417 Reason = PDSA_LoopIterVarPrivate;
2418 else if (DVar.CKind == OMPC_lastprivate)
2419 Reason = PDSA_LoopIterVarLastprivate;
2420 else
2421 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002422 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2423 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002424 Reason = PDSA_TaskVarFirstprivate;
2425 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002426 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002427 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002428 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002429 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002430 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002431 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002432 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002433 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002434 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002435 ReportHint = true;
2436 Reason = PDSA_LocalVarPrivate;
2437 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002438 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002439 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002440 << Reason << ReportHint
2441 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2442 } else if (DVar.ImplicitDSALoc.isValid()) {
2443 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2444 << getOpenMPClauseName(DVar.CKind);
2445 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002446}
2447
Alexey Bataev758e55e2013-09-06 18:03:48 +00002448namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002449class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002450 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002451 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002452 bool ErrorFound = false;
2453 CapturedStmt *CS = nullptr;
2454 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2455 llvm::SmallVector<Expr *, 4> ImplicitMap;
2456 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2457 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002458
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002459 void VisitSubCaptures(OMPExecutableDirective *S) {
2460 // Check implicitly captured variables.
2461 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2462 return;
2463 for (const CapturedStmt::Capture &Cap :
2464 S->getInnermostCapturedStmt()->captures()) {
2465 if (!Cap.capturesVariable())
2466 continue;
2467 VarDecl *VD = Cap.getCapturedVar();
2468 // Do not try to map the variable if it or its sub-component was mapped
2469 // already.
2470 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2471 Stack->checkMappableExprComponentListsForDecl(
2472 VD, /*CurrentRegionOnly=*/true,
2473 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2474 OpenMPClauseKind) { return true; }))
2475 continue;
2476 DeclRefExpr *DRE = buildDeclRefExpr(
2477 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2478 Cap.getLocation(), /*RefersToCapture=*/true);
2479 Visit(DRE);
2480 }
2481 }
2482
Alexey Bataev758e55e2013-09-06 18:03:48 +00002483public:
2484 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002485 if (E->isTypeDependent() || E->isValueDependent() ||
2486 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2487 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002488 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002489 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002490 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002491 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002492 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002493
Alexey Bataeve3727102018-04-18 15:57:46 +00002494 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002495 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002496 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002497 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002498
Alexey Bataevafe50572017-10-06 17:00:28 +00002499 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002500 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002501 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002502 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2503 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002504 return;
2505
Alexey Bataeve3727102018-04-18 15:57:46 +00002506 SourceLocation ELoc = E->getExprLoc();
2507 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002508 // The default(none) clause requires that each variable that is referenced
2509 // in the construct, and does not have a predetermined data-sharing
2510 // attribute, must have its data-sharing attribute explicitly determined
2511 // by being listed in a data-sharing attribute clause.
2512 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002513 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002514 VarsWithInheritedDSA.count(VD) == 0) {
2515 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002516 return;
2517 }
2518
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002519 if (isOpenMPTargetExecutionDirective(DKind) &&
2520 !Stack->isLoopControlVariable(VD).first) {
2521 if (!Stack->checkMappableExprComponentListsForDecl(
2522 VD, /*CurrentRegionOnly=*/true,
2523 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2524 StackComponents,
2525 OpenMPClauseKind) {
2526 // Variable is used if it has been marked as an array, array
2527 // section or the variable iself.
2528 return StackComponents.size() == 1 ||
2529 std::all_of(
2530 std::next(StackComponents.rbegin()),
2531 StackComponents.rend(),
2532 [](const OMPClauseMappableExprCommon::
2533 MappableComponent &MC) {
2534 return MC.getAssociatedDeclaration() ==
2535 nullptr &&
2536 (isa<OMPArraySectionExpr>(
2537 MC.getAssociatedExpression()) ||
2538 isa<ArraySubscriptExpr>(
2539 MC.getAssociatedExpression()));
2540 });
2541 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002542 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002543 // By default lambdas are captured as firstprivates.
2544 if (const auto *RD =
2545 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002546 IsFirstprivate = RD->isLambda();
2547 IsFirstprivate =
2548 IsFirstprivate ||
2549 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002550 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002551 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002552 ImplicitFirstprivate.emplace_back(E);
2553 else
2554 ImplicitMap.emplace_back(E);
2555 return;
2556 }
2557 }
2558
Alexey Bataev758e55e2013-09-06 18:03:48 +00002559 // OpenMP [2.9.3.6, Restrictions, p.2]
2560 // A list item that appears in a reduction clause of the innermost
2561 // enclosing worksharing or parallel construct may not be accessed in an
2562 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002563 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002564 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2565 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002566 return isOpenMPParallelDirective(K) ||
2567 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2568 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002569 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002570 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002571 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002572 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002573 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002574 return;
2575 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002576
2577 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002578 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002579 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00002580 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002581 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00002582 return;
2583 }
2584
2585 // Store implicitly used globals with declare target link for parent
2586 // target.
2587 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2588 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2589 Stack->addToParentTargetRegionLinkGlobals(E);
2590 return;
2591 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002592 }
2593 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002594 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002595 if (E->isTypeDependent() || E->isValueDependent() ||
2596 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2597 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002598 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002599 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002600 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002601 if (!FD)
2602 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002603 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002604 // Check if the variable has explicit DSA set and stop analysis if it
2605 // so.
2606 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2607 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002608
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002609 if (isOpenMPTargetExecutionDirective(DKind) &&
2610 !Stack->isLoopControlVariable(FD).first &&
2611 !Stack->checkMappableExprComponentListsForDecl(
2612 FD, /*CurrentRegionOnly=*/true,
2613 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2614 StackComponents,
2615 OpenMPClauseKind) {
2616 return isa<CXXThisExpr>(
2617 cast<MemberExpr>(
2618 StackComponents.back().getAssociatedExpression())
2619 ->getBase()
2620 ->IgnoreParens());
2621 })) {
2622 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2623 // A bit-field cannot appear in a map clause.
2624 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002625 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002626 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002627
2628 // Check to see if the member expression is referencing a class that
2629 // has already been explicitly mapped
2630 if (Stack->isClassPreviouslyMapped(TE->getType()))
2631 return;
2632
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002633 ImplicitMap.emplace_back(E);
2634 return;
2635 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002636
Alexey Bataeve3727102018-04-18 15:57:46 +00002637 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002638 // OpenMP [2.9.3.6, Restrictions, p.2]
2639 // A list item that appears in a reduction clause of the innermost
2640 // enclosing worksharing or parallel construct may not be accessed in
2641 // an explicit task.
2642 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002643 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2644 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002645 return isOpenMPParallelDirective(K) ||
2646 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2647 },
2648 /*FromParent=*/true);
2649 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2650 ErrorFound = true;
2651 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002652 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002653 return;
2654 }
2655
2656 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002657 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002658 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002659 !Stack->isLoopControlVariable(FD).first) {
2660 // Check if there is a captured expression for the current field in the
2661 // region. Do not mark it as firstprivate unless there is no captured
2662 // expression.
2663 // TODO: try to make it firstprivate.
2664 if (DVar.CKind != OMPC_unknown)
2665 ImplicitFirstprivate.push_back(E);
2666 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002667 return;
2668 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002669 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002670 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002671 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002672 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002673 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002674 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002675 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2676 if (!Stack->checkMappableExprComponentListsForDecl(
2677 VD, /*CurrentRegionOnly=*/true,
2678 [&CurComponents](
2679 OMPClauseMappableExprCommon::MappableExprComponentListRef
2680 StackComponents,
2681 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002682 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002683 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002684 for (const auto &SC : llvm::reverse(StackComponents)) {
2685 // Do both expressions have the same kind?
2686 if (CCI->getAssociatedExpression()->getStmtClass() !=
2687 SC.getAssociatedExpression()->getStmtClass())
2688 if (!(isa<OMPArraySectionExpr>(
2689 SC.getAssociatedExpression()) &&
2690 isa<ArraySubscriptExpr>(
2691 CCI->getAssociatedExpression())))
2692 return false;
2693
Alexey Bataeve3727102018-04-18 15:57:46 +00002694 const Decl *CCD = CCI->getAssociatedDeclaration();
2695 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002696 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2697 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2698 if (SCD != CCD)
2699 return false;
2700 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002701 if (CCI == CCE)
2702 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002703 }
2704 return true;
2705 })) {
2706 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002707 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002708 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002709 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00002710 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002711 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002712 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002713 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002714 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002715 // for task|target directives.
2716 // Skip analysis of arguments of implicitly defined map clause for target
2717 // directives.
2718 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2719 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002720 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002721 if (CC)
2722 Visit(CC);
2723 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002724 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002725 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00002726 // Check implicitly captured variables.
2727 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002728 }
2729 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002730 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002731 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00002732 // Check implicitly captured variables in the task-based directives to
2733 // check if they must be firstprivatized.
2734 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002735 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002736 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002737 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002738
Alexey Bataeve3727102018-04-18 15:57:46 +00002739 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002740 ArrayRef<Expr *> getImplicitFirstprivate() const {
2741 return ImplicitFirstprivate;
2742 }
2743 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00002744 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002745 return VarsWithInheritedDSA;
2746 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002747
Alexey Bataev7ff55242014-06-19 09:13:45 +00002748 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00002749 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
2750 // Process declare target link variables for the target directives.
2751 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
2752 for (DeclRefExpr *E : Stack->getLinkGlobals())
2753 Visit(E);
2754 }
2755 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002756};
Alexey Bataeved09d242014-05-28 05:53:51 +00002757} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002758
Alexey Bataevbae9a792014-06-27 10:37:06 +00002759void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002760 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002761 case OMPD_parallel:
2762 case OMPD_parallel_for:
2763 case OMPD_parallel_for_simd:
2764 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002765 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002766 case OMPD_teams_distribute:
2767 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002768 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002769 QualType KmpInt32PtrTy =
2770 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002771 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002772 std::make_pair(".global_tid.", KmpInt32PtrTy),
2773 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2774 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002775 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002776 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2777 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002778 break;
2779 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002780 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002781 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002782 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002783 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002784 case OMPD_target_teams_distribute:
2785 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002786 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2787 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2788 QualType KmpInt32PtrTy =
2789 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2790 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002791 FunctionProtoType::ExtProtoInfo EPI;
2792 EPI.Variadic = true;
2793 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2794 Sema::CapturedParamNameType Params[] = {
2795 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002796 std::make_pair(".part_id.", KmpInt32PtrTy),
2797 std::make_pair(".privates.", VoidPtrTy),
2798 std::make_pair(
2799 ".copy_fn.",
2800 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002801 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2802 std::make_pair(StringRef(), QualType()) // __context with shared vars
2803 };
2804 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2805 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002806 // Mark this captured region as inlined, because we don't use outlined
2807 // function directly.
2808 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2809 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002810 Context, AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002811 Sema::CapturedParamNameType ParamsTarget[] = {
2812 std::make_pair(StringRef(), QualType()) // __context with shared vars
2813 };
2814 // Start a captured region for 'target' with no implicit parameters.
2815 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2816 ParamsTarget);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002817 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002818 std::make_pair(".global_tid.", KmpInt32PtrTy),
2819 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2820 std::make_pair(StringRef(), QualType()) // __context with shared vars
2821 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002822 // Start a captured region for 'teams' or 'parallel'. Both regions have
2823 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002824 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002825 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002826 break;
2827 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002828 case OMPD_target:
2829 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002830 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2831 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2832 QualType KmpInt32PtrTy =
2833 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2834 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002835 FunctionProtoType::ExtProtoInfo EPI;
2836 EPI.Variadic = true;
2837 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2838 Sema::CapturedParamNameType Params[] = {
2839 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002840 std::make_pair(".part_id.", KmpInt32PtrTy),
2841 std::make_pair(".privates.", VoidPtrTy),
2842 std::make_pair(
2843 ".copy_fn.",
2844 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002845 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2846 std::make_pair(StringRef(), QualType()) // __context with shared vars
2847 };
2848 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2849 Params);
2850 // Mark this captured region as inlined, because we don't use outlined
2851 // function directly.
2852 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2853 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002854 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00002855 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2856 std::make_pair(StringRef(), QualType()));
2857 break;
2858 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002859 case OMPD_simd:
2860 case OMPD_for:
2861 case OMPD_for_simd:
2862 case OMPD_sections:
2863 case OMPD_section:
2864 case OMPD_single:
2865 case OMPD_master:
2866 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002867 case OMPD_taskgroup:
2868 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002869 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002870 case OMPD_ordered:
2871 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002872 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002873 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002874 std::make_pair(StringRef(), QualType()) // __context with shared vars
2875 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002876 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2877 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002878 break;
2879 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002880 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002881 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2882 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2883 QualType KmpInt32PtrTy =
2884 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2885 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002886 FunctionProtoType::ExtProtoInfo EPI;
2887 EPI.Variadic = true;
2888 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002889 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002890 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002891 std::make_pair(".part_id.", KmpInt32PtrTy),
2892 std::make_pair(".privates.", VoidPtrTy),
2893 std::make_pair(
2894 ".copy_fn.",
2895 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002896 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002897 std::make_pair(StringRef(), QualType()) // __context with shared vars
2898 };
2899 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2900 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002901 // Mark this captured region as inlined, because we don't use outlined
2902 // function directly.
2903 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2904 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002905 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002906 break;
2907 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002908 case OMPD_taskloop:
2909 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002910 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002911 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2912 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002913 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002914 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2915 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002916 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002917 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2918 .withConst();
2919 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2920 QualType KmpInt32PtrTy =
2921 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2922 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00002923 FunctionProtoType::ExtProtoInfo EPI;
2924 EPI.Variadic = true;
2925 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002926 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002927 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002928 std::make_pair(".part_id.", KmpInt32PtrTy),
2929 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00002930 std::make_pair(
2931 ".copy_fn.",
2932 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2933 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2934 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002935 std::make_pair(".ub.", KmpUInt64Ty),
2936 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00002937 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002938 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002939 std::make_pair(StringRef(), QualType()) // __context with shared vars
2940 };
2941 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2942 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002943 // Mark this captured region as inlined, because we don't use outlined
2944 // function directly.
2945 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2946 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002947 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002948 break;
2949 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002950 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002951 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002952 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00002953 QualType KmpInt32PtrTy =
2954 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2955 Sema::CapturedParamNameType Params[] = {
2956 std::make_pair(".global_tid.", KmpInt32PtrTy),
2957 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002958 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2959 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00002960 std::make_pair(StringRef(), QualType()) // __context with shared vars
2961 };
2962 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2963 Params);
2964 break;
2965 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002966 case OMPD_target_teams_distribute_parallel_for:
2967 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002968 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002969 QualType KmpInt32PtrTy =
2970 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002971 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002972
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002973 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002974 FunctionProtoType::ExtProtoInfo EPI;
2975 EPI.Variadic = true;
2976 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2977 Sema::CapturedParamNameType Params[] = {
2978 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002979 std::make_pair(".part_id.", KmpInt32PtrTy),
2980 std::make_pair(".privates.", VoidPtrTy),
2981 std::make_pair(
2982 ".copy_fn.",
2983 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002984 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2985 std::make_pair(StringRef(), QualType()) // __context with shared vars
2986 };
2987 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2988 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00002989 // Mark this captured region as inlined, because we don't use outlined
2990 // function directly.
2991 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2992 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002993 Context, AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00002994 Sema::CapturedParamNameType ParamsTarget[] = {
2995 std::make_pair(StringRef(), QualType()) // __context with shared vars
2996 };
2997 // Start a captured region for 'target' with no implicit parameters.
2998 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2999 ParamsTarget);
3000
3001 Sema::CapturedParamNameType ParamsTeams[] = {
3002 std::make_pair(".global_tid.", KmpInt32PtrTy),
3003 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3004 std::make_pair(StringRef(), QualType()) // __context with shared vars
3005 };
3006 // Start a captured region for 'target' with no implicit parameters.
3007 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3008 ParamsTeams);
3009
3010 Sema::CapturedParamNameType ParamsParallel[] = {
3011 std::make_pair(".global_tid.", KmpInt32PtrTy),
3012 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003013 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3014 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003015 std::make_pair(StringRef(), QualType()) // __context with shared vars
3016 };
3017 // Start a captured region for 'teams' or 'parallel'. Both regions have
3018 // the same implicit parameters.
3019 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3020 ParamsParallel);
3021 break;
3022 }
3023
Alexey Bataev46506272017-12-05 17:41:34 +00003024 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003025 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003026 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003027 QualType KmpInt32PtrTy =
3028 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3029
3030 Sema::CapturedParamNameType ParamsTeams[] = {
3031 std::make_pair(".global_tid.", KmpInt32PtrTy),
3032 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3033 std::make_pair(StringRef(), QualType()) // __context with shared vars
3034 };
3035 // Start a captured region for 'target' with no implicit parameters.
3036 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3037 ParamsTeams);
3038
3039 Sema::CapturedParamNameType ParamsParallel[] = {
3040 std::make_pair(".global_tid.", KmpInt32PtrTy),
3041 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003042 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3043 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003044 std::make_pair(StringRef(), QualType()) // __context with shared vars
3045 };
3046 // Start a captured region for 'teams' or 'parallel'. Both regions have
3047 // the same implicit parameters.
3048 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3049 ParamsParallel);
3050 break;
3051 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003052 case OMPD_target_update:
3053 case OMPD_target_enter_data:
3054 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003055 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3056 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3057 QualType KmpInt32PtrTy =
3058 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3059 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003060 FunctionProtoType::ExtProtoInfo EPI;
3061 EPI.Variadic = true;
3062 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3063 Sema::CapturedParamNameType Params[] = {
3064 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003065 std::make_pair(".part_id.", KmpInt32PtrTy),
3066 std::make_pair(".privates.", VoidPtrTy),
3067 std::make_pair(
3068 ".copy_fn.",
3069 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003070 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3071 std::make_pair(StringRef(), QualType()) // __context with shared vars
3072 };
3073 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3074 Params);
3075 // Mark this captured region as inlined, because we don't use outlined
3076 // function directly.
3077 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3078 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003079 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003080 break;
3081 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003082 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003083 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003084 case OMPD_taskyield:
3085 case OMPD_barrier:
3086 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003087 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003088 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003089 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003090 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003091 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003092 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003093 case OMPD_declare_target:
3094 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003095 case OMPD_requires:
Alexey Bataev9959db52014-05-06 10:08:46 +00003096 llvm_unreachable("OpenMP Directive is not allowed");
3097 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003098 llvm_unreachable("Unknown OpenMP directive");
3099 }
3100}
3101
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003102int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3103 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3104 getOpenMPCaptureRegions(CaptureRegions, DKind);
3105 return CaptureRegions.size();
3106}
3107
Alexey Bataev3392d762016-02-16 11:18:12 +00003108static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003109 Expr *CaptureExpr, bool WithInit,
3110 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003111 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003112 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003113 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003114 QualType Ty = Init->getType();
3115 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003116 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003117 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003118 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003119 Ty = C.getPointerType(Ty);
3120 ExprResult Res =
3121 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3122 if (!Res.isUsable())
3123 return nullptr;
3124 Init = Res.get();
3125 }
Alexey Bataev61205072016-03-02 04:57:40 +00003126 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003127 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003128 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003129 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003130 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003131 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003132 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003133 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003134 return CED;
3135}
3136
Alexey Bataev61205072016-03-02 04:57:40 +00003137static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3138 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003139 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003140 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003141 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003142 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003143 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3144 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003145 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003146 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003147}
3148
Alexey Bataev5a3af132016-03-29 08:58:54 +00003149static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003150 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003151 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003152 OMPCapturedExprDecl *CD = buildCaptureDecl(
3153 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3154 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003155 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3156 CaptureExpr->getExprLoc());
3157 }
3158 ExprResult Res = Ref;
3159 if (!S.getLangOpts().CPlusPlus &&
3160 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003161 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003162 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003163 if (!Res.isUsable())
3164 return ExprError();
3165 }
3166 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003167}
3168
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003169namespace {
3170// OpenMP directives parsed in this section are represented as a
3171// CapturedStatement with an associated statement. If a syntax error
3172// is detected during the parsing of the associated statement, the
3173// compiler must abort processing and close the CapturedStatement.
3174//
3175// Combined directives such as 'target parallel' have more than one
3176// nested CapturedStatements. This RAII ensures that we unwind out
3177// of all the nested CapturedStatements when an error is found.
3178class CaptureRegionUnwinderRAII {
3179private:
3180 Sema &S;
3181 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003182 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003183
3184public:
3185 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3186 OpenMPDirectiveKind DKind)
3187 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3188 ~CaptureRegionUnwinderRAII() {
3189 if (ErrorFound) {
3190 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3191 while (--ThisCaptureLevel >= 0)
3192 S.ActOnCapturedRegionError();
3193 }
3194 }
3195};
3196} // namespace
3197
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003198StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3199 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003200 bool ErrorFound = false;
3201 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3202 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003203 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003204 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003205 return StmtError();
3206 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003207
Alexey Bataev2ba67042017-11-28 21:11:44 +00003208 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3209 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003210 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003211 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003212 SmallVector<const OMPLinearClause *, 4> LCs;
3213 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003214 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003215 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003216 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3217 Clause->getClauseKind() == OMPC_in_reduction) {
3218 // Capture taskgroup task_reduction descriptors inside the tasking regions
3219 // with the corresponding in_reduction items.
3220 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003221 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003222 if (E)
3223 MarkDeclarationsReferencedInExpr(E);
3224 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003225 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003226 Clause->getClauseKind() == OMPC_copyprivate ||
3227 (getLangOpts().OpenMPUseTLS &&
3228 getASTContext().getTargetInfo().isTLSSupported() &&
3229 Clause->getClauseKind() == OMPC_copyin)) {
3230 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003231 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003232 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003233 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003234 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003235 }
3236 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003237 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003238 } else if (CaptureRegions.size() > 1 ||
3239 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003240 if (auto *C = OMPClauseWithPreInit::get(Clause))
3241 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003242 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003243 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003244 MarkDeclarationsReferencedInExpr(E);
3245 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003246 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003247 if (Clause->getClauseKind() == OMPC_schedule)
3248 SC = cast<OMPScheduleClause>(Clause);
3249 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003250 OC = cast<OMPOrderedClause>(Clause);
3251 else if (Clause->getClauseKind() == OMPC_linear)
3252 LCs.push_back(cast<OMPLinearClause>(Clause));
3253 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003254 // OpenMP, 2.7.1 Loop Construct, Restrictions
3255 // The nonmonotonic modifier cannot be specified if an ordered clause is
3256 // specified.
3257 if (SC &&
3258 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3259 SC->getSecondScheduleModifier() ==
3260 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3261 OC) {
3262 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3263 ? SC->getFirstScheduleModifierLoc()
3264 : SC->getSecondScheduleModifierLoc(),
3265 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003266 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003267 ErrorFound = true;
3268 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003269 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003270 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003271 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003272 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003273 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003274 ErrorFound = true;
3275 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003276 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3277 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3278 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003279 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003280 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3281 ErrorFound = true;
3282 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003283 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003284 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003285 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003286 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003287 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003288 // Mark all variables in private list clauses as used in inner region.
3289 // Required for proper codegen of combined directives.
3290 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003291 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003292 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003293 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3294 // Find the particular capture region for the clause if the
3295 // directive is a combined one with multiple capture regions.
3296 // If the directive is not a combined one, the capture region
3297 // associated with the clause is OMPD_unknown and is generated
3298 // only once.
3299 if (CaptureRegion == ThisCaptureRegion ||
3300 CaptureRegion == OMPD_unknown) {
3301 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003302 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003303 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3304 }
3305 }
3306 }
3307 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003308 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003309 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003310 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003311}
3312
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003313static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3314 OpenMPDirectiveKind CancelRegion,
3315 SourceLocation StartLoc) {
3316 // CancelRegion is only needed for cancel and cancellation_point.
3317 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3318 return false;
3319
3320 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3321 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3322 return false;
3323
3324 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3325 << getOpenMPDirectiveName(CancelRegion);
3326 return true;
3327}
3328
Alexey Bataeve3727102018-04-18 15:57:46 +00003329static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003330 OpenMPDirectiveKind CurrentRegion,
3331 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003332 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003333 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003334 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003335 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3336 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003337 bool NestingProhibited = false;
3338 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003339 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003340 enum {
3341 NoRecommend,
3342 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003343 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003344 ShouldBeInTargetRegion,
3345 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003346 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003347 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003348 // OpenMP [2.16, Nesting of Regions]
3349 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003350 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003351 // An ordered construct with the simd clause is the only OpenMP
3352 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003353 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003354 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3355 // message.
3356 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3357 ? diag::err_omp_prohibited_region_simd
3358 : diag::warn_omp_nesting_simd);
3359 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003360 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003361 if (ParentRegion == OMPD_atomic) {
3362 // OpenMP [2.16, Nesting of Regions]
3363 // OpenMP constructs may not be nested inside an atomic region.
3364 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3365 return true;
3366 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003367 if (CurrentRegion == OMPD_section) {
3368 // OpenMP [2.7.2, sections Construct, Restrictions]
3369 // Orphaned section directives are prohibited. That is, the section
3370 // directives must appear within the sections construct and must not be
3371 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003372 if (ParentRegion != OMPD_sections &&
3373 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003374 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3375 << (ParentRegion != OMPD_unknown)
3376 << getOpenMPDirectiveName(ParentRegion);
3377 return true;
3378 }
3379 return false;
3380 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003381 // Allow some constructs (except teams and cancellation constructs) to be
3382 // orphaned (they could be used in functions, called from OpenMP regions
3383 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003384 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003385 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3386 CurrentRegion != OMPD_cancellation_point &&
3387 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003388 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003389 if (CurrentRegion == OMPD_cancellation_point ||
3390 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003391 // OpenMP [2.16, Nesting of Regions]
3392 // A cancellation point construct for which construct-type-clause is
3393 // taskgroup must be nested inside a task construct. A cancellation
3394 // point construct for which construct-type-clause is not taskgroup must
3395 // be closely nested inside an OpenMP construct that matches the type
3396 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003397 // A cancel construct for which construct-type-clause is taskgroup must be
3398 // nested inside a task construct. A cancel construct for which
3399 // construct-type-clause is not taskgroup must be closely nested inside an
3400 // OpenMP construct that matches the type specified in
3401 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003402 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003403 !((CancelRegion == OMPD_parallel &&
3404 (ParentRegion == OMPD_parallel ||
3405 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003406 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003407 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003408 ParentRegion == OMPD_target_parallel_for ||
3409 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003410 ParentRegion == OMPD_teams_distribute_parallel_for ||
3411 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003412 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3413 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003414 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3415 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003416 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003417 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003418 // OpenMP [2.16, Nesting of Regions]
3419 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003420 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003421 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003422 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003423 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3424 // OpenMP [2.16, Nesting of Regions]
3425 // A critical region may not be nested (closely or otherwise) inside a
3426 // critical region with the same name. Note that this restriction is not
3427 // sufficient to prevent deadlock.
3428 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003429 bool DeadLock = Stack->hasDirective(
3430 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3431 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003432 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003433 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3434 PreviousCriticalLoc = Loc;
3435 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003436 }
3437 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003438 },
3439 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003440 if (DeadLock) {
3441 SemaRef.Diag(StartLoc,
3442 diag::err_omp_prohibited_region_critical_same_name)
3443 << CurrentName.getName();
3444 if (PreviousCriticalLoc.isValid())
3445 SemaRef.Diag(PreviousCriticalLoc,
3446 diag::note_omp_previous_critical_region);
3447 return true;
3448 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003449 } else if (CurrentRegion == OMPD_barrier) {
3450 // OpenMP [2.16, Nesting of Regions]
3451 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003452 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003453 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3454 isOpenMPTaskingDirective(ParentRegion) ||
3455 ParentRegion == OMPD_master ||
3456 ParentRegion == OMPD_critical ||
3457 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003458 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003459 !isOpenMPParallelDirective(CurrentRegion) &&
3460 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003461 // OpenMP [2.16, Nesting of Regions]
3462 // A worksharing region may not be closely nested inside a worksharing,
3463 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003464 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3465 isOpenMPTaskingDirective(ParentRegion) ||
3466 ParentRegion == OMPD_master ||
3467 ParentRegion == OMPD_critical ||
3468 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003469 Recommend = ShouldBeInParallelRegion;
3470 } else if (CurrentRegion == OMPD_ordered) {
3471 // OpenMP [2.16, Nesting of Regions]
3472 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003473 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003474 // An ordered region must be closely nested inside a loop region (or
3475 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003476 // OpenMP [2.8.1,simd Construct, Restrictions]
3477 // An ordered construct with the simd clause is the only OpenMP construct
3478 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003479 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003480 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003481 !(isOpenMPSimdDirective(ParentRegion) ||
3482 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003483 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003484 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003485 // OpenMP [2.16, Nesting of Regions]
3486 // If specified, a teams construct must be contained within a target
3487 // construct.
3488 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00003489 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003490 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003491 }
Kelvin Libf594a52016-12-17 05:48:59 +00003492 if (!NestingProhibited &&
3493 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3494 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3495 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003496 // OpenMP [2.16, Nesting of Regions]
3497 // distribute, parallel, parallel sections, parallel workshare, and the
3498 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3499 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003500 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3501 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003502 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003503 }
David Majnemer9d168222016-08-05 17:44:54 +00003504 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003505 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003506 // OpenMP 4.5 [2.17 Nesting of Regions]
3507 // The region associated with the distribute construct must be strictly
3508 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003509 NestingProhibited =
3510 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003511 Recommend = ShouldBeInTeamsRegion;
3512 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003513 if (!NestingProhibited &&
3514 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3515 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3516 // OpenMP 4.5 [2.17 Nesting of Regions]
3517 // If a target, target update, target data, target enter data, or
3518 // target exit data construct is encountered during execution of a
3519 // target region, the behavior is unspecified.
3520 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003521 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003522 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003523 if (isOpenMPTargetExecutionDirective(K)) {
3524 OffendingRegion = K;
3525 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003526 }
3527 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003528 },
3529 false /* don't skip top directive */);
3530 CloseNesting = false;
3531 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003532 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003533 if (OrphanSeen) {
3534 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3535 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3536 } else {
3537 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3538 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3539 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3540 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003541 return true;
3542 }
3543 }
3544 return false;
3545}
3546
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003547static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3548 ArrayRef<OMPClause *> Clauses,
3549 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3550 bool ErrorFound = false;
3551 unsigned NamedModifiersNumber = 0;
3552 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3553 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003554 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003555 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003556 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3557 // At most one if clause without a directive-name-modifier can appear on
3558 // the directive.
3559 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3560 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003561 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003562 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3563 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3564 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003565 } else if (CurNM != OMPD_unknown) {
3566 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003567 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003568 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003569 FoundNameModifiers[CurNM] = IC;
3570 if (CurNM == OMPD_unknown)
3571 continue;
3572 // Check if the specified name modifier is allowed for the current
3573 // directive.
3574 // At most one if clause with the particular directive-name-modifier can
3575 // appear on the directive.
3576 bool MatchFound = false;
3577 for (auto NM : AllowedNameModifiers) {
3578 if (CurNM == NM) {
3579 MatchFound = true;
3580 break;
3581 }
3582 }
3583 if (!MatchFound) {
3584 S.Diag(IC->getNameModifierLoc(),
3585 diag::err_omp_wrong_if_directive_name_modifier)
3586 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3587 ErrorFound = true;
3588 }
3589 }
3590 }
3591 // If any if clause on the directive includes a directive-name-modifier then
3592 // all if clauses on the directive must include a directive-name-modifier.
3593 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3594 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003595 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003596 diag::err_omp_no_more_if_clause);
3597 } else {
3598 std::string Values;
3599 std::string Sep(", ");
3600 unsigned AllowedCnt = 0;
3601 unsigned TotalAllowedNum =
3602 AllowedNameModifiers.size() - NamedModifiersNumber;
3603 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3604 ++Cnt) {
3605 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3606 if (!FoundNameModifiers[NM]) {
3607 Values += "'";
3608 Values += getOpenMPDirectiveName(NM);
3609 Values += "'";
3610 if (AllowedCnt + 2 == TotalAllowedNum)
3611 Values += " or ";
3612 else if (AllowedCnt + 1 != TotalAllowedNum)
3613 Values += Sep;
3614 ++AllowedCnt;
3615 }
3616 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003617 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003618 diag::err_omp_unnamed_if_clause)
3619 << (TotalAllowedNum > 1) << Values;
3620 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003621 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00003622 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3623 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003624 ErrorFound = true;
3625 }
3626 return ErrorFound;
3627}
3628
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003629StmtResult Sema::ActOnOpenMPExecutableDirective(
3630 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3631 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3632 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003633 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003634 // First check CancelRegion which is then used in checkNestingOfRegions.
3635 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3636 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003637 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00003638 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003639
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003640 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00003641 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003642 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003643 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003644 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003645 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3646
3647 // Check default data sharing attributes for referenced variables.
3648 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003649 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3650 Stmt *S = AStmt;
3651 while (--ThisCaptureLevel >= 0)
3652 S = cast<CapturedStmt>(S)->getCapturedStmt();
3653 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003654 if (DSAChecker.isErrorFound())
3655 return StmtError();
3656 // Generate list of implicitly defined firstprivate variables.
3657 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003658
Alexey Bataev88202be2017-07-27 13:20:36 +00003659 SmallVector<Expr *, 4> ImplicitFirstprivates(
3660 DSAChecker.getImplicitFirstprivate().begin(),
3661 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003662 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3663 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003664 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00003665 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003666 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003667 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003668 if (E)
3669 ImplicitFirstprivates.emplace_back(E);
3670 }
3671 }
3672 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003673 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00003674 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3675 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003676 ClausesWithImplicit.push_back(Implicit);
3677 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00003678 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003679 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00003680 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003681 }
Alexey Bataev68446b72014-07-18 07:47:19 +00003682 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003683 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00003684 CXXScopeSpec MapperIdScopeSpec;
3685 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003686 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00003687 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
3688 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
3689 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003690 ClausesWithImplicit.emplace_back(Implicit);
3691 ErrorFound |=
3692 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003693 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003694 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003695 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003696 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003697 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003698
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003699 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003700 switch (Kind) {
3701 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003702 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3703 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003704 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003705 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003706 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003707 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3708 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003709 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003710 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003711 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3712 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003713 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003714 case OMPD_for_simd:
3715 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3716 EndLoc, VarsWithInheritedDSA);
3717 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003718 case OMPD_sections:
3719 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3720 EndLoc);
3721 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003722 case OMPD_section:
3723 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003724 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003725 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3726 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003727 case OMPD_single:
3728 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3729 EndLoc);
3730 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003731 case OMPD_master:
3732 assert(ClausesWithImplicit.empty() &&
3733 "No clauses are allowed for 'omp master' directive");
3734 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3735 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003736 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003737 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3738 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003739 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003740 case OMPD_parallel_for:
3741 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3742 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003743 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003744 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003745 case OMPD_parallel_for_simd:
3746 Res = ActOnOpenMPParallelForSimdDirective(
3747 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003748 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003749 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003750 case OMPD_parallel_sections:
3751 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3752 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003753 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003754 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003755 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003756 Res =
3757 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003758 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003759 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003760 case OMPD_taskyield:
3761 assert(ClausesWithImplicit.empty() &&
3762 "No clauses are allowed for 'omp taskyield' directive");
3763 assert(AStmt == nullptr &&
3764 "No associated statement allowed for 'omp taskyield' directive");
3765 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3766 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003767 case OMPD_barrier:
3768 assert(ClausesWithImplicit.empty() &&
3769 "No clauses are allowed for 'omp barrier' directive");
3770 assert(AStmt == nullptr &&
3771 "No associated statement allowed for 'omp barrier' directive");
3772 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3773 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003774 case OMPD_taskwait:
3775 assert(ClausesWithImplicit.empty() &&
3776 "No clauses are allowed for 'omp taskwait' directive");
3777 assert(AStmt == nullptr &&
3778 "No associated statement allowed for 'omp taskwait' directive");
3779 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3780 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003781 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003782 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3783 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003784 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003785 case OMPD_flush:
3786 assert(AStmt == nullptr &&
3787 "No associated statement allowed for 'omp flush' directive");
3788 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3789 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003790 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003791 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3792 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003793 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003794 case OMPD_atomic:
3795 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3796 EndLoc);
3797 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003798 case OMPD_teams:
3799 Res =
3800 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3801 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003802 case OMPD_target:
3803 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3804 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003805 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003806 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003807 case OMPD_target_parallel:
3808 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3809 StartLoc, EndLoc);
3810 AllowedNameModifiers.push_back(OMPD_target);
3811 AllowedNameModifiers.push_back(OMPD_parallel);
3812 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003813 case OMPD_target_parallel_for:
3814 Res = ActOnOpenMPTargetParallelForDirective(
3815 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3816 AllowedNameModifiers.push_back(OMPD_target);
3817 AllowedNameModifiers.push_back(OMPD_parallel);
3818 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003819 case OMPD_cancellation_point:
3820 assert(ClausesWithImplicit.empty() &&
3821 "No clauses are allowed for 'omp cancellation point' directive");
3822 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3823 "cancellation point' directive");
3824 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3825 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003826 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003827 assert(AStmt == nullptr &&
3828 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003829 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3830 CancelRegion);
3831 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003832 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003833 case OMPD_target_data:
3834 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3835 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003836 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003837 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003838 case OMPD_target_enter_data:
3839 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003840 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003841 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3842 break;
Samuel Antao72590762016-01-19 20:04:50 +00003843 case OMPD_target_exit_data:
3844 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003845 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003846 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3847 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003848 case OMPD_taskloop:
3849 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3850 EndLoc, VarsWithInheritedDSA);
3851 AllowedNameModifiers.push_back(OMPD_taskloop);
3852 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003853 case OMPD_taskloop_simd:
3854 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3855 EndLoc, VarsWithInheritedDSA);
3856 AllowedNameModifiers.push_back(OMPD_taskloop);
3857 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003858 case OMPD_distribute:
3859 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3860 EndLoc, VarsWithInheritedDSA);
3861 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003862 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003863 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3864 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003865 AllowedNameModifiers.push_back(OMPD_target_update);
3866 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003867 case OMPD_distribute_parallel_for:
3868 Res = ActOnOpenMPDistributeParallelForDirective(
3869 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3870 AllowedNameModifiers.push_back(OMPD_parallel);
3871 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003872 case OMPD_distribute_parallel_for_simd:
3873 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3874 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3875 AllowedNameModifiers.push_back(OMPD_parallel);
3876 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003877 case OMPD_distribute_simd:
3878 Res = ActOnOpenMPDistributeSimdDirective(
3879 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3880 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003881 case OMPD_target_parallel_for_simd:
3882 Res = ActOnOpenMPTargetParallelForSimdDirective(
3883 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3884 AllowedNameModifiers.push_back(OMPD_target);
3885 AllowedNameModifiers.push_back(OMPD_parallel);
3886 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003887 case OMPD_target_simd:
3888 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3889 EndLoc, VarsWithInheritedDSA);
3890 AllowedNameModifiers.push_back(OMPD_target);
3891 break;
Kelvin Li02532872016-08-05 14:37:37 +00003892 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003893 Res = ActOnOpenMPTeamsDistributeDirective(
3894 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003895 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003896 case OMPD_teams_distribute_simd:
3897 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3898 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3899 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003900 case OMPD_teams_distribute_parallel_for_simd:
3901 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3902 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3903 AllowedNameModifiers.push_back(OMPD_parallel);
3904 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003905 case OMPD_teams_distribute_parallel_for:
3906 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3907 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3908 AllowedNameModifiers.push_back(OMPD_parallel);
3909 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003910 case OMPD_target_teams:
3911 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3912 EndLoc);
3913 AllowedNameModifiers.push_back(OMPD_target);
3914 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003915 case OMPD_target_teams_distribute:
3916 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3917 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3918 AllowedNameModifiers.push_back(OMPD_target);
3919 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003920 case OMPD_target_teams_distribute_parallel_for:
3921 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3922 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3923 AllowedNameModifiers.push_back(OMPD_target);
3924 AllowedNameModifiers.push_back(OMPD_parallel);
3925 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003926 case OMPD_target_teams_distribute_parallel_for_simd:
3927 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3928 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3929 AllowedNameModifiers.push_back(OMPD_target);
3930 AllowedNameModifiers.push_back(OMPD_parallel);
3931 break;
Kelvin Lida681182017-01-10 18:08:18 +00003932 case OMPD_target_teams_distribute_simd:
3933 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3934 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3935 AllowedNameModifiers.push_back(OMPD_target);
3936 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003937 case OMPD_declare_target:
3938 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003939 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003940 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003941 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003942 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003943 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00003944 case OMPD_requires:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003945 llvm_unreachable("OpenMP Directive is not allowed");
3946 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003947 llvm_unreachable("Unknown OpenMP directive");
3948 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003949
Roman Lebedevb5700602019-03-20 16:32:36 +00003950 ErrorFound = Res.isInvalid() || ErrorFound;
3951
Alexey Bataeve3727102018-04-18 15:57:46 +00003952 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003953 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3954 << P.first << P.second->getSourceRange();
3955 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003956 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3957
3958 if (!AllowedNameModifiers.empty())
3959 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3960 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003961
Alexey Bataeved09d242014-05-28 05:53:51 +00003962 if (ErrorFound)
3963 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00003964
3965 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
3966 Res.getAs<OMPExecutableDirective>()
3967 ->getStructuredBlock()
3968 ->setIsOMPStructuredBlock(true);
3969 }
3970
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003971 return Res;
3972}
3973
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003974Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3975 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003976 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003977 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3978 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003979 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003980 assert(Linears.size() == LinModifiers.size());
3981 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003982 if (!DG || DG.get().isNull())
3983 return DeclGroupPtrTy();
3984
3985 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003986 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003987 return DG;
3988 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003989 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00003990 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3991 ADecl = FTD->getTemplatedDecl();
3992
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003993 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3994 if (!FD) {
3995 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003996 return DeclGroupPtrTy();
3997 }
3998
Alexey Bataev2af33e32016-04-07 12:45:37 +00003999 // OpenMP [2.8.2, declare simd construct, Description]
4000 // The parameter of the simdlen clause must be a constant positive integer
4001 // expression.
4002 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004003 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00004004 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004005 // OpenMP [2.8.2, declare simd construct, Description]
4006 // The special this pointer can be used as if was one of the arguments to the
4007 // function in any of the linear, aligned, or uniform clauses.
4008 // The uniform clause declares one or more arguments to have an invariant
4009 // value for all concurrent invocations of the function in the execution of a
4010 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00004011 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4012 const Expr *UniformedLinearThis = nullptr;
4013 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004014 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004015 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4016 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004017 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4018 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004019 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004020 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004021 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004022 }
4023 if (isa<CXXThisExpr>(E)) {
4024 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004025 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004026 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004027 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4028 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004029 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004030 // OpenMP [2.8.2, declare simd construct, Description]
4031 // The aligned clause declares that the object to which each list item points
4032 // is aligned to the number of bytes expressed in the optional parameter of
4033 // the aligned clause.
4034 // The special this pointer can be used as if was one of the arguments to the
4035 // function in any of the linear, aligned, or uniform clauses.
4036 // The type of list items appearing in the aligned clause must be array,
4037 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004038 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4039 const Expr *AlignedThis = nullptr;
4040 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004041 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004042 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4043 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4044 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004045 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4046 FD->getParamDecl(PVD->getFunctionScopeIndex())
4047 ->getCanonicalDecl() == CanonPVD) {
4048 // OpenMP [2.8.1, simd construct, Restrictions]
4049 // A list-item cannot appear in more than one aligned clause.
4050 if (AlignedArgs.count(CanonPVD) > 0) {
4051 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4052 << 1 << E->getSourceRange();
4053 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4054 diag::note_omp_explicit_dsa)
4055 << getOpenMPClauseName(OMPC_aligned);
4056 continue;
4057 }
4058 AlignedArgs[CanonPVD] = E;
4059 QualType QTy = PVD->getType()
4060 .getNonReferenceType()
4061 .getUnqualifiedType()
4062 .getCanonicalType();
4063 const Type *Ty = QTy.getTypePtrOrNull();
4064 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4065 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4066 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4067 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4068 }
4069 continue;
4070 }
4071 }
4072 if (isa<CXXThisExpr>(E)) {
4073 if (AlignedThis) {
4074 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4075 << 2 << E->getSourceRange();
4076 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4077 << getOpenMPClauseName(OMPC_aligned);
4078 }
4079 AlignedThis = E;
4080 continue;
4081 }
4082 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4083 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4084 }
4085 // The optional parameter of the aligned clause, alignment, must be a constant
4086 // positive integer expression. If no optional parameter is specified,
4087 // implementation-defined default alignments for SIMD instructions on the
4088 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00004089 SmallVector<const Expr *, 4> NewAligns;
4090 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004091 ExprResult Align;
4092 if (E)
4093 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4094 NewAligns.push_back(Align.get());
4095 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00004096 // OpenMP [2.8.2, declare simd construct, Description]
4097 // The linear clause declares one or more list items to be private to a SIMD
4098 // lane and to have a linear relationship with respect to the iteration space
4099 // of a loop.
4100 // The special this pointer can be used as if was one of the arguments to the
4101 // function in any of the linear, aligned, or uniform clauses.
4102 // When a linear-step expression is specified in a linear clause it must be
4103 // either a constant integer expression or an integer-typed parameter that is
4104 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00004105 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004106 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4107 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00004108 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004109 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4110 ++MI;
4111 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004112 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4113 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4114 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004115 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4116 FD->getParamDecl(PVD->getFunctionScopeIndex())
4117 ->getCanonicalDecl() == CanonPVD) {
4118 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4119 // A list-item cannot appear in more than one linear clause.
4120 if (LinearArgs.count(CanonPVD) > 0) {
4121 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4122 << getOpenMPClauseName(OMPC_linear)
4123 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4124 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4125 diag::note_omp_explicit_dsa)
4126 << getOpenMPClauseName(OMPC_linear);
4127 continue;
4128 }
4129 // Each argument can appear in at most one uniform or linear clause.
4130 if (UniformedArgs.count(CanonPVD) > 0) {
4131 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4132 << getOpenMPClauseName(OMPC_linear)
4133 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4134 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4135 diag::note_omp_explicit_dsa)
4136 << getOpenMPClauseName(OMPC_uniform);
4137 continue;
4138 }
4139 LinearArgs[CanonPVD] = E;
4140 if (E->isValueDependent() || E->isTypeDependent() ||
4141 E->isInstantiationDependent() ||
4142 E->containsUnexpandedParameterPack())
4143 continue;
4144 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4145 PVD->getOriginalType());
4146 continue;
4147 }
4148 }
4149 if (isa<CXXThisExpr>(E)) {
4150 if (UniformedLinearThis) {
4151 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4152 << getOpenMPClauseName(OMPC_linear)
4153 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4154 << E->getSourceRange();
4155 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4156 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4157 : OMPC_linear);
4158 continue;
4159 }
4160 UniformedLinearThis = E;
4161 if (E->isValueDependent() || E->isTypeDependent() ||
4162 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4163 continue;
4164 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4165 E->getType());
4166 continue;
4167 }
4168 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4169 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4170 }
4171 Expr *Step = nullptr;
4172 Expr *NewStep = nullptr;
4173 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00004174 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004175 // Skip the same step expression, it was checked already.
4176 if (Step == E || !E) {
4177 NewSteps.push_back(E ? NewStep : nullptr);
4178 continue;
4179 }
4180 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00004181 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4182 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4183 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004184 if (UniformedArgs.count(CanonPVD) == 0) {
4185 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4186 << Step->getSourceRange();
4187 } else if (E->isValueDependent() || E->isTypeDependent() ||
4188 E->isInstantiationDependent() ||
4189 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00004190 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004191 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00004192 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004193 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4194 << Step->getSourceRange();
4195 }
4196 continue;
4197 }
4198 NewStep = Step;
4199 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4200 !Step->isInstantiationDependent() &&
4201 !Step->containsUnexpandedParameterPack()) {
4202 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4203 .get();
4204 if (NewStep)
4205 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4206 }
4207 NewSteps.push_back(NewStep);
4208 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004209 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4210 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00004211 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00004212 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4213 const_cast<Expr **>(Linears.data()), Linears.size(),
4214 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4215 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004216 ADecl->addAttr(NewAttr);
4217 return ConvertDeclToDeclGroup(ADecl);
4218}
4219
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004220StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
4221 Stmt *AStmt,
4222 SourceLocation StartLoc,
4223 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004224 if (!AStmt)
4225 return StmtError();
4226
Alexey Bataeve3727102018-04-18 15:57:46 +00004227 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00004228 // 1.2.2 OpenMP Language Terminology
4229 // Structured block - An executable statement with a single entry at the
4230 // top and a single exit at the bottom.
4231 // The point of exit cannot be a branch out of the structured block.
4232 // longjmp() and throw() must not violate the entry/exit criteria.
4233 CS->getCapturedDecl()->setNothrow();
4234
Reid Kleckner87a31802018-03-12 21:43:02 +00004235 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004236
Alexey Bataev25e5b442015-09-15 12:52:43 +00004237 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4238 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004239}
4240
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004241namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004242/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004243/// extracting iteration space of each loop in the loop nest, that will be used
4244/// for IR generation.
4245class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004246 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004247 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004248 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004249 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004250 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004251 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004252 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004253 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004254 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004255 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004256 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004257 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004258 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004259 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004260 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004261 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004262 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004263 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004264 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004265 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004266 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004267 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004268 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004269 /// Var < UB
4270 /// Var <= UB
4271 /// UB > Var
4272 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00004273 /// This will have no value when the condition is !=
4274 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004275 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004276 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004277 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004278 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004279
4280public:
4281 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004282 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004283 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004284 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00004285 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004286 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004287 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00004288 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004289 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004290 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00004291 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004292 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004293 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004294 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004295 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004296 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004297 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004298 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00004299 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004300 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004301 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004302 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00004303 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00004304 /// True, if the compare operator is strict (<, > or !=).
4305 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004306 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004307 Expr *buildNumIterations(
4308 Scope *S, const bool LimitedType,
4309 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004310 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00004311 Expr *
4312 buildPreCond(Scope *S, Expr *Cond,
4313 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004314 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004315 DeclRefExpr *
4316 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4317 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004318 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00004319 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004320 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004321 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004322 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004323 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004324 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004325 /// Build loop data with counter value for depend clauses in ordered
4326 /// directives.
4327 Expr *
4328 buildOrderedLoopData(Scope *S, Expr *Counter,
4329 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4330 SourceLocation Loc, Expr *Inc = nullptr,
4331 OverloadedOperatorKind OOK = OO_Amp);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004332 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00004333 bool dependent() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004334
4335private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004336 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004337 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00004338 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004339 /// Helper to set loop counter variable and its initializer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004340 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004341 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00004342 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4343 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004344 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004345 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004346};
4347
Alexey Bataeve3727102018-04-18 15:57:46 +00004348bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004349 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004350 assert(!LB && !UB && !Step);
4351 return false;
4352 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004353 return LCDecl->getType()->isDependentType() ||
4354 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4355 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004356}
4357
Alexey Bataeve3727102018-04-18 15:57:46 +00004358bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004359 Expr *NewLCRefExpr,
4360 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004361 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004362 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00004363 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004364 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004365 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004366 LCDecl = getCanonicalDecl(NewLCDecl);
4367 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004368 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4369 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004370 if ((Ctor->isCopyOrMoveConstructor() ||
4371 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4372 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004373 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004374 LB = NewLB;
4375 return false;
4376}
4377
Alexey Bataev316ccf62019-01-29 18:51:58 +00004378bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4379 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00004380 bool StrictOp, SourceRange SR,
4381 SourceLocation SL) {
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 && UB == nullptr &&
4384 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004385 if (!NewUB)
4386 return true;
4387 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00004388 if (LessOp)
4389 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004390 TestIsStrictOp = StrictOp;
4391 ConditionSrcRange = SR;
4392 ConditionLoc = SL;
4393 return false;
4394}
4395
Alexey Bataeve3727102018-04-18 15:57:46 +00004396bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004397 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004398 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004399 if (!NewStep)
4400 return true;
4401 if (!NewStep->isValueDependent()) {
4402 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004403 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00004404 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4405 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004406 if (Val.isInvalid())
4407 return true;
4408 NewStep = Val.get();
4409
4410 // OpenMP [2.6, Canonical Loop Form, Restrictions]
4411 // If test-expr is of form var relational-op b and relational-op is < or
4412 // <= then incr-expr must cause var to increase on each iteration of the
4413 // loop. If test-expr is of form var relational-op b and relational-op is
4414 // > or >= then incr-expr must cause var to decrease on each iteration of
4415 // the loop.
4416 // If test-expr is of form b relational-op var and relational-op is < or
4417 // <= then incr-expr must cause var to decrease on each iteration of the
4418 // loop. If test-expr is of form b relational-op var and relational-op is
4419 // > or >= then incr-expr must cause var to increase on each iteration of
4420 // the loop.
4421 llvm::APSInt Result;
4422 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4423 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4424 bool IsConstNeg =
4425 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004426 bool IsConstPos =
4427 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004428 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00004429
4430 // != with increment is treated as <; != with decrement is treated as >
4431 if (!TestIsLessOp.hasValue())
4432 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004433 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004434 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004435 (IsConstNeg || (IsUnsigned && Subtract)) :
4436 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004437 SemaRef.Diag(NewStep->getExprLoc(),
4438 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004439 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004440 SemaRef.Diag(ConditionLoc,
4441 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004442 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004443 return true;
4444 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00004445 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00004446 NewStep =
4447 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4448 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004449 Subtract = !Subtract;
4450 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004451 }
4452
4453 Step = NewStep;
4454 SubtractStep = Subtract;
4455 return false;
4456}
4457
Alexey Bataeve3727102018-04-18 15:57:46 +00004458bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004459 // Check init-expr for canonical loop form and save loop counter
4460 // variable - #Var and its initialization value - #LB.
4461 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4462 // var = lb
4463 // integer-type var = lb
4464 // random-access-iterator-type var = lb
4465 // pointer-type var = lb
4466 //
4467 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00004468 if (EmitDiags) {
4469 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4470 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004471 return true;
4472 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004473 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4474 if (!ExprTemp->cleanupsHaveSideEffects())
4475 S = ExprTemp->getSubExpr();
4476
Alexander Musmana5f070a2014-10-01 06:03:56 +00004477 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004478 if (Expr *E = dyn_cast<Expr>(S))
4479 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004480 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004481 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004482 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004483 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4484 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4485 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004486 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4487 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004488 }
4489 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4490 if (ME->isArrow() &&
4491 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004492 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004493 }
4494 }
David Majnemer9d168222016-08-05 17:44:54 +00004495 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004496 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00004497 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00004498 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004499 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00004500 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004501 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004502 diag::ext_omp_loop_not_canonical_init)
4503 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00004504 return setLCDeclAndLB(
4505 Var,
4506 buildDeclRefExpr(SemaRef, Var,
4507 Var->getType().getNonReferenceType(),
4508 DS->getBeginLoc()),
4509 Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004510 }
4511 }
4512 }
David Majnemer9d168222016-08-05 17:44:54 +00004513 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004514 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004515 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00004516 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004517 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4518 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004519 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4520 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004521 }
4522 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4523 if (ME->isArrow() &&
4524 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004525 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004526 }
4527 }
4528 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004529
Alexey Bataeve3727102018-04-18 15:57:46 +00004530 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004531 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00004532 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004533 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00004534 << S->getSourceRange();
4535 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004536 return true;
4537}
4538
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004539/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004540/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00004541static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004542 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00004543 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004544 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00004545 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004546 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004547 if ((Ctor->isCopyOrMoveConstructor() ||
4548 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4549 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004550 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004551 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4552 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004553 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004554 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004555 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004556 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4557 return getCanonicalDecl(ME->getMemberDecl());
4558 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004559}
4560
Alexey Bataeve3727102018-04-18 15:57:46 +00004561bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004562 // Check test-expr for canonical form, save upper-bound UB, flags for
4563 // less/greater and for strict/non-strict comparison.
4564 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4565 // var relational-op b
4566 // b relational-op var
4567 //
4568 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004569 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004570 return true;
4571 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004572 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004573 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00004574 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004575 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004576 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4577 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004578 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4579 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4580 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004581 if (getInitLCDecl(BO->getRHS()) == LCDecl)
4582 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004583 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4584 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4585 BO->getSourceRange(), BO->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00004586 } else if (BO->getOpcode() == BO_NE)
4587 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
4588 BO->getRHS() : BO->getLHS(),
4589 /*LessOp=*/llvm::None,
4590 /*StrictOp=*/true,
4591 BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00004592 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004593 if (CE->getNumArgs() == 2) {
4594 auto Op = CE->getOperator();
4595 switch (Op) {
4596 case OO_Greater:
4597 case OO_GreaterEqual:
4598 case OO_Less:
4599 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004600 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4601 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004602 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4603 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004604 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4605 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004606 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4607 CE->getOperatorLoc());
4608 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004609 case OO_ExclaimEqual:
Kelvin Liefbe4af2018-11-21 19:10:48 +00004610 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
4611 CE->getArg(1) : CE->getArg(0),
4612 /*LessOp=*/llvm::None,
4613 /*StrictOp=*/true,
4614 CE->getSourceRange(),
4615 CE->getOperatorLoc());
4616 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004617 default:
4618 break;
4619 }
4620 }
4621 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004622 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004623 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004624 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004625 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004626 return true;
4627}
4628
Alexey Bataeve3727102018-04-18 15:57:46 +00004629bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004630 // RHS of canonical loop form increment can be:
4631 // var + incr
4632 // incr + var
4633 // var - incr
4634 //
4635 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00004636 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004637 if (BO->isAdditiveOp()) {
4638 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00004639 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4640 return setStep(BO->getRHS(), !IsAdd);
4641 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4642 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004643 }
David Majnemer9d168222016-08-05 17:44:54 +00004644 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004645 bool IsAdd = CE->getOperator() == OO_Plus;
4646 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004647 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4648 return setStep(CE->getArg(1), !IsAdd);
4649 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4650 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004651 }
4652 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004653 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004654 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004655 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004656 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004657 return true;
4658}
4659
Alexey Bataeve3727102018-04-18 15:57:46 +00004660bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004661 // Check incr-expr for canonical loop form and return true if it
4662 // does not conform.
4663 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4664 // ++var
4665 // var++
4666 // --var
4667 // var--
4668 // var += incr
4669 // var -= incr
4670 // var = var + incr
4671 // var = incr + var
4672 // var = var - incr
4673 //
4674 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004675 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004676 return true;
4677 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004678 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4679 if (!ExprTemp->cleanupsHaveSideEffects())
4680 S = ExprTemp->getSubExpr();
4681
Alexander Musmana5f070a2014-10-01 06:03:56 +00004682 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004683 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004684 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004685 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00004686 getInitLCDecl(UO->getSubExpr()) == LCDecl)
4687 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004688 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004689 (UO->isDecrementOp() ? -1 : 1))
4690 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004691 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00004692 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004693 switch (BO->getOpcode()) {
4694 case BO_AddAssign:
4695 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004696 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4697 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004698 break;
4699 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004700 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4701 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004702 break;
4703 default:
4704 break;
4705 }
David Majnemer9d168222016-08-05 17:44:54 +00004706 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004707 switch (CE->getOperator()) {
4708 case OO_PlusPlus:
4709 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00004710 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4711 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00004712 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004713 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004714 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4715 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004716 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004717 break;
4718 case OO_PlusEqual:
4719 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004720 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4721 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004722 break;
4723 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00004724 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4725 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004726 break;
4727 default:
4728 break;
4729 }
4730 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004731 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004732 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004733 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004734 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004735 return true;
4736}
Alexander Musmana5f070a2014-10-01 06:03:56 +00004737
Alexey Bataev5a3af132016-03-29 08:58:54 +00004738static ExprResult
4739tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00004740 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00004741 if (SemaRef.CurContext->isDependentContext())
4742 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004743 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4744 return SemaRef.PerformImplicitConversion(
4745 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4746 /*AllowExplicit=*/true);
4747 auto I = Captures.find(Capture);
4748 if (I != Captures.end())
4749 return buildCapture(SemaRef, Capture, I->second);
4750 DeclRefExpr *Ref = nullptr;
4751 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4752 Captures[Capture] = Ref;
4753 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004754}
4755
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004756/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004757Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004758 Scope *S, const bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00004759 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004760 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00004761 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004762 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004763 SemaRef.getLangOpts().CPlusPlus) {
4764 // Upper - Lower
Kelvin Liefbe4af2018-11-21 19:10:48 +00004765 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
4766 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004767 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4768 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004769 if (!Upper || !Lower)
4770 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004771
4772 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4773
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004774 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004775 // BuildBinOp already emitted error, this one is to point user to upper
4776 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004777 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004778 << Upper->getSourceRange() << Lower->getSourceRange();
4779 return nullptr;
4780 }
4781 }
4782
4783 if (!Diff.isUsable())
4784 return nullptr;
4785
4786 // Upper - Lower [- 1]
4787 if (TestIsStrictOp)
4788 Diff = SemaRef.BuildBinOp(
4789 S, DefaultLoc, BO_Sub, Diff.get(),
4790 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4791 if (!Diff.isUsable())
4792 return nullptr;
4793
4794 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00004795 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004796 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004797 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004798 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004799 if (!Diff.isUsable())
4800 return nullptr;
4801
4802 // Parentheses (for dumping/debugging purposes only).
4803 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4804 if (!Diff.isUsable())
4805 return nullptr;
4806
4807 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004808 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004809 if (!Diff.isUsable())
4810 return nullptr;
4811
Alexander Musman174b3ca2014-10-06 11:16:29 +00004812 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004813 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00004814 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004815 bool UseVarType = VarType->hasIntegerRepresentation() &&
4816 C.getTypeSize(Type) > C.getTypeSize(VarType);
4817 if (!Type->isIntegerType() || UseVarType) {
4818 unsigned NewSize =
4819 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4820 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4821 : Type->hasSignedIntegerRepresentation();
4822 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004823 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4824 Diff = SemaRef.PerformImplicitConversion(
4825 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4826 if (!Diff.isUsable())
4827 return nullptr;
4828 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004829 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004830 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004831 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4832 if (NewSize != C.getTypeSize(Type)) {
4833 if (NewSize < C.getTypeSize(Type)) {
4834 assert(NewSize == 64 && "incorrect loop var size");
4835 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4836 << InitSrcRange << ConditionSrcRange;
4837 }
4838 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004839 NewSize, Type->hasSignedIntegerRepresentation() ||
4840 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004841 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4842 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4843 Sema::AA_Converting, true);
4844 if (!Diff.isUsable())
4845 return nullptr;
4846 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004847 }
4848 }
4849
Alexander Musmana5f070a2014-10-01 06:03:56 +00004850 return Diff.get();
4851}
4852
Alexey Bataeve3727102018-04-18 15:57:46 +00004853Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004854 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00004855 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004856 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4857 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4858 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004859
Alexey Bataeve3727102018-04-18 15:57:46 +00004860 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4861 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004862 if (!NewLB.isUsable() || !NewUB.isUsable())
4863 return nullptr;
4864
Alexey Bataeve3727102018-04-18 15:57:46 +00004865 ExprResult CondExpr =
4866 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004867 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004868 (TestIsStrictOp ? BO_LT : BO_LE) :
4869 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00004870 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004871 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004872 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4873 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004874 CondExpr = SemaRef.PerformImplicitConversion(
4875 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4876 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004877 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004878 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00004879 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004880 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4881}
4882
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004883/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004884DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00004885 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4886 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004887 auto *VD = dyn_cast<VarDecl>(LCDecl);
4888 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004889 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4890 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004891 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004892 const DSAStackTy::DSAVarData Data =
4893 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004894 // If the loop control decl is explicitly marked as private, do not mark it
4895 // as captured again.
4896 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4897 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004898 return Ref;
4899 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00004900 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00004901}
4902
Alexey Bataeve3727102018-04-18 15:57:46 +00004903Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004904 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004905 QualType Type = LCDecl->getType().getNonReferenceType();
4906 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004907 SemaRef, DefaultLoc, Type, LCDecl->getName(),
4908 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4909 isa<VarDecl>(LCDecl)
4910 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4911 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004912 if (PrivateVar->isInvalidDecl())
4913 return nullptr;
4914 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4915 }
4916 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004917}
4918
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004919/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004920Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004921
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004922/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004923Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004924
Alexey Bataevf138fda2018-08-13 19:04:24 +00004925Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
4926 Scope *S, Expr *Counter,
4927 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
4928 Expr *Inc, OverloadedOperatorKind OOK) {
4929 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
4930 if (!Cnt)
4931 return nullptr;
4932 if (Inc) {
4933 assert((OOK == OO_Plus || OOK == OO_Minus) &&
4934 "Expected only + or - operations for depend clauses.");
4935 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
4936 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
4937 if (!Cnt)
4938 return nullptr;
4939 }
4940 ExprResult Diff;
4941 QualType VarType = LCDecl->getType().getNonReferenceType();
4942 if (VarType->isIntegerType() || VarType->isPointerType() ||
4943 SemaRef.getLangOpts().CPlusPlus) {
4944 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00004945 Expr *Upper = TestIsLessOp.getValue()
4946 ? Cnt
4947 : tryBuildCapture(SemaRef, UB, Captures).get();
4948 Expr *Lower = TestIsLessOp.getValue()
4949 ? tryBuildCapture(SemaRef, LB, Captures).get()
4950 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004951 if (!Upper || !Lower)
4952 return nullptr;
4953
4954 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4955
4956 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4957 // BuildBinOp already emitted error, this one is to point user to upper
4958 // and lower bound, and to tell what is passed to 'operator-'.
4959 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4960 << Upper->getSourceRange() << Lower->getSourceRange();
4961 return nullptr;
4962 }
4963 }
4964
4965 if (!Diff.isUsable())
4966 return nullptr;
4967
4968 // Parentheses (for dumping/debugging purposes only).
4969 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4970 if (!Diff.isUsable())
4971 return nullptr;
4972
4973 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4974 if (!NewStep.isUsable())
4975 return nullptr;
4976 // (Upper - Lower) / Step
4977 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4978 if (!Diff.isUsable())
4979 return nullptr;
4980
4981 return Diff.get();
4982}
4983
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004984/// Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004985struct LoopIterationSpace final {
Alexey Bataev316ccf62019-01-29 18:51:58 +00004986 /// True if the condition operator is the strict compare operator (<, > or
4987 /// !=).
4988 bool IsStrictCompare = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004989 /// Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004990 Expr *PreCond = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004991 /// This expression calculates the number of iterations in the loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004992 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004993 Expr *NumIterations = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004994 /// The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004995 Expr *CounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004996 /// Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004997 Expr *PrivateCounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004998 /// This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004999 Expr *CounterInit = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005000 /// This is step for the #CounterVar used to generate its update:
Alexander Musmana5f070a2014-10-01 06:03:56 +00005001 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00005002 Expr *CounterStep = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005003 /// Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00005004 bool Subtract = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005005 /// Source range of the loop init.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005006 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005007 /// Source range of the loop condition.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005008 SourceRange CondSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005009 /// Source range of the loop increment.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005010 SourceRange IncSrcRange;
5011};
5012
Alexey Bataev23b69422014-06-18 07:08:49 +00005013} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005014
Alexey Bataev9c821032015-04-30 04:23:23 +00005015void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
5016 assert(getLangOpts().OpenMP && "OpenMP is not active.");
5017 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005018 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
5019 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00005020 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00005021 DSAStack->loopStart();
Alexey Bataev9c821032015-04-30 04:23:23 +00005022 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00005023 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
5024 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005025 auto *VD = dyn_cast<VarDecl>(D);
5026 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005027 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005028 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00005029 } else {
5030 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
5031 /*WithInit=*/false);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005032 VD = cast<VarDecl>(Ref->getDecl());
5033 }
5034 }
5035 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005036 const Decl *LD = DSAStack->getPossiblyLoopCunter();
5037 if (LD != D->getCanonicalDecl()) {
5038 DSAStack->resetPossibleLoopCounter();
5039 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
5040 MarkDeclarationsReferencedInExpr(
5041 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
5042 Var->getType().getNonLValueExprType(Context),
5043 ForLoc, /*RefersToCapture=*/true));
5044 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005045 }
5046 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005047 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00005048 }
5049}
5050
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005051/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005052/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00005053static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00005054 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
5055 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00005056 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
5057 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00005058 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005059 LoopIterationSpace &ResultIterSpace,
Alexey Bataeve3727102018-04-18 15:57:46 +00005060 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005061 // OpenMP [2.6, Canonical Loop Form]
5062 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00005063 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005064 if (!For) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005065 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005066 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00005067 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00005068 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005069 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005070 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
5071 SemaRef.Diag(DSA.getConstructLoc(),
5072 diag::note_omp_collapse_ordered_expr)
5073 << 2 << CollapseLoopCountExpr->getSourceRange()
5074 << OrderedLoopCountExpr->getSourceRange();
5075 else if (CollapseLoopCountExpr)
5076 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5077 diag::note_omp_collapse_ordered_expr)
5078 << 0 << CollapseLoopCountExpr->getSourceRange();
5079 else
5080 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5081 diag::note_omp_collapse_ordered_expr)
5082 << 1 << OrderedLoopCountExpr->getSourceRange();
5083 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005084 return true;
5085 }
5086 assert(For->getBody());
5087
5088 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
5089
5090 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005091 Stmt *Init = For->getInit();
5092 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005093 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005094
5095 bool HasErrors = false;
5096
5097 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005098 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
5099 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005100
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005101 // OpenMP [2.6, Canonical Loop Form]
5102 // Var is one of the following:
5103 // A variable of signed or unsigned integer type.
5104 // For C++, a variable of a random access iterator type.
5105 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005106 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005107 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
5108 !VarType->isPointerType() &&
5109 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005110 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005111 << SemaRef.getLangOpts().CPlusPlus;
5112 HasErrors = true;
5113 }
5114
5115 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
5116 // a Construct
5117 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5118 // parallel for construct is (are) private.
5119 // The loop iteration variable in the associated for-loop of a simd
5120 // construct with just one associated for-loop is linear with a
5121 // constant-linear-step that is the increment of the associated for-loop.
5122 // Exclude loop var from the list of variables with implicitly defined data
5123 // sharing attributes.
5124 VarsWithImplicitDSA.erase(LCDecl);
5125
5126 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5127 // in a Construct, C/C++].
5128 // The loop iteration variable in the associated for-loop of a simd
5129 // construct with just one associated for-loop may be listed in a linear
5130 // clause with a constant-linear-step that is the increment of the
5131 // associated for-loop.
5132 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5133 // parallel for construct may be listed in a private or lastprivate clause.
5134 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
5135 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
5136 // declared in the loop and it is predetermined as a private.
Alexey Bataeve3727102018-04-18 15:57:46 +00005137 OpenMPClauseKind PredeterminedCKind =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005138 isOpenMPSimdDirective(DKind)
5139 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
5140 : OMPC_private;
5141 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5142 DVar.CKind != PredeterminedCKind) ||
5143 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
5144 isOpenMPDistributeDirective(DKind)) &&
5145 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5146 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
5147 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005148 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005149 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
5150 << getOpenMPClauseName(PredeterminedCKind);
5151 if (DVar.RefExpr == nullptr)
5152 DVar.CKind = PredeterminedCKind;
Alexey Bataeve3727102018-04-18 15:57:46 +00005153 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005154 HasErrors = true;
5155 } else if (LoopDeclRefExpr != nullptr) {
5156 // Make the loop iteration variable private (for worksharing constructs),
5157 // linear (for simd directives with the only one associated loop) or
5158 // lastprivate (for simd directives with several collapsed or ordered
5159 // loops).
5160 if (DVar.CKind == OMPC_unknown)
Alexey Bataevc2cdff62019-01-29 21:12:28 +00005161 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005162 }
5163
5164 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
5165
5166 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005167 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005168
5169 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005170 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005171 }
5172
Alexey Bataeve3727102018-04-18 15:57:46 +00005173 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005174 return HasErrors;
5175
Alexander Musmana5f070a2014-10-01 06:03:56 +00005176 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005177 ResultIterSpace.PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00005178 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
5179 ResultIterSpace.NumIterations = ISC.buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005180 DSA.getCurScope(),
5181 (isOpenMPWorksharingDirective(DKind) ||
5182 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
5183 Captures);
Alexey Bataeve3727102018-04-18 15:57:46 +00005184 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
5185 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
5186 ResultIterSpace.CounterInit = ISC.buildCounterInit();
5187 ResultIterSpace.CounterStep = ISC.buildCounterStep();
5188 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
5189 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
5190 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
5191 ResultIterSpace.Subtract = ISC.shouldSubtractStep();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005192 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005193
Alexey Bataev62dbb972015-04-22 11:59:37 +00005194 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
5195 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005196 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00005197 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005198 ResultIterSpace.CounterInit == nullptr ||
5199 ResultIterSpace.CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00005200 if (!HasErrors && DSA.isOrderedRegion()) {
5201 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
5202 if (CurrentNestedLoopCount <
5203 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
5204 DSA.getOrderedRegionParam().second->setLoopNumIterations(
5205 CurrentNestedLoopCount, ResultIterSpace.NumIterations);
5206 DSA.getOrderedRegionParam().second->setLoopCounter(
5207 CurrentNestedLoopCount, ResultIterSpace.CounterVar);
5208 }
5209 }
5210 for (auto &Pair : DSA.getDoacrossDependClauses()) {
5211 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
5212 // Erroneous case - clause has some problems.
5213 continue;
5214 }
5215 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
5216 Pair.second.size() <= CurrentNestedLoopCount) {
5217 // Erroneous case - clause has some problems.
5218 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
5219 continue;
5220 }
5221 Expr *CntValue;
5222 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5223 CntValue = ISC.buildOrderedLoopData(
5224 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5225 Pair.first->getDependencyLoc());
5226 else
5227 CntValue = ISC.buildOrderedLoopData(
5228 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5229 Pair.first->getDependencyLoc(),
5230 Pair.second[CurrentNestedLoopCount].first,
5231 Pair.second[CurrentNestedLoopCount].second);
5232 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
5233 }
5234 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005235
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005236 return HasErrors;
5237}
5238
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005239/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005240static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00005241buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005242 ExprResult Start,
Alexey Bataeve3727102018-04-18 15:57:46 +00005243 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005244 // Build 'VarRef = Start.
Alexey Bataeve3727102018-04-18 15:57:46 +00005245 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005246 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005247 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00005248 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00005249 VarRef.get()->getType())) {
5250 NewStart = SemaRef.PerformImplicitConversion(
5251 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
5252 /*AllowExplicit=*/true);
5253 if (!NewStart.isUsable())
5254 return ExprError();
5255 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005256
Alexey Bataeve3727102018-04-18 15:57:46 +00005257 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005258 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5259 return Init;
5260}
5261
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005262/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00005263static ExprResult buildCounterUpdate(
5264 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5265 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
5266 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005267 // Add parentheses (for debugging purposes only).
5268 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
5269 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
5270 !Step.isUsable())
5271 return ExprError();
5272
Alexey Bataev5a3af132016-03-29 08:58:54 +00005273 ExprResult NewStep = Step;
5274 if (Captures)
5275 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005276 if (NewStep.isInvalid())
5277 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005278 ExprResult Update =
5279 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005280 if (!Update.isUsable())
5281 return ExprError();
5282
Alexey Bataevc0214e02016-02-16 12:13:49 +00005283 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
5284 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005285 ExprResult NewStart = Start;
5286 if (Captures)
5287 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005288 if (NewStart.isInvalid())
5289 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005290
Alexey Bataevc0214e02016-02-16 12:13:49 +00005291 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5292 ExprResult SavedUpdate = Update;
5293 ExprResult UpdateVal;
5294 if (VarRef.get()->getType()->isOverloadableType() ||
5295 NewStart.get()->getType()->isOverloadableType() ||
5296 Update.get()->getType()->isOverloadableType()) {
5297 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5298 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5299 Update =
5300 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5301 if (Update.isUsable()) {
5302 UpdateVal =
5303 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5304 VarRef.get(), SavedUpdate.get());
5305 if (UpdateVal.isUsable()) {
5306 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5307 UpdateVal.get());
5308 }
5309 }
5310 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5311 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005312
Alexey Bataevc0214e02016-02-16 12:13:49 +00005313 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5314 if (!Update.isUsable() || !UpdateVal.isUsable()) {
5315 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5316 NewStart.get(), SavedUpdate.get());
5317 if (!Update.isUsable())
5318 return ExprError();
5319
Alexey Bataev11481f52016-02-17 10:29:05 +00005320 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5321 VarRef.get()->getType())) {
5322 Update = SemaRef.PerformImplicitConversion(
5323 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5324 if (!Update.isUsable())
5325 return ExprError();
5326 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00005327
5328 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5329 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005330 return Update;
5331}
5332
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005333/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005334/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005335static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005336 if (E == nullptr)
5337 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00005338 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005339 QualType OldType = E->getType();
5340 unsigned HasBits = C.getTypeSize(OldType);
5341 if (HasBits >= Bits)
5342 return ExprResult(E);
5343 // OK to convert to signed, because new type has more bits than old.
5344 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5345 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5346 true);
5347}
5348
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005349/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005350/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005351static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005352 if (E == nullptr)
5353 return false;
5354 llvm::APSInt Result;
5355 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5356 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5357 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005358}
5359
Alexey Bataev5a3af132016-03-29 08:58:54 +00005360/// Build preinits statement for the given declarations.
5361static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00005362 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005363 if (!PreInits.empty()) {
5364 return new (Context) DeclStmt(
5365 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5366 SourceLocation(), SourceLocation());
5367 }
5368 return nullptr;
5369}
5370
5371/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00005372static Stmt *
5373buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00005374 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005375 if (!Captures.empty()) {
5376 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00005377 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00005378 PreInits.push_back(Pair.second->getDecl());
5379 return buildPreInits(Context, PreInits);
5380 }
5381 return nullptr;
5382}
5383
5384/// Build postupdate expression for the given list of postupdates expressions.
5385static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5386 Expr *PostUpdate = nullptr;
5387 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005388 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005389 Expr *ConvE = S.BuildCStyleCastExpr(
5390 E->getExprLoc(),
5391 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5392 E->getExprLoc(), E)
5393 .get();
5394 PostUpdate = PostUpdate
5395 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5396 PostUpdate, ConvE)
5397 .get()
5398 : ConvE;
5399 }
5400 }
5401 return PostUpdate;
5402}
5403
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005404/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00005405/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5406/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005407static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00005408checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00005409 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5410 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00005411 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00005412 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005413 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005414 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005415 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005416 Expr::EvalResult Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005417 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Fangrui Song407659a2018-11-30 23:41:18 +00005418 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005419 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005420 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005421 if (OrderedLoopCountExpr) {
5422 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005423 Expr::EvalResult EVResult;
5424 if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5425 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005426 if (Result.getLimitedValue() < NestedLoopCount) {
5427 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5428 diag::err_omp_wrong_ordered_loop_count)
5429 << OrderedLoopCountExpr->getSourceRange();
5430 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5431 diag::note_collapse_loop_count)
5432 << CollapseLoopCountExpr->getSourceRange();
5433 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005434 OrderedLoopCount = Result.getLimitedValue();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005435 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005436 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005437 // This is helper routine for loop directives (e.g., 'for', 'simd',
5438 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00005439 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00005440 SmallVector<LoopIterationSpace, 4> IterSpaces(
5441 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00005442 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005443 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005444 if (checkOpenMPIterationSpace(
5445 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5446 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5447 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5448 Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00005449 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005450 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005451 // OpenMP [2.8.1, simd construct, Restrictions]
5452 // All loops associated with the construct must be perfectly nested; that
5453 // is, there must be no intervening code nor any OpenMP directive between
5454 // any two loops.
5455 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005456 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005457 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5458 if (checkOpenMPIterationSpace(
5459 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5460 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5461 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5462 Captures))
5463 return 0;
5464 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5465 // Handle initialization of captured loop iterator variables.
5466 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5467 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5468 Captures[DRE] = DRE;
5469 }
5470 }
5471 // Move on to the next nested for loop, or to the loop body.
5472 // OpenMP [2.8.1, simd construct, Restrictions]
5473 // All loops associated with the construct must be perfectly nested; that
5474 // is, there must be no intervening code nor any OpenMP directive between
5475 // any two loops.
5476 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5477 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005478
Alexander Musmana5f070a2014-10-01 06:03:56 +00005479 Built.clear(/* size */ NestedLoopCount);
5480
5481 if (SemaRef.CurContext->isDependentContext())
5482 return NestedLoopCount;
5483
5484 // An example of what is generated for the following code:
5485 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00005486 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00005487 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005488 // for (k = 0; k < NK; ++k)
5489 // for (j = J0; j < NJ; j+=2) {
5490 // <loop body>
5491 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005492 //
5493 // We generate the code below.
5494 // Note: the loop body may be outlined in CodeGen.
5495 // Note: some counters may be C++ classes, operator- is used to find number of
5496 // iterations and operator+= to calculate counter value.
5497 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5498 // or i64 is currently supported).
5499 //
5500 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5501 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5502 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5503 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5504 // // similar updates for vars in clauses (e.g. 'linear')
5505 // <loop body (using local i and j)>
5506 // }
5507 // i = NI; // assign final values of counters
5508 // j = NJ;
5509 //
5510
5511 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5512 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00005513 // Precondition tests if there is at least one iteration (all conditions are
5514 // true).
5515 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00005516 Expr *N0 = IterSpaces[0].NumIterations;
5517 ExprResult LastIteration32 =
5518 widenIterationCount(/*Bits=*/32,
5519 SemaRef
5520 .PerformImplicitConversion(
5521 N0->IgnoreImpCasts(), N0->getType(),
5522 Sema::AA_Converting, /*AllowExplicit=*/true)
5523 .get(),
5524 SemaRef);
5525 ExprResult LastIteration64 = widenIterationCount(
5526 /*Bits=*/64,
5527 SemaRef
5528 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5529 Sema::AA_Converting,
5530 /*AllowExplicit=*/true)
5531 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005532 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005533
5534 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5535 return NestedLoopCount;
5536
Alexey Bataeve3727102018-04-18 15:57:46 +00005537 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005538 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5539
5540 Scope *CurScope = DSA.getCurScope();
5541 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00005542 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00005543 PreCond =
5544 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5545 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00005546 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005547 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00005548 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005549 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5550 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005551 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005552 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005553 SemaRef
5554 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5555 Sema::AA_Converting,
5556 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005557 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005558 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005559 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005560 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005561 SemaRef
5562 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5563 Sema::AA_Converting,
5564 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005565 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005566 }
5567
5568 // Choose either the 32-bit or 64-bit version.
5569 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005570 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
5571 (LastIteration32.isUsable() &&
5572 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5573 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5574 fitsInto(
5575 /*Bits=*/32,
5576 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5577 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00005578 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00005579 QualType VType = LastIteration.get()->getType();
5580 QualType RealVType = VType;
5581 QualType StrideVType = VType;
5582 if (isOpenMPTaskLoopDirective(DKind)) {
5583 VType =
5584 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5585 StrideVType =
5586 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5587 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005588
5589 if (!LastIteration.isUsable())
5590 return 0;
5591
5592 // Save the number of iterations.
5593 ExprResult NumIterations = LastIteration;
5594 {
5595 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005596 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5597 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005598 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5599 if (!LastIteration.isUsable())
5600 return 0;
5601 }
5602
5603 // Calculate the last iteration number beforehand instead of doing this on
5604 // each iteration. Do not do this if the number of iterations may be kfold-ed.
5605 llvm::APSInt Result;
5606 bool IsConstant =
5607 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5608 ExprResult CalcLastIteration;
5609 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005610 ExprResult SaveRef =
5611 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005612 LastIteration = SaveRef;
5613
5614 // Prepare SaveRef + 1.
5615 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005616 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005617 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5618 if (!NumIterations.isUsable())
5619 return 0;
5620 }
5621
5622 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5623
David Majnemer9d168222016-08-05 17:44:54 +00005624 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005625 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005626 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5627 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005628 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005629 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5630 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005631 SemaRef.AddInitializerToDecl(LBDecl,
5632 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5633 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005634
5635 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005636 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
5637 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00005638 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00005639 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005640
5641 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
5642 // This will be used to implement clause 'lastprivate'.
5643 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005644 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
5645 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005646 SemaRef.AddInitializerToDecl(ILDecl,
5647 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5648 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005649
5650 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00005651 VarDecl *STDecl =
5652 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
5653 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005654 SemaRef.AddInitializerToDecl(STDecl,
5655 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
5656 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005657
5658 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00005659 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00005660 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
5661 UB.get(), LastIteration.get());
5662 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00005663 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
5664 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00005665 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
5666 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005667 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005668
5669 // If we have a combined directive that combines 'distribute', 'for' or
5670 // 'simd' we need to be able to access the bounds of the schedule of the
5671 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
5672 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
5673 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00005674 // Lower bound variable, initialized with zero.
5675 VarDecl *CombLBDecl =
5676 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
5677 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
5678 SemaRef.AddInitializerToDecl(
5679 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5680 /*DirectInit*/ false);
5681
5682 // Upper bound variable, initialized with last iteration number.
5683 VarDecl *CombUBDecl =
5684 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
5685 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
5686 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
5687 /*DirectInit*/ false);
5688
5689 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
5690 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
5691 ExprResult CombCondOp =
5692 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
5693 LastIteration.get(), CombUB.get());
5694 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
5695 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005696 CombEUB =
5697 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005698
Alexey Bataeve3727102018-04-18 15:57:46 +00005699 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005700 // We expect to have at least 2 more parameters than the 'parallel'
5701 // directive does - the lower and upper bounds of the previous schedule.
5702 assert(CD->getNumParams() >= 4 &&
5703 "Unexpected number of parameters in loop combined directive");
5704
5705 // Set the proper type for the bounds given what we learned from the
5706 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005707 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
5708 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005709
5710 // Previous lower and upper bounds are obtained from the region
5711 // parameters.
5712 PrevLB =
5713 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
5714 PrevUB =
5715 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
5716 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005717 }
5718
5719 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005720 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005721 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005722 {
Alexey Bataev7292c292016-04-25 12:22:29 +00005723 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
5724 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00005725 Expr *RHS =
5726 (isOpenMPWorksharingDirective(DKind) ||
5727 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5728 ? LB.get()
5729 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005730 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005731 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005732
5733 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5734 Expr *CombRHS =
5735 (isOpenMPWorksharingDirective(DKind) ||
5736 isOpenMPTaskLoopDirective(DKind) ||
5737 isOpenMPDistributeDirective(DKind))
5738 ? CombLB.get()
5739 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5740 CombInit =
5741 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005742 CombInit =
5743 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005744 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005745 }
5746
Alexey Bataev316ccf62019-01-29 18:51:58 +00005747 bool UseStrictCompare =
5748 RealVType->hasUnsignedIntegerRepresentation() &&
5749 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
5750 return LIS.IsStrictCompare;
5751 });
5752 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
5753 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005754 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005755 Expr *BoundUB = UB.get();
5756 if (UseStrictCompare) {
5757 BoundUB =
5758 SemaRef
5759 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
5760 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5761 .get();
5762 BoundUB =
5763 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
5764 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005765 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005766 (isOpenMPWorksharingDirective(DKind) ||
5767 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00005768 ? SemaRef.BuildBinOp(CurScope, CondLoc,
5769 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
5770 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00005771 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5772 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005773 ExprResult CombDistCond;
5774 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005775 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5776 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005777 }
5778
Carlo Bertolliffafe102017-04-20 00:39:39 +00005779 ExprResult CombCond;
5780 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005781 Expr *BoundCombUB = CombUB.get();
5782 if (UseStrictCompare) {
5783 BoundCombUB =
5784 SemaRef
5785 .BuildBinOp(
5786 CurScope, CondLoc, BO_Add, BoundCombUB,
5787 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5788 .get();
5789 BoundCombUB =
5790 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
5791 .get();
5792 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00005793 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005794 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5795 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005796 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005797 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005798 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005799 ExprResult Inc =
5800 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5801 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5802 if (!Inc.isUsable())
5803 return 0;
5804 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005805 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005806 if (!Inc.isUsable())
5807 return 0;
5808
5809 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5810 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005811 // In combined construct, add combined version that use CombLB and CombUB
5812 // base variables for the update
5813 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005814 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5815 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005816 // LB + ST
5817 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5818 if (!NextLB.isUsable())
5819 return 0;
5820 // LB = LB + ST
5821 NextLB =
5822 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005823 NextLB =
5824 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005825 if (!NextLB.isUsable())
5826 return 0;
5827 // UB + ST
5828 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5829 if (!NextUB.isUsable())
5830 return 0;
5831 // UB = UB + ST
5832 NextUB =
5833 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005834 NextUB =
5835 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005836 if (!NextUB.isUsable())
5837 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005838 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5839 CombNextLB =
5840 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5841 if (!NextLB.isUsable())
5842 return 0;
5843 // LB = LB + ST
5844 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5845 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005846 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
5847 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005848 if (!CombNextLB.isUsable())
5849 return 0;
5850 // UB + ST
5851 CombNextUB =
5852 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5853 if (!CombNextUB.isUsable())
5854 return 0;
5855 // UB = UB + ST
5856 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5857 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005858 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
5859 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005860 if (!CombNextUB.isUsable())
5861 return 0;
5862 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005863 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005864
Carlo Bertolliffafe102017-04-20 00:39:39 +00005865 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00005866 // directive with for as IV = IV + ST; ensure upper bound expression based
5867 // on PrevUB instead of NumIterations - used to implement 'for' when found
5868 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005869 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005870 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00005871 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005872 DistCond = SemaRef.BuildBinOp(
5873 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005874 assert(DistCond.isUsable() && "distribute cond expr was not built");
5875
5876 DistInc =
5877 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5878 assert(DistInc.isUsable() && "distribute inc expr was not built");
5879 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5880 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005881 DistInc =
5882 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005883 assert(DistInc.isUsable() && "distribute inc expr was not built");
5884
5885 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5886 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005887 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005888 ExprResult IsUBGreater =
5889 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5890 ExprResult CondOp = SemaRef.ActOnConditionalOp(
5891 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5892 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5893 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005894 PrevEUB =
5895 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005896
Alexey Bataev316ccf62019-01-29 18:51:58 +00005897 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
5898 // parallel for is in combination with a distribute directive with
5899 // schedule(static, 1)
5900 Expr *BoundPrevUB = PrevUB.get();
5901 if (UseStrictCompare) {
5902 BoundPrevUB =
5903 SemaRef
5904 .BuildBinOp(
5905 CurScope, CondLoc, BO_Add, BoundPrevUB,
5906 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5907 .get();
5908 BoundPrevUB =
5909 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
5910 .get();
5911 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005912 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005913 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5914 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005915 }
5916
Alexander Musmana5f070a2014-10-01 06:03:56 +00005917 // Build updates and final values of the loop counters.
5918 bool HasErrors = false;
5919 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005920 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005921 Built.Updates.resize(NestedLoopCount);
5922 Built.Finals.resize(NestedLoopCount);
5923 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005924 // We implement the following algorithm for obtaining the
5925 // original loop iteration variable values based on the
5926 // value of the collapsed loop iteration variable IV.
5927 //
5928 // Let n+1 be the number of collapsed loops in the nest.
5929 // Iteration variables (I0, I1, .... In)
5930 // Iteration counts (N0, N1, ... Nn)
5931 //
5932 // Acc = IV;
5933 //
5934 // To compute Ik for loop k, 0 <= k <= n, generate:
5935 // Prod = N(k+1) * N(k+2) * ... * Nn;
5936 // Ik = Acc / Prod;
5937 // Acc -= Ik * Prod;
5938 //
5939 ExprResult Acc = IV;
5940 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005941 LoopIterationSpace &IS = IterSpaces[Cnt];
5942 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005943 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005944
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005945 // Compute prod
5946 ExprResult Prod =
5947 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5948 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
5949 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
5950 IterSpaces[K].NumIterations);
5951
5952 // Iter = Acc / Prod
5953 // If there is at least one more inner loop to avoid
5954 // multiplication by 1.
5955 if (Cnt + 1 < NestedLoopCount)
5956 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
5957 Acc.get(), Prod.get());
5958 else
5959 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005960 if (!Iter.isUsable()) {
5961 HasErrors = true;
5962 break;
5963 }
5964
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005965 // Update Acc:
5966 // Acc -= Iter * Prod
5967 // Check if there is at least one more inner loop to avoid
5968 // multiplication by 1.
5969 if (Cnt + 1 < NestedLoopCount)
5970 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
5971 Iter.get(), Prod.get());
5972 else
5973 Prod = Iter;
5974 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
5975 Acc.get(), Prod.get());
5976
Alexey Bataev39f915b82015-05-08 10:41:21 +00005977 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005978 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00005979 DeclRefExpr *CounterVar = buildDeclRefExpr(
5980 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5981 /*RefersToCapture=*/true);
5982 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005983 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005984 if (!Init.isUsable()) {
5985 HasErrors = true;
5986 break;
5987 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005988 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005989 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5990 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005991 if (!Update.isUsable()) {
5992 HasErrors = true;
5993 break;
5994 }
5995
5996 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataeve3727102018-04-18 15:57:46 +00005997 ExprResult Final = buildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00005998 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005999 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006000 if (!Final.isUsable()) {
6001 HasErrors = true;
6002 break;
6003 }
6004
Alexander Musmana5f070a2014-10-01 06:03:56 +00006005 if (!Update.isUsable() || !Final.isUsable()) {
6006 HasErrors = true;
6007 break;
6008 }
6009 // Save results
6010 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00006011 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006012 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006013 Built.Updates[Cnt] = Update.get();
6014 Built.Finals[Cnt] = Final.get();
6015 }
6016 }
6017
6018 if (HasErrors)
6019 return 0;
6020
6021 // Save results
6022 Built.IterationVarRef = IV.get();
6023 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00006024 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006025 Built.CalcLastIteration = SemaRef
6026 .ActOnFinishFullExpr(CalcLastIteration.get(),
6027 /*DiscardedValue*/ false)
6028 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006029 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00006030 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006031 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006032 Built.Init = Init.get();
6033 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00006034 Built.LB = LB.get();
6035 Built.UB = UB.get();
6036 Built.IL = IL.get();
6037 Built.ST = ST.get();
6038 Built.EUB = EUB.get();
6039 Built.NLB = NextLB.get();
6040 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00006041 Built.PrevLB = PrevLB.get();
6042 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00006043 Built.DistInc = DistInc.get();
6044 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00006045 Built.DistCombinedFields.LB = CombLB.get();
6046 Built.DistCombinedFields.UB = CombUB.get();
6047 Built.DistCombinedFields.EUB = CombEUB.get();
6048 Built.DistCombinedFields.Init = CombInit.get();
6049 Built.DistCombinedFields.Cond = CombCond.get();
6050 Built.DistCombinedFields.NLB = CombNextLB.get();
6051 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006052 Built.DistCombinedFields.DistCond = CombDistCond.get();
6053 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006054
Alexey Bataevabfc0692014-06-25 06:52:00 +00006055 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006056}
6057
Alexey Bataev10e775f2015-07-30 11:36:16 +00006058static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006059 auto CollapseClauses =
6060 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
6061 if (CollapseClauses.begin() != CollapseClauses.end())
6062 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006063 return nullptr;
6064}
6065
Alexey Bataev10e775f2015-07-30 11:36:16 +00006066static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006067 auto OrderedClauses =
6068 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
6069 if (OrderedClauses.begin() != OrderedClauses.end())
6070 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00006071 return nullptr;
6072}
6073
Kelvin Lic5609492016-07-15 04:39:07 +00006074static bool checkSimdlenSafelenSpecified(Sema &S,
6075 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006076 const OMPSafelenClause *Safelen = nullptr;
6077 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00006078
Alexey Bataeve3727102018-04-18 15:57:46 +00006079 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00006080 if (Clause->getClauseKind() == OMPC_safelen)
6081 Safelen = cast<OMPSafelenClause>(Clause);
6082 else if (Clause->getClauseKind() == OMPC_simdlen)
6083 Simdlen = cast<OMPSimdlenClause>(Clause);
6084 if (Safelen && Simdlen)
6085 break;
6086 }
6087
6088 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006089 const Expr *SimdlenLength = Simdlen->getSimdlen();
6090 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00006091 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
6092 SimdlenLength->isInstantiationDependent() ||
6093 SimdlenLength->containsUnexpandedParameterPack())
6094 return false;
6095 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
6096 SafelenLength->isInstantiationDependent() ||
6097 SafelenLength->containsUnexpandedParameterPack())
6098 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00006099 Expr::EvalResult SimdlenResult, SafelenResult;
6100 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
6101 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
6102 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
6103 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00006104 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
6105 // If both simdlen and safelen clauses are specified, the value of the
6106 // simdlen parameter must be less than or equal to the value of the safelen
6107 // parameter.
6108 if (SimdlenRes > SafelenRes) {
6109 S.Diag(SimdlenLength->getExprLoc(),
6110 diag::err_omp_wrong_simdlen_safelen_values)
6111 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
6112 return true;
6113 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00006114 }
6115 return false;
6116}
6117
Alexey Bataeve3727102018-04-18 15:57:46 +00006118StmtResult
6119Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6120 SourceLocation StartLoc, SourceLocation EndLoc,
6121 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006122 if (!AStmt)
6123 return StmtError();
6124
6125 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006126 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006127 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6128 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006129 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006130 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6131 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006132 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006133 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006134
Alexander Musmana5f070a2014-10-01 06:03:56 +00006135 assert((CurContext->isDependentContext() || B.builtAll()) &&
6136 "omp simd loop exprs were not built");
6137
Alexander Musman3276a272015-03-21 10:12:56 +00006138 if (!CurContext->isDependentContext()) {
6139 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006140 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006141 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00006142 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006143 B.NumIterations, *this, CurScope,
6144 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00006145 return StmtError();
6146 }
6147 }
6148
Kelvin Lic5609492016-07-15 04:39:07 +00006149 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006150 return StmtError();
6151
Reid Kleckner87a31802018-03-12 21:43:02 +00006152 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006153 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6154 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006155}
6156
Alexey Bataeve3727102018-04-18 15:57:46 +00006157StmtResult
6158Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6159 SourceLocation StartLoc, SourceLocation EndLoc,
6160 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006161 if (!AStmt)
6162 return StmtError();
6163
6164 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006165 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006166 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6167 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006168 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006169 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6170 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006171 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00006172 return StmtError();
6173
Alexander Musmana5f070a2014-10-01 06:03:56 +00006174 assert((CurContext->isDependentContext() || B.builtAll()) &&
6175 "omp for loop exprs were not built");
6176
Alexey Bataev54acd402015-08-04 11:18:19 +00006177 if (!CurContext->isDependentContext()) {
6178 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006179 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006180 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006181 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006182 B.NumIterations, *this, CurScope,
6183 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006184 return StmtError();
6185 }
6186 }
6187
Reid Kleckner87a31802018-03-12 21:43:02 +00006188 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006189 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006190 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00006191}
6192
Alexander Musmanf82886e2014-09-18 05:12:34 +00006193StmtResult Sema::ActOnOpenMPForSimdDirective(
6194 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006195 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006196 if (!AStmt)
6197 return StmtError();
6198
6199 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006200 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006201 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6202 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00006203 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006204 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006205 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6206 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006207 if (NestedLoopCount == 0)
6208 return StmtError();
6209
Alexander Musmanc6388682014-12-15 07:07:06 +00006210 assert((CurContext->isDependentContext() || B.builtAll()) &&
6211 "omp for simd loop exprs were not built");
6212
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006213 if (!CurContext->isDependentContext()) {
6214 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006215 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006216 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006217 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006218 B.NumIterations, *this, CurScope,
6219 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006220 return StmtError();
6221 }
6222 }
6223
Kelvin Lic5609492016-07-15 04:39:07 +00006224 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006225 return StmtError();
6226
Reid Kleckner87a31802018-03-12 21:43:02 +00006227 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006228 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6229 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006230}
6231
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006232StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
6233 Stmt *AStmt,
6234 SourceLocation StartLoc,
6235 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006236 if (!AStmt)
6237 return StmtError();
6238
6239 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006240 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006241 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006242 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006243 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006244 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006245 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006246 return StmtError();
6247 // All associated statements must be '#pragma omp section' except for
6248 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006249 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006250 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6251 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006252 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006253 diag::err_omp_sections_substmt_not_section);
6254 return StmtError();
6255 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006256 cast<OMPSectionDirective>(SectionStmt)
6257 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006258 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006259 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006260 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006261 return StmtError();
6262 }
6263
Reid Kleckner87a31802018-03-12 21:43:02 +00006264 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006265
Alexey Bataev25e5b442015-09-15 12:52:43 +00006266 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6267 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006268}
6269
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006270StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
6271 SourceLocation StartLoc,
6272 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006273 if (!AStmt)
6274 return StmtError();
6275
6276 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006277
Reid Kleckner87a31802018-03-12 21:43:02 +00006278 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00006279 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006280
Alexey Bataev25e5b442015-09-15 12:52:43 +00006281 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
6282 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006283}
6284
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006285StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
6286 Stmt *AStmt,
6287 SourceLocation StartLoc,
6288 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006289 if (!AStmt)
6290 return StmtError();
6291
6292 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00006293
Reid Kleckner87a31802018-03-12 21:43:02 +00006294 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00006295
Alexey Bataev3255bf32015-01-19 05:20:46 +00006296 // OpenMP [2.7.3, single Construct, Restrictions]
6297 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00006298 const OMPClause *Nowait = nullptr;
6299 const OMPClause *Copyprivate = nullptr;
6300 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00006301 if (Clause->getClauseKind() == OMPC_nowait)
6302 Nowait = Clause;
6303 else if (Clause->getClauseKind() == OMPC_copyprivate)
6304 Copyprivate = Clause;
6305 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006306 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00006307 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006308 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00006309 return StmtError();
6310 }
6311 }
6312
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006313 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6314}
6315
Alexander Musman80c22892014-07-17 08:54:58 +00006316StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6317 SourceLocation StartLoc,
6318 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006319 if (!AStmt)
6320 return StmtError();
6321
6322 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00006323
Reid Kleckner87a31802018-03-12 21:43:02 +00006324 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00006325
6326 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6327}
6328
Alexey Bataev28c75412015-12-15 08:19:24 +00006329StmtResult Sema::ActOnOpenMPCriticalDirective(
6330 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6331 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006332 if (!AStmt)
6333 return StmtError();
6334
6335 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006336
Alexey Bataev28c75412015-12-15 08:19:24 +00006337 bool ErrorFound = false;
6338 llvm::APSInt Hint;
6339 SourceLocation HintLoc;
6340 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006341 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006342 if (C->getClauseKind() == OMPC_hint) {
6343 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006344 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00006345 ErrorFound = true;
6346 }
6347 Expr *E = cast<OMPHintClause>(C)->getHint();
6348 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00006349 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006350 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006351 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00006352 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006353 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00006354 }
6355 }
6356 }
6357 if (ErrorFound)
6358 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006359 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00006360 if (Pair.first && DirName.getName() && !DependentHint) {
6361 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6362 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00006363 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00006364 Diag(HintLoc, diag::note_omp_critical_hint_here)
6365 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006366 else
Alexey Bataev28c75412015-12-15 08:19:24 +00006367 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00006368 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006369 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00006370 << 1
6371 << C->getHint()->EvaluateKnownConstInt(Context).toString(
6372 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006373 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006374 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00006375 }
Alexey Bataev28c75412015-12-15 08:19:24 +00006376 }
6377 }
6378
Reid Kleckner87a31802018-03-12 21:43:02 +00006379 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006380
Alexey Bataev28c75412015-12-15 08:19:24 +00006381 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6382 Clauses, AStmt);
6383 if (!Pair.first && DirName.getName() && !DependentHint)
6384 DSAStack->addCriticalWithHint(Dir, Hint);
6385 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006386}
6387
Alexey Bataev4acb8592014-07-07 13:01:15 +00006388StmtResult Sema::ActOnOpenMPParallelForDirective(
6389 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006390 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006391 if (!AStmt)
6392 return StmtError();
6393
Alexey Bataeve3727102018-04-18 15:57:46 +00006394 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006395 // 1.2.2 OpenMP Language Terminology
6396 // Structured block - An executable statement with a single entry at the
6397 // top and a single exit at the bottom.
6398 // The point of exit cannot be a branch out of the structured block.
6399 // longjmp() and throw() must not violate the entry/exit criteria.
6400 CS->getCapturedDecl()->setNothrow();
6401
Alexander Musmanc6388682014-12-15 07:07:06 +00006402 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006403 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6404 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006405 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006406 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006407 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6408 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006409 if (NestedLoopCount == 0)
6410 return StmtError();
6411
Alexander Musmana5f070a2014-10-01 06:03:56 +00006412 assert((CurContext->isDependentContext() || B.builtAll()) &&
6413 "omp parallel for loop exprs were not built");
6414
Alexey Bataev54acd402015-08-04 11:18:19 +00006415 if (!CurContext->isDependentContext()) {
6416 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006417 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006418 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006419 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006420 B.NumIterations, *this, CurScope,
6421 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006422 return StmtError();
6423 }
6424 }
6425
Reid Kleckner87a31802018-03-12 21:43:02 +00006426 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006427 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006428 NestedLoopCount, Clauses, AStmt, B,
6429 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00006430}
6431
Alexander Musmane4e893b2014-09-23 09:33:00 +00006432StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6433 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006434 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006435 if (!AStmt)
6436 return StmtError();
6437
Alexey Bataeve3727102018-04-18 15:57:46 +00006438 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006439 // 1.2.2 OpenMP Language Terminology
6440 // Structured block - An executable statement with a single entry at the
6441 // top and a single exit at the bottom.
6442 // The point of exit cannot be a branch out of the structured block.
6443 // longjmp() and throw() must not violate the entry/exit criteria.
6444 CS->getCapturedDecl()->setNothrow();
6445
Alexander Musmanc6388682014-12-15 07:07:06 +00006446 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006447 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6448 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00006449 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006450 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006451 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6452 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006453 if (NestedLoopCount == 0)
6454 return StmtError();
6455
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006456 if (!CurContext->isDependentContext()) {
6457 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006458 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006459 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006460 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006461 B.NumIterations, *this, CurScope,
6462 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006463 return StmtError();
6464 }
6465 }
6466
Kelvin Lic5609492016-07-15 04:39:07 +00006467 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006468 return StmtError();
6469
Reid Kleckner87a31802018-03-12 21:43:02 +00006470 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006471 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00006472 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006473}
6474
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006475StmtResult
6476Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6477 Stmt *AStmt, SourceLocation StartLoc,
6478 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006479 if (!AStmt)
6480 return StmtError();
6481
6482 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006483 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006484 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006485 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006486 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006487 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006488 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006489 return StmtError();
6490 // All associated statements must be '#pragma omp section' except for
6491 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006492 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006493 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6494 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006495 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006496 diag::err_omp_parallel_sections_substmt_not_section);
6497 return StmtError();
6498 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006499 cast<OMPSectionDirective>(SectionStmt)
6500 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006501 }
6502 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006503 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006504 diag::err_omp_parallel_sections_not_compound_stmt);
6505 return StmtError();
6506 }
6507
Reid Kleckner87a31802018-03-12 21:43:02 +00006508 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006509
Alexey Bataev25e5b442015-09-15 12:52:43 +00006510 return OMPParallelSectionsDirective::Create(
6511 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006512}
6513
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006514StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6515 Stmt *AStmt, SourceLocation StartLoc,
6516 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006517 if (!AStmt)
6518 return StmtError();
6519
David Majnemer9d168222016-08-05 17:44:54 +00006520 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006521 // 1.2.2 OpenMP Language Terminology
6522 // Structured block - An executable statement with a single entry at the
6523 // top and a single exit at the bottom.
6524 // The point of exit cannot be a branch out of the structured block.
6525 // longjmp() and throw() must not violate the entry/exit criteria.
6526 CS->getCapturedDecl()->setNothrow();
6527
Reid Kleckner87a31802018-03-12 21:43:02 +00006528 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006529
Alexey Bataev25e5b442015-09-15 12:52:43 +00006530 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6531 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006532}
6533
Alexey Bataev68446b72014-07-18 07:47:19 +00006534StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6535 SourceLocation EndLoc) {
6536 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6537}
6538
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00006539StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6540 SourceLocation EndLoc) {
6541 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6542}
6543
Alexey Bataev2df347a2014-07-18 10:17:07 +00006544StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6545 SourceLocation EndLoc) {
6546 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6547}
6548
Alexey Bataev169d96a2017-07-18 20:17:46 +00006549StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6550 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006551 SourceLocation StartLoc,
6552 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006553 if (!AStmt)
6554 return StmtError();
6555
6556 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006557
Reid Kleckner87a31802018-03-12 21:43:02 +00006558 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006559
Alexey Bataev169d96a2017-07-18 20:17:46 +00006560 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00006561 AStmt,
6562 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006563}
6564
Alexey Bataev6125da92014-07-21 11:26:11 +00006565StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6566 SourceLocation StartLoc,
6567 SourceLocation EndLoc) {
6568 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6569 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6570}
6571
Alexey Bataev346265e2015-09-25 10:37:12 +00006572StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6573 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006574 SourceLocation StartLoc,
6575 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006576 const OMPClause *DependFound = nullptr;
6577 const OMPClause *DependSourceClause = nullptr;
6578 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00006579 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006580 const OMPThreadsClause *TC = nullptr;
6581 const OMPSIMDClause *SC = nullptr;
6582 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00006583 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6584 DependFound = C;
6585 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6586 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006587 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00006588 << getOpenMPDirectiveName(OMPD_ordered)
6589 << getOpenMPClauseName(OMPC_depend) << 2;
6590 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006591 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00006592 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00006593 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006594 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006595 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006596 << 0;
6597 ErrorFound = true;
6598 }
6599 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6600 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006601 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006602 << 1;
6603 ErrorFound = true;
6604 }
6605 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00006606 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006607 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00006608 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006609 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006610 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006611 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006612 }
Alexey Bataeveb482352015-12-18 05:05:56 +00006613 if (!ErrorFound && !SC &&
6614 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006615 // OpenMP [2.8.1,simd Construct, Restrictions]
6616 // An ordered construct with the simd clause is the only OpenMP construct
6617 // that can appear in the simd region.
6618 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00006619 ErrorFound = true;
6620 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006621 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00006622 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6623 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006624 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006625 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00006626 diag::err_omp_ordered_directive_without_param);
6627 ErrorFound = true;
6628 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006629 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006630 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00006631 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6632 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006633 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00006634 ErrorFound = true;
6635 }
6636 }
6637 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006638 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00006639
6640 if (AStmt) {
6641 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6642
Reid Kleckner87a31802018-03-12 21:43:02 +00006643 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006644 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006645
6646 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006647}
6648
Alexey Bataev1d160b12015-03-13 12:27:31 +00006649namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006650/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006651/// construct.
6652class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006653 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006654 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006655 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006656 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006657 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006658 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006659 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006660 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006661 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006662 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006663 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006664 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006665 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006666 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006667 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00006668 /// expression.
6669 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006670 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00006671 /// part.
6672 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006673 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006674 NoError
6675 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006676 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006677 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006678 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00006679 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006680 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006681 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006682 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006683 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006684 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00006685 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6686 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6687 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006688 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00006689 /// important for non-associative operations.
6690 bool IsXLHSInRHSPart;
6691 BinaryOperatorKind Op;
6692 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006693 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006694 /// if it is a prefix unary operation.
6695 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006696
6697public:
6698 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00006699 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00006700 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006701 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006702 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00006703 /// expression. If DiagId and NoteId == 0, then only check is performed
6704 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006705 /// \param DiagId Diagnostic which should be emitted if error is found.
6706 /// \param NoteId Diagnostic note for the main error message.
6707 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00006708 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006709 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006710 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006711 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006712 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006713 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00006714 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6715 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6716 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006717 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00006718 /// false otherwise.
6719 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
6720
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006721 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006722 /// if it is a prefix unary operation.
6723 bool isPostfixUpdate() const { return IsPostfixUpdate; }
6724
Alexey Bataev1d160b12015-03-13 12:27:31 +00006725private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00006726 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
6727 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00006728};
6729} // namespace
6730
6731bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
6732 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
6733 ExprAnalysisErrorCode ErrorFound = NoError;
6734 SourceLocation ErrorLoc, NoteLoc;
6735 SourceRange ErrorRange, NoteRange;
6736 // Allowed constructs are:
6737 // x = x binop expr;
6738 // x = expr binop x;
6739 if (AtomicBinOp->getOpcode() == BO_Assign) {
6740 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00006741 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006742 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
6743 if (AtomicInnerBinOp->isMultiplicativeOp() ||
6744 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
6745 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006746 Op = AtomicInnerBinOp->getOpcode();
6747 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00006748 Expr *LHS = AtomicInnerBinOp->getLHS();
6749 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006750 llvm::FoldingSetNodeID XId, LHSId, RHSId;
6751 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
6752 /*Canonical=*/true);
6753 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
6754 /*Canonical=*/true);
6755 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
6756 /*Canonical=*/true);
6757 if (XId == LHSId) {
6758 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006759 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006760 } else if (XId == RHSId) {
6761 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006762 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006763 } else {
6764 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6765 ErrorRange = AtomicInnerBinOp->getSourceRange();
6766 NoteLoc = X->getExprLoc();
6767 NoteRange = X->getSourceRange();
6768 ErrorFound = NotAnUpdateExpression;
6769 }
6770 } else {
6771 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6772 ErrorRange = AtomicInnerBinOp->getSourceRange();
6773 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
6774 NoteRange = SourceRange(NoteLoc, NoteLoc);
6775 ErrorFound = NotABinaryOperator;
6776 }
6777 } else {
6778 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
6779 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
6780 ErrorFound = NotABinaryExpression;
6781 }
6782 } else {
6783 ErrorLoc = AtomicBinOp->getExprLoc();
6784 ErrorRange = AtomicBinOp->getSourceRange();
6785 NoteLoc = AtomicBinOp->getOperatorLoc();
6786 NoteRange = SourceRange(NoteLoc, NoteLoc);
6787 ErrorFound = NotAnAssignmentOp;
6788 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006789 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006790 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6791 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6792 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006793 }
6794 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006795 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006796 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006797}
6798
6799bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6800 unsigned NoteId) {
6801 ExprAnalysisErrorCode ErrorFound = NoError;
6802 SourceLocation ErrorLoc, NoteLoc;
6803 SourceRange ErrorRange, NoteRange;
6804 // Allowed constructs are:
6805 // x++;
6806 // x--;
6807 // ++x;
6808 // --x;
6809 // x binop= expr;
6810 // x = x binop expr;
6811 // x = expr binop x;
6812 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6813 AtomicBody = AtomicBody->IgnoreParenImpCasts();
6814 if (AtomicBody->getType()->isScalarType() ||
6815 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006816 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006817 AtomicBody->IgnoreParenImpCasts())) {
6818 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00006819 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006820 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00006821 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006822 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006823 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006824 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006825 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6826 AtomicBody->IgnoreParenImpCasts())) {
6827 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00006828 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00006829 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006830 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00006831 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006832 // Check for Unary Operation
6833 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006834 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006835 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6836 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006837 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006838 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6839 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006840 } else {
6841 ErrorFound = NotAnUnaryIncDecExpression;
6842 ErrorLoc = AtomicUnaryOp->getExprLoc();
6843 ErrorRange = AtomicUnaryOp->getSourceRange();
6844 NoteLoc = AtomicUnaryOp->getOperatorLoc();
6845 NoteRange = SourceRange(NoteLoc, NoteLoc);
6846 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006847 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006848 ErrorFound = NotABinaryOrUnaryExpression;
6849 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6850 NoteRange = ErrorRange = AtomicBody->getSourceRange();
6851 }
6852 } else {
6853 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006854 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006855 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6856 }
6857 } else {
6858 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006859 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006860 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6861 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006862 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006863 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6864 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6865 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006866 }
6867 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006868 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006869 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006870 // Build an update expression of form 'OpaqueValueExpr(x) binop
6871 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6872 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6873 auto *OVEX = new (SemaRef.getASTContext())
6874 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6875 auto *OVEExpr = new (SemaRef.getASTContext())
6876 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00006877 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00006878 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6879 IsXLHSInRHSPart ? OVEExpr : OVEX);
6880 if (Update.isInvalid())
6881 return true;
6882 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6883 Sema::AA_Casting);
6884 if (Update.isInvalid())
6885 return true;
6886 UpdateExpr = Update.get();
6887 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00006888 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006889}
6890
Alexey Bataev0162e452014-07-22 10:10:35 +00006891StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6892 Stmt *AStmt,
6893 SourceLocation StartLoc,
6894 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006895 if (!AStmt)
6896 return StmtError();
6897
David Majnemer9d168222016-08-05 17:44:54 +00006898 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00006899 // 1.2.2 OpenMP Language Terminology
6900 // Structured block - An executable statement with a single entry at the
6901 // top and a single exit at the bottom.
6902 // The point of exit cannot be a branch out of the structured block.
6903 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00006904 OpenMPClauseKind AtomicKind = OMPC_unknown;
6905 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00006906 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00006907 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00006908 C->getClauseKind() == OMPC_update ||
6909 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00006910 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006911 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006912 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00006913 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6914 << getOpenMPClauseName(AtomicKind);
6915 } else {
6916 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006917 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006918 }
6919 }
6920 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006921
Alexey Bataeve3727102018-04-18 15:57:46 +00006922 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00006923 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6924 Body = EWC->getSubExpr();
6925
Alexey Bataev62cec442014-11-18 10:14:22 +00006926 Expr *X = nullptr;
6927 Expr *V = nullptr;
6928 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006929 Expr *UE = nullptr;
6930 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006931 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006932 // OpenMP [2.12.6, atomic Construct]
6933 // In the next expressions:
6934 // * x and v (as applicable) are both l-value expressions with scalar type.
6935 // * During the execution of an atomic region, multiple syntactic
6936 // occurrences of x must designate the same storage location.
6937 // * Neither of v and expr (as applicable) may access the storage location
6938 // designated by x.
6939 // * Neither of x and expr (as applicable) may access the storage location
6940 // designated by v.
6941 // * expr is an expression with scalar type.
6942 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6943 // * binop, binop=, ++, and -- are not overloaded operators.
6944 // * The expression x binop expr must be numerically equivalent to x binop
6945 // (expr). This requirement is satisfied if the operators in expr have
6946 // precedence greater than binop, or by using parentheses around expr or
6947 // subexpressions of expr.
6948 // * The expression expr binop x must be numerically equivalent to (expr)
6949 // binop x. This requirement is satisfied if the operators in expr have
6950 // precedence equal to or greater than binop, or by using parentheses around
6951 // expr or subexpressions of expr.
6952 // * For forms that allow multiple occurrences of x, the number of times
6953 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006954 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006955 enum {
6956 NotAnExpression,
6957 NotAnAssignmentOp,
6958 NotAScalarType,
6959 NotAnLValue,
6960 NoError
6961 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006962 SourceLocation ErrorLoc, NoteLoc;
6963 SourceRange ErrorRange, NoteRange;
6964 // If clause is read:
6965 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006966 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6967 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006968 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6969 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6970 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6971 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6972 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6973 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6974 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006975 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00006976 ErrorFound = NotAnLValue;
6977 ErrorLoc = AtomicBinOp->getExprLoc();
6978 ErrorRange = AtomicBinOp->getSourceRange();
6979 NoteLoc = NotLValueExpr->getExprLoc();
6980 NoteRange = NotLValueExpr->getSourceRange();
6981 }
6982 } else if (!X->isInstantiationDependent() ||
6983 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006984 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00006985 (X->isInstantiationDependent() || X->getType()->isScalarType())
6986 ? V
6987 : X;
6988 ErrorFound = NotAScalarType;
6989 ErrorLoc = AtomicBinOp->getExprLoc();
6990 ErrorRange = AtomicBinOp->getSourceRange();
6991 NoteLoc = NotScalarExpr->getExprLoc();
6992 NoteRange = NotScalarExpr->getSourceRange();
6993 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006994 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00006995 ErrorFound = NotAnAssignmentOp;
6996 ErrorLoc = AtomicBody->getExprLoc();
6997 ErrorRange = AtomicBody->getSourceRange();
6998 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6999 : AtomicBody->getExprLoc();
7000 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7001 : AtomicBody->getSourceRange();
7002 }
7003 } else {
7004 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007005 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00007006 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00007007 }
Alexey Bataev62cec442014-11-18 10:14:22 +00007008 if (ErrorFound != NoError) {
7009 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
7010 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00007011 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7012 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00007013 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007014 }
7015 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00007016 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00007017 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007018 enum {
7019 NotAnExpression,
7020 NotAnAssignmentOp,
7021 NotAScalarType,
7022 NotAnLValue,
7023 NoError
7024 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00007025 SourceLocation ErrorLoc, NoteLoc;
7026 SourceRange ErrorRange, NoteRange;
7027 // If clause is write:
7028 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00007029 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7030 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007031 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7032 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00007033 X = AtomicBinOp->getLHS();
7034 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007035 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7036 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
7037 if (!X->isLValue()) {
7038 ErrorFound = NotAnLValue;
7039 ErrorLoc = AtomicBinOp->getExprLoc();
7040 ErrorRange = AtomicBinOp->getSourceRange();
7041 NoteLoc = X->getExprLoc();
7042 NoteRange = X->getSourceRange();
7043 }
7044 } else if (!X->isInstantiationDependent() ||
7045 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007046 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007047 (X->isInstantiationDependent() || X->getType()->isScalarType())
7048 ? E
7049 : X;
7050 ErrorFound = NotAScalarType;
7051 ErrorLoc = AtomicBinOp->getExprLoc();
7052 ErrorRange = AtomicBinOp->getSourceRange();
7053 NoteLoc = NotScalarExpr->getExprLoc();
7054 NoteRange = NotScalarExpr->getSourceRange();
7055 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007056 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00007057 ErrorFound = NotAnAssignmentOp;
7058 ErrorLoc = AtomicBody->getExprLoc();
7059 ErrorRange = AtomicBody->getSourceRange();
7060 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7061 : AtomicBody->getExprLoc();
7062 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7063 : AtomicBody->getSourceRange();
7064 }
7065 } else {
7066 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007067 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007068 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00007069 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00007070 if (ErrorFound != NoError) {
7071 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
7072 << ErrorRange;
7073 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7074 << NoteRange;
7075 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007076 }
7077 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00007078 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007079 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007080 // If clause is update:
7081 // x++;
7082 // x--;
7083 // ++x;
7084 // --x;
7085 // x binop= expr;
7086 // x = x binop expr;
7087 // x = expr binop x;
7088 OpenMPAtomicUpdateChecker Checker(*this);
7089 if (Checker.checkStatement(
7090 Body, (AtomicKind == OMPC_update)
7091 ? diag::err_omp_atomic_update_not_expression_statement
7092 : diag::err_omp_atomic_not_expression_statement,
7093 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00007094 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007095 if (!CurContext->isDependentContext()) {
7096 E = Checker.getExpr();
7097 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007098 UE = Checker.getUpdateExpr();
7099 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00007100 }
Alexey Bataev459dec02014-07-24 06:46:57 +00007101 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007102 enum {
7103 NotAnAssignmentOp,
7104 NotACompoundStatement,
7105 NotTwoSubstatements,
7106 NotASpecificExpression,
7107 NoError
7108 } ErrorFound = NoError;
7109 SourceLocation ErrorLoc, NoteLoc;
7110 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00007111 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007112 // If clause is a capture:
7113 // v = x++;
7114 // v = x--;
7115 // v = ++x;
7116 // v = --x;
7117 // v = x binop= expr;
7118 // v = x = x binop expr;
7119 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00007120 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00007121 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7122 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7123 V = AtomicBinOp->getLHS();
7124 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7125 OpenMPAtomicUpdateChecker Checker(*this);
7126 if (Checker.checkStatement(
7127 Body, diag::err_omp_atomic_capture_not_expression_statement,
7128 diag::note_omp_atomic_update))
7129 return StmtError();
7130 E = Checker.getExpr();
7131 X = Checker.getX();
7132 UE = Checker.getUpdateExpr();
7133 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7134 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00007135 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007136 ErrorLoc = AtomicBody->getExprLoc();
7137 ErrorRange = AtomicBody->getSourceRange();
7138 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7139 : AtomicBody->getExprLoc();
7140 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7141 : AtomicBody->getSourceRange();
7142 ErrorFound = NotAnAssignmentOp;
7143 }
7144 if (ErrorFound != NoError) {
7145 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
7146 << ErrorRange;
7147 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7148 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007149 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007150 if (CurContext->isDependentContext())
7151 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007152 } else {
7153 // If clause is a capture:
7154 // { v = x; x = expr; }
7155 // { v = x; x++; }
7156 // { v = x; x--; }
7157 // { v = x; ++x; }
7158 // { v = x; --x; }
7159 // { v = x; x binop= expr; }
7160 // { v = x; x = x binop expr; }
7161 // { v = x; x = expr binop x; }
7162 // { x++; v = x; }
7163 // { x--; v = x; }
7164 // { ++x; v = x; }
7165 // { --x; v = x; }
7166 // { x binop= expr; v = x; }
7167 // { x = x binop expr; v = x; }
7168 // { x = expr binop x; v = x; }
7169 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
7170 // Check that this is { expr1; expr2; }
7171 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007172 Stmt *First = CS->body_front();
7173 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007174 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
7175 First = EWC->getSubExpr()->IgnoreParenImpCasts();
7176 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
7177 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
7178 // Need to find what subexpression is 'v' and what is 'x'.
7179 OpenMPAtomicUpdateChecker Checker(*this);
7180 bool IsUpdateExprFound = !Checker.checkStatement(Second);
7181 BinaryOperator *BinOp = nullptr;
7182 if (IsUpdateExprFound) {
7183 BinOp = dyn_cast<BinaryOperator>(First);
7184 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7185 }
7186 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7187 // { v = x; x++; }
7188 // { v = x; x--; }
7189 // { v = x; ++x; }
7190 // { v = x; --x; }
7191 // { v = x; x binop= expr; }
7192 // { v = x; x = x binop expr; }
7193 // { v = x; x = expr binop x; }
7194 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007195 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007196 llvm::FoldingSetNodeID XId, PossibleXId;
7197 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7198 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7199 IsUpdateExprFound = XId == PossibleXId;
7200 if (IsUpdateExprFound) {
7201 V = BinOp->getLHS();
7202 X = Checker.getX();
7203 E = Checker.getExpr();
7204 UE = Checker.getUpdateExpr();
7205 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007206 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007207 }
7208 }
7209 if (!IsUpdateExprFound) {
7210 IsUpdateExprFound = !Checker.checkStatement(First);
7211 BinOp = nullptr;
7212 if (IsUpdateExprFound) {
7213 BinOp = dyn_cast<BinaryOperator>(Second);
7214 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7215 }
7216 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7217 // { x++; v = x; }
7218 // { x--; v = x; }
7219 // { ++x; v = x; }
7220 // { --x; v = x; }
7221 // { x binop= expr; v = x; }
7222 // { x = x binop expr; v = x; }
7223 // { x = expr binop x; v = x; }
7224 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007225 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007226 llvm::FoldingSetNodeID XId, PossibleXId;
7227 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7228 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7229 IsUpdateExprFound = XId == PossibleXId;
7230 if (IsUpdateExprFound) {
7231 V = BinOp->getLHS();
7232 X = Checker.getX();
7233 E = Checker.getExpr();
7234 UE = Checker.getUpdateExpr();
7235 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007236 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007237 }
7238 }
7239 }
7240 if (!IsUpdateExprFound) {
7241 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00007242 auto *FirstExpr = dyn_cast<Expr>(First);
7243 auto *SecondExpr = dyn_cast<Expr>(Second);
7244 if (!FirstExpr || !SecondExpr ||
7245 !(FirstExpr->isInstantiationDependent() ||
7246 SecondExpr->isInstantiationDependent())) {
7247 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
7248 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007249 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00007250 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007251 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007252 NoteRange = ErrorRange = FirstBinOp
7253 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00007254 : SourceRange(ErrorLoc, ErrorLoc);
7255 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00007256 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
7257 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
7258 ErrorFound = NotAnAssignmentOp;
7259 NoteLoc = ErrorLoc = SecondBinOp
7260 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007261 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007262 NoteRange = ErrorRange =
7263 SecondBinOp ? SecondBinOp->getSourceRange()
7264 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00007265 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007266 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00007267 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00007268 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00007269 SecondBinOp->getLHS()->IgnoreParenImpCasts();
7270 llvm::FoldingSetNodeID X1Id, X2Id;
7271 PossibleXRHSInFirst->Profile(X1Id, Context,
7272 /*Canonical=*/true);
7273 PossibleXLHSInSecond->Profile(X2Id, Context,
7274 /*Canonical=*/true);
7275 IsUpdateExprFound = X1Id == X2Id;
7276 if (IsUpdateExprFound) {
7277 V = FirstBinOp->getLHS();
7278 X = SecondBinOp->getLHS();
7279 E = SecondBinOp->getRHS();
7280 UE = nullptr;
7281 IsXLHSInRHSPart = false;
7282 IsPostfixUpdate = true;
7283 } else {
7284 ErrorFound = NotASpecificExpression;
7285 ErrorLoc = FirstBinOp->getExprLoc();
7286 ErrorRange = FirstBinOp->getSourceRange();
7287 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
7288 NoteRange = SecondBinOp->getRHS()->getSourceRange();
7289 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007290 }
7291 }
7292 }
7293 }
7294 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007295 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007296 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007297 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007298 ErrorFound = NotTwoSubstatements;
7299 }
7300 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007301 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007302 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007303 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007304 ErrorFound = NotACompoundStatement;
7305 }
7306 if (ErrorFound != NoError) {
7307 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7308 << ErrorRange;
7309 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7310 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007311 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007312 if (CurContext->isDependentContext())
7313 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00007314 }
Alexey Bataevdea47612014-07-23 07:46:59 +00007315 }
Alexey Bataev0162e452014-07-22 10:10:35 +00007316
Reid Kleckner87a31802018-03-12 21:43:02 +00007317 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00007318
Alexey Bataev62cec442014-11-18 10:14:22 +00007319 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00007320 X, V, E, UE, IsXLHSInRHSPart,
7321 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00007322}
7323
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007324StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7325 Stmt *AStmt,
7326 SourceLocation StartLoc,
7327 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007328 if (!AStmt)
7329 return StmtError();
7330
Alexey Bataeve3727102018-04-18 15:57:46 +00007331 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00007332 // 1.2.2 OpenMP Language Terminology
7333 // Structured block - An executable statement with a single entry at the
7334 // top and a single exit at the bottom.
7335 // The point of exit cannot be a branch out of the structured block.
7336 // longjmp() and throw() must not violate the entry/exit criteria.
7337 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007338 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7339 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7340 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7341 // 1.2.2 OpenMP Language Terminology
7342 // Structured block - An executable statement with a single entry at the
7343 // top and a single exit at the bottom.
7344 // The point of exit cannot be a branch out of the structured block.
7345 // longjmp() and throw() must not violate the entry/exit criteria.
7346 CS->getCapturedDecl()->setNothrow();
7347 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007348
Alexey Bataev13314bf2014-10-09 04:18:56 +00007349 // OpenMP [2.16, Nesting of Regions]
7350 // If specified, a teams construct must be contained within a target
7351 // construct. That target construct must contain no statements or directives
7352 // outside of the teams construct.
7353 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007354 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007355 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007356 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00007357 auto I = CS->body_begin();
7358 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007359 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00007360 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7361 OMPTeamsFound) {
7362
Alexey Bataev13314bf2014-10-09 04:18:56 +00007363 OMPTeamsFound = false;
7364 break;
7365 }
7366 ++I;
7367 }
7368 assert(I != CS->body_end() && "Not found statement");
7369 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00007370 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007371 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00007372 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00007373 }
7374 if (!OMPTeamsFound) {
7375 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7376 Diag(DSAStack->getInnerTeamsRegionLoc(),
7377 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007378 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00007379 << isa<OMPExecutableDirective>(S);
7380 return StmtError();
7381 }
7382 }
7383
Reid Kleckner87a31802018-03-12 21:43:02 +00007384 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007385
7386 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7387}
7388
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007389StmtResult
7390Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7391 Stmt *AStmt, SourceLocation StartLoc,
7392 SourceLocation EndLoc) {
7393 if (!AStmt)
7394 return StmtError();
7395
Alexey Bataeve3727102018-04-18 15:57:46 +00007396 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007397 // 1.2.2 OpenMP Language Terminology
7398 // Structured block - An executable statement with a single entry at the
7399 // top and a single exit at the bottom.
7400 // The point of exit cannot be a branch out of the structured block.
7401 // longjmp() and throw() must not violate the entry/exit criteria.
7402 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007403 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7404 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7405 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7406 // 1.2.2 OpenMP Language Terminology
7407 // Structured block - An executable statement with a single entry at the
7408 // top and a single exit at the bottom.
7409 // The point of exit cannot be a branch out of the structured block.
7410 // longjmp() and throw() must not violate the entry/exit criteria.
7411 CS->getCapturedDecl()->setNothrow();
7412 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007413
Reid Kleckner87a31802018-03-12 21:43:02 +00007414 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007415
7416 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7417 AStmt);
7418}
7419
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007420StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7421 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007422 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007423 if (!AStmt)
7424 return StmtError();
7425
Alexey Bataeve3727102018-04-18 15:57:46 +00007426 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007427 // 1.2.2 OpenMP Language Terminology
7428 // Structured block - An executable statement with a single entry at the
7429 // top and a single exit at the bottom.
7430 // The point of exit cannot be a branch out of the structured block.
7431 // longjmp() and throw() must not violate the entry/exit criteria.
7432 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007433 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7434 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7435 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7436 // 1.2.2 OpenMP Language Terminology
7437 // Structured block - An executable statement with a single entry at the
7438 // top and a single exit at the bottom.
7439 // The point of exit cannot be a branch out of the structured block.
7440 // longjmp() and throw() must not violate the entry/exit criteria.
7441 CS->getCapturedDecl()->setNothrow();
7442 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007443
7444 OMPLoopDirective::HelperExprs B;
7445 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7446 // define the nested loops number.
7447 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007448 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007449 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007450 VarsWithImplicitDSA, B);
7451 if (NestedLoopCount == 0)
7452 return StmtError();
7453
7454 assert((CurContext->isDependentContext() || B.builtAll()) &&
7455 "omp target parallel for loop exprs were not built");
7456
7457 if (!CurContext->isDependentContext()) {
7458 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007459 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007460 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007461 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007462 B.NumIterations, *this, CurScope,
7463 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007464 return StmtError();
7465 }
7466 }
7467
Reid Kleckner87a31802018-03-12 21:43:02 +00007468 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007469 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7470 NestedLoopCount, Clauses, AStmt,
7471 B, DSAStack->isCancelRegion());
7472}
7473
Alexey Bataev95b64a92017-05-30 16:00:04 +00007474/// Check for existence of a map clause in the list of clauses.
7475static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7476 const OpenMPClauseKind K) {
7477 return llvm::any_of(
7478 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7479}
Samuel Antaodf67fc42016-01-19 19:15:56 +00007480
Alexey Bataev95b64a92017-05-30 16:00:04 +00007481template <typename... Params>
7482static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7483 const Params... ClauseTypes) {
7484 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007485}
7486
Michael Wong65f367f2015-07-21 13:44:28 +00007487StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7488 Stmt *AStmt,
7489 SourceLocation StartLoc,
7490 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007491 if (!AStmt)
7492 return StmtError();
7493
7494 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7495
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007496 // OpenMP [2.10.1, Restrictions, p. 97]
7497 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007498 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7499 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7500 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00007501 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007502 return StmtError();
7503 }
7504
Reid Kleckner87a31802018-03-12 21:43:02 +00007505 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00007506
7507 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7508 AStmt);
7509}
7510
Samuel Antaodf67fc42016-01-19 19:15:56 +00007511StmtResult
7512Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7513 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007514 SourceLocation EndLoc, Stmt *AStmt) {
7515 if (!AStmt)
7516 return StmtError();
7517
Alexey Bataeve3727102018-04-18 15:57:46 +00007518 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007519 // 1.2.2 OpenMP Language Terminology
7520 // Structured block - An executable statement with a single entry at the
7521 // top and a single exit at the bottom.
7522 // The point of exit cannot be a branch out of the structured block.
7523 // longjmp() and throw() must not violate the entry/exit criteria.
7524 CS->getCapturedDecl()->setNothrow();
7525 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7526 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7527 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7528 // 1.2.2 OpenMP Language Terminology
7529 // Structured block - An executable statement with a single entry at the
7530 // top and a single exit at the bottom.
7531 // The point of exit cannot be a branch out of the structured block.
7532 // longjmp() and throw() must not violate the entry/exit criteria.
7533 CS->getCapturedDecl()->setNothrow();
7534 }
7535
Samuel Antaodf67fc42016-01-19 19:15:56 +00007536 // OpenMP [2.10.2, Restrictions, p. 99]
7537 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007538 if (!hasClauses(Clauses, OMPC_map)) {
7539 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7540 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007541 return StmtError();
7542 }
7543
Alexey Bataev7828b252017-11-21 17:08:48 +00007544 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7545 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007546}
7547
Samuel Antao72590762016-01-19 20:04:50 +00007548StmtResult
7549Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7550 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007551 SourceLocation EndLoc, Stmt *AStmt) {
7552 if (!AStmt)
7553 return StmtError();
7554
Alexey Bataeve3727102018-04-18 15:57:46 +00007555 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007556 // 1.2.2 OpenMP Language Terminology
7557 // Structured block - An executable statement with a single entry at the
7558 // top and a single exit at the bottom.
7559 // The point of exit cannot be a branch out of the structured block.
7560 // longjmp() and throw() must not violate the entry/exit criteria.
7561 CS->getCapturedDecl()->setNothrow();
7562 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7563 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7564 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7565 // 1.2.2 OpenMP Language Terminology
7566 // Structured block - An executable statement with a single entry at the
7567 // top and a single exit at the bottom.
7568 // The point of exit cannot be a branch out of the structured block.
7569 // longjmp() and throw() must not violate the entry/exit criteria.
7570 CS->getCapturedDecl()->setNothrow();
7571 }
7572
Samuel Antao72590762016-01-19 20:04:50 +00007573 // OpenMP [2.10.3, Restrictions, p. 102]
7574 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007575 if (!hasClauses(Clauses, OMPC_map)) {
7576 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7577 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00007578 return StmtError();
7579 }
7580
Alexey Bataev7828b252017-11-21 17:08:48 +00007581 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7582 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00007583}
7584
Samuel Antao686c70c2016-05-26 17:30:50 +00007585StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7586 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007587 SourceLocation EndLoc,
7588 Stmt *AStmt) {
7589 if (!AStmt)
7590 return StmtError();
7591
Alexey Bataeve3727102018-04-18 15:57:46 +00007592 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007593 // 1.2.2 OpenMP Language Terminology
7594 // Structured block - An executable statement with a single entry at the
7595 // top and a single exit at the bottom.
7596 // The point of exit cannot be a branch out of the structured block.
7597 // longjmp() and throw() must not violate the entry/exit criteria.
7598 CS->getCapturedDecl()->setNothrow();
7599 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7600 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7601 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7602 // 1.2.2 OpenMP Language Terminology
7603 // Structured block - An executable statement with a single entry at the
7604 // top and a single exit at the bottom.
7605 // The point of exit cannot be a branch out of the structured block.
7606 // longjmp() and throw() must not violate the entry/exit criteria.
7607 CS->getCapturedDecl()->setNothrow();
7608 }
7609
Alexey Bataev95b64a92017-05-30 16:00:04 +00007610 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00007611 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7612 return StmtError();
7613 }
Alexey Bataev7828b252017-11-21 17:08:48 +00007614 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7615 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00007616}
7617
Alexey Bataev13314bf2014-10-09 04:18:56 +00007618StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7619 Stmt *AStmt, SourceLocation StartLoc,
7620 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007621 if (!AStmt)
7622 return StmtError();
7623
Alexey Bataeve3727102018-04-18 15:57:46 +00007624 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007625 // 1.2.2 OpenMP Language Terminology
7626 // Structured block - An executable statement with a single entry at the
7627 // top and a single exit at the bottom.
7628 // The point of exit cannot be a branch out of the structured block.
7629 // longjmp() and throw() must not violate the entry/exit criteria.
7630 CS->getCapturedDecl()->setNothrow();
7631
Reid Kleckner87a31802018-03-12 21:43:02 +00007632 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00007633
Alexey Bataevceabd412017-11-30 18:01:54 +00007634 DSAStack->setParentTeamsRegionLoc(StartLoc);
7635
Alexey Bataev13314bf2014-10-09 04:18:56 +00007636 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7637}
7638
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007639StmtResult
7640Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7641 SourceLocation EndLoc,
7642 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007643 if (DSAStack->isParentNowaitRegion()) {
7644 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
7645 return StmtError();
7646 }
7647 if (DSAStack->isParentOrderedRegion()) {
7648 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
7649 return StmtError();
7650 }
7651 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
7652 CancelRegion);
7653}
7654
Alexey Bataev87933c72015-09-18 08:07:34 +00007655StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7656 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00007657 SourceLocation EndLoc,
7658 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00007659 if (DSAStack->isParentNowaitRegion()) {
7660 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
7661 return StmtError();
7662 }
7663 if (DSAStack->isParentOrderedRegion()) {
7664 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
7665 return StmtError();
7666 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007667 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00007668 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7669 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00007670}
7671
Alexey Bataev382967a2015-12-08 12:06:20 +00007672static bool checkGrainsizeNumTasksClauses(Sema &S,
7673 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007674 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00007675 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007676 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00007677 if (C->getClauseKind() == OMPC_grainsize ||
7678 C->getClauseKind() == OMPC_num_tasks) {
7679 if (!PrevClause)
7680 PrevClause = C;
7681 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007682 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007683 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
7684 << getOpenMPClauseName(C->getClauseKind())
7685 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007686 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007687 diag::note_omp_previous_grainsize_num_tasks)
7688 << getOpenMPClauseName(PrevClause->getClauseKind());
7689 ErrorFound = true;
7690 }
7691 }
7692 }
7693 return ErrorFound;
7694}
7695
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007696static bool checkReductionClauseWithNogroup(Sema &S,
7697 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007698 const OMPClause *ReductionClause = nullptr;
7699 const OMPClause *NogroupClause = nullptr;
7700 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007701 if (C->getClauseKind() == OMPC_reduction) {
7702 ReductionClause = C;
7703 if (NogroupClause)
7704 break;
7705 continue;
7706 }
7707 if (C->getClauseKind() == OMPC_nogroup) {
7708 NogroupClause = C;
7709 if (ReductionClause)
7710 break;
7711 continue;
7712 }
7713 }
7714 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007715 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
7716 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007717 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007718 return true;
7719 }
7720 return false;
7721}
7722
Alexey Bataev49f6e782015-12-01 04:18:41 +00007723StmtResult Sema::ActOnOpenMPTaskLoopDirective(
7724 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007725 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00007726 if (!AStmt)
7727 return StmtError();
7728
7729 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7730 OMPLoopDirective::HelperExprs B;
7731 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7732 // define the nested loops number.
7733 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007734 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007735 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00007736 VarsWithImplicitDSA, B);
7737 if (NestedLoopCount == 0)
7738 return StmtError();
7739
7740 assert((CurContext->isDependentContext() || B.builtAll()) &&
7741 "omp for loop exprs were not built");
7742
Alexey Bataev382967a2015-12-08 12:06:20 +00007743 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7744 // The grainsize clause and num_tasks clause are mutually exclusive and may
7745 // not appear on the same taskloop directive.
7746 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7747 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007748 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7749 // If a reduction clause is present on the taskloop directive, the nogroup
7750 // clause must not be specified.
7751 if (checkReductionClauseWithNogroup(*this, Clauses))
7752 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007753
Reid Kleckner87a31802018-03-12 21:43:02 +00007754 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00007755 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
7756 NestedLoopCount, Clauses, AStmt, B);
7757}
7758
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007759StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
7760 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007761 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007762 if (!AStmt)
7763 return StmtError();
7764
7765 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7766 OMPLoopDirective::HelperExprs B;
7767 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7768 // define the nested loops number.
7769 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007770 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007771 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7772 VarsWithImplicitDSA, B);
7773 if (NestedLoopCount == 0)
7774 return StmtError();
7775
7776 assert((CurContext->isDependentContext() || B.builtAll()) &&
7777 "omp for loop exprs were not built");
7778
Alexey Bataev5a3af132016-03-29 08:58:54 +00007779 if (!CurContext->isDependentContext()) {
7780 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007781 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007782 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007783 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007784 B.NumIterations, *this, CurScope,
7785 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007786 return StmtError();
7787 }
7788 }
7789
Alexey Bataev382967a2015-12-08 12:06:20 +00007790 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7791 // The grainsize clause and num_tasks clause are mutually exclusive and may
7792 // not appear on the same taskloop directive.
7793 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7794 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007795 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7796 // If a reduction clause is present on the taskloop directive, the nogroup
7797 // clause must not be specified.
7798 if (checkReductionClauseWithNogroup(*this, Clauses))
7799 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00007800 if (checkSimdlenSafelenSpecified(*this, Clauses))
7801 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007802
Reid Kleckner87a31802018-03-12 21:43:02 +00007803 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007804 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7805 NestedLoopCount, Clauses, AStmt, B);
7806}
7807
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007808StmtResult Sema::ActOnOpenMPDistributeDirective(
7809 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007810 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007811 if (!AStmt)
7812 return StmtError();
7813
7814 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7815 OMPLoopDirective::HelperExprs B;
7816 // In presence of clause 'collapse' with number of loops, it will
7817 // define the nested loops number.
7818 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007819 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007820 nullptr /*ordered not a clause on distribute*/, AStmt,
7821 *this, *DSAStack, VarsWithImplicitDSA, B);
7822 if (NestedLoopCount == 0)
7823 return StmtError();
7824
7825 assert((CurContext->isDependentContext() || B.builtAll()) &&
7826 "omp for loop exprs were not built");
7827
Reid Kleckner87a31802018-03-12 21:43:02 +00007828 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007829 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7830 NestedLoopCount, Clauses, AStmt, B);
7831}
7832
Carlo Bertolli9925f152016-06-27 14:55:37 +00007833StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7834 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007835 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00007836 if (!AStmt)
7837 return StmtError();
7838
Alexey Bataeve3727102018-04-18 15:57:46 +00007839 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007840 // 1.2.2 OpenMP Language Terminology
7841 // Structured block - An executable statement with a single entry at the
7842 // top and a single exit at the bottom.
7843 // The point of exit cannot be a branch out of the structured block.
7844 // longjmp() and throw() must not violate the entry/exit criteria.
7845 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00007846 for (int ThisCaptureLevel =
7847 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7848 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7849 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7850 // 1.2.2 OpenMP Language Terminology
7851 // Structured block - An executable statement with a single entry at the
7852 // top and a single exit at the bottom.
7853 // The point of exit cannot be a branch out of the structured block.
7854 // longjmp() and throw() must not violate the entry/exit criteria.
7855 CS->getCapturedDecl()->setNothrow();
7856 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00007857
7858 OMPLoopDirective::HelperExprs B;
7859 // In presence of clause 'collapse' with number of loops, it will
7860 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007861 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00007862 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00007863 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00007864 VarsWithImplicitDSA, B);
7865 if (NestedLoopCount == 0)
7866 return StmtError();
7867
7868 assert((CurContext->isDependentContext() || B.builtAll()) &&
7869 "omp for loop exprs were not built");
7870
Reid Kleckner87a31802018-03-12 21:43:02 +00007871 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007872 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007873 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7874 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00007875}
7876
Kelvin Li4a39add2016-07-05 05:00:15 +00007877StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7878 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007879 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00007880 if (!AStmt)
7881 return StmtError();
7882
Alexey Bataeve3727102018-04-18 15:57:46 +00007883 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00007884 // 1.2.2 OpenMP Language Terminology
7885 // Structured block - An executable statement with a single entry at the
7886 // top and a single exit at the bottom.
7887 // The point of exit cannot be a branch out of the structured block.
7888 // longjmp() and throw() must not violate the entry/exit criteria.
7889 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00007890 for (int ThisCaptureLevel =
7891 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7892 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7893 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7894 // 1.2.2 OpenMP Language Terminology
7895 // Structured block - An executable statement with a single entry at the
7896 // top and a single exit at the bottom.
7897 // The point of exit cannot be a branch out of the structured block.
7898 // longjmp() and throw() must not violate the entry/exit criteria.
7899 CS->getCapturedDecl()->setNothrow();
7900 }
Kelvin Li4a39add2016-07-05 05:00:15 +00007901
7902 OMPLoopDirective::HelperExprs B;
7903 // In presence of clause 'collapse' with number of loops, it will
7904 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007905 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00007906 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00007907 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00007908 VarsWithImplicitDSA, B);
7909 if (NestedLoopCount == 0)
7910 return StmtError();
7911
7912 assert((CurContext->isDependentContext() || B.builtAll()) &&
7913 "omp for loop exprs were not built");
7914
Alexey Bataev438388c2017-11-22 18:34:02 +00007915 if (!CurContext->isDependentContext()) {
7916 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007917 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007918 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7919 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7920 B.NumIterations, *this, CurScope,
7921 DSAStack))
7922 return StmtError();
7923 }
7924 }
7925
Kelvin Lic5609492016-07-15 04:39:07 +00007926 if (checkSimdlenSafelenSpecified(*this, Clauses))
7927 return StmtError();
7928
Reid Kleckner87a31802018-03-12 21:43:02 +00007929 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00007930 return OMPDistributeParallelForSimdDirective::Create(
7931 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7932}
7933
Kelvin Li787f3fc2016-07-06 04:45:38 +00007934StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7935 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007936 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00007937 if (!AStmt)
7938 return StmtError();
7939
Alexey Bataeve3727102018-04-18 15:57:46 +00007940 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007941 // 1.2.2 OpenMP Language Terminology
7942 // Structured block - An executable statement with a single entry at the
7943 // top and a single exit at the bottom.
7944 // The point of exit cannot be a branch out of the structured block.
7945 // longjmp() and throw() must not violate the entry/exit criteria.
7946 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00007947 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7948 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7949 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7950 // 1.2.2 OpenMP Language Terminology
7951 // Structured block - An executable statement with a single entry at the
7952 // top and a single exit at the bottom.
7953 // The point of exit cannot be a branch out of the structured block.
7954 // longjmp() and throw() must not violate the entry/exit criteria.
7955 CS->getCapturedDecl()->setNothrow();
7956 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007957
7958 OMPLoopDirective::HelperExprs B;
7959 // In presence of clause 'collapse' with number of loops, it will
7960 // define the nested loops number.
7961 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007962 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007963 nullptr /*ordered not a clause on distribute*/, CS, *this,
7964 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007965 if (NestedLoopCount == 0)
7966 return StmtError();
7967
7968 assert((CurContext->isDependentContext() || B.builtAll()) &&
7969 "omp for loop exprs were not built");
7970
Alexey Bataev438388c2017-11-22 18:34:02 +00007971 if (!CurContext->isDependentContext()) {
7972 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007973 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007974 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7975 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7976 B.NumIterations, *this, CurScope,
7977 DSAStack))
7978 return StmtError();
7979 }
7980 }
7981
Kelvin Lic5609492016-07-15 04:39:07 +00007982 if (checkSimdlenSafelenSpecified(*this, Clauses))
7983 return StmtError();
7984
Reid Kleckner87a31802018-03-12 21:43:02 +00007985 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00007986 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7987 NestedLoopCount, Clauses, AStmt, B);
7988}
7989
Kelvin Lia579b912016-07-14 02:54:56 +00007990StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7991 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007992 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00007993 if (!AStmt)
7994 return StmtError();
7995
Alexey Bataeve3727102018-04-18 15:57:46 +00007996 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00007997 // 1.2.2 OpenMP Language Terminology
7998 // Structured block - An executable statement with a single entry at the
7999 // top and a single exit at the bottom.
8000 // The point of exit cannot be a branch out of the structured block.
8001 // longjmp() and throw() must not violate the entry/exit criteria.
8002 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008003 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
8004 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8005 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8006 // 1.2.2 OpenMP Language Terminology
8007 // Structured block - An executable statement with a single entry at the
8008 // top and a single exit at the bottom.
8009 // The point of exit cannot be a branch out of the structured block.
8010 // longjmp() and throw() must not violate the entry/exit criteria.
8011 CS->getCapturedDecl()->setNothrow();
8012 }
Kelvin Lia579b912016-07-14 02:54:56 +00008013
8014 OMPLoopDirective::HelperExprs B;
8015 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8016 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008017 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00008018 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008019 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00008020 VarsWithImplicitDSA, B);
8021 if (NestedLoopCount == 0)
8022 return StmtError();
8023
8024 assert((CurContext->isDependentContext() || B.builtAll()) &&
8025 "omp target parallel for simd loop exprs were not built");
8026
8027 if (!CurContext->isDependentContext()) {
8028 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008029 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008030 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00008031 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8032 B.NumIterations, *this, CurScope,
8033 DSAStack))
8034 return StmtError();
8035 }
8036 }
Kelvin Lic5609492016-07-15 04:39:07 +00008037 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00008038 return StmtError();
8039
Reid Kleckner87a31802018-03-12 21:43:02 +00008040 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00008041 return OMPTargetParallelForSimdDirective::Create(
8042 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8043}
8044
Kelvin Li986330c2016-07-20 22:57:10 +00008045StmtResult Sema::ActOnOpenMPTargetSimdDirective(
8046 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008047 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00008048 if (!AStmt)
8049 return StmtError();
8050
Alexey Bataeve3727102018-04-18 15:57:46 +00008051 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00008052 // 1.2.2 OpenMP Language Terminology
8053 // Structured block - An executable statement with a single entry at the
8054 // top and a single exit at the bottom.
8055 // The point of exit cannot be a branch out of the structured block.
8056 // longjmp() and throw() must not violate the entry/exit criteria.
8057 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00008058 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
8059 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8060 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8061 // 1.2.2 OpenMP Language Terminology
8062 // Structured block - An executable statement with a single entry at the
8063 // top and a single exit at the bottom.
8064 // The point of exit cannot be a branch out of the structured block.
8065 // longjmp() and throw() must not violate the entry/exit criteria.
8066 CS->getCapturedDecl()->setNothrow();
8067 }
8068
Kelvin Li986330c2016-07-20 22:57:10 +00008069 OMPLoopDirective::HelperExprs B;
8070 // In presence of clause 'collapse' with number of loops, it will define the
8071 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00008072 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008073 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00008074 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00008075 VarsWithImplicitDSA, B);
8076 if (NestedLoopCount == 0)
8077 return StmtError();
8078
8079 assert((CurContext->isDependentContext() || B.builtAll()) &&
8080 "omp target simd loop exprs were not built");
8081
8082 if (!CurContext->isDependentContext()) {
8083 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008084 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008085 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00008086 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8087 B.NumIterations, *this, CurScope,
8088 DSAStack))
8089 return StmtError();
8090 }
8091 }
8092
8093 if (checkSimdlenSafelenSpecified(*this, Clauses))
8094 return StmtError();
8095
Reid Kleckner87a31802018-03-12 21:43:02 +00008096 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00008097 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
8098 NestedLoopCount, Clauses, AStmt, B);
8099}
8100
Kelvin Li02532872016-08-05 14:37:37 +00008101StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
8102 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008103 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00008104 if (!AStmt)
8105 return StmtError();
8106
Alexey Bataeve3727102018-04-18 15:57:46 +00008107 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00008108 // 1.2.2 OpenMP Language Terminology
8109 // Structured block - An executable statement with a single entry at the
8110 // top and a single exit at the bottom.
8111 // The point of exit cannot be a branch out of the structured block.
8112 // longjmp() and throw() must not violate the entry/exit criteria.
8113 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008114 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
8115 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8116 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8117 // 1.2.2 OpenMP Language Terminology
8118 // Structured block - An executable statement with a single entry at the
8119 // top and a single exit at the bottom.
8120 // The point of exit cannot be a branch out of the structured block.
8121 // longjmp() and throw() must not violate the entry/exit criteria.
8122 CS->getCapturedDecl()->setNothrow();
8123 }
Kelvin Li02532872016-08-05 14:37:37 +00008124
8125 OMPLoopDirective::HelperExprs B;
8126 // In presence of clause 'collapse' with number of loops, it will
8127 // define the nested loops number.
8128 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008129 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008130 nullptr /*ordered not a clause on distribute*/, CS, *this,
8131 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00008132 if (NestedLoopCount == 0)
8133 return StmtError();
8134
8135 assert((CurContext->isDependentContext() || B.builtAll()) &&
8136 "omp teams distribute loop exprs were not built");
8137
Reid Kleckner87a31802018-03-12 21:43:02 +00008138 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008139
8140 DSAStack->setParentTeamsRegionLoc(StartLoc);
8141
David Majnemer9d168222016-08-05 17:44:54 +00008142 return OMPTeamsDistributeDirective::Create(
8143 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00008144}
8145
Kelvin Li4e325f72016-10-25 12:50:55 +00008146StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
8147 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008148 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008149 if (!AStmt)
8150 return StmtError();
8151
Alexey Bataeve3727102018-04-18 15:57:46 +00008152 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00008153 // 1.2.2 OpenMP Language Terminology
8154 // Structured block - An executable statement with a single entry at the
8155 // top and a single exit at the bottom.
8156 // The point of exit cannot be a branch out of the structured block.
8157 // longjmp() and throw() must not violate the entry/exit criteria.
8158 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00008159 for (int ThisCaptureLevel =
8160 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
8161 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8162 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8163 // 1.2.2 OpenMP Language Terminology
8164 // Structured block - An executable statement with a single entry at the
8165 // top and a single exit at the bottom.
8166 // The point of exit cannot be a branch out of the structured block.
8167 // longjmp() and throw() must not violate the entry/exit criteria.
8168 CS->getCapturedDecl()->setNothrow();
8169 }
8170
Kelvin Li4e325f72016-10-25 12:50:55 +00008171
8172 OMPLoopDirective::HelperExprs B;
8173 // In presence of clause 'collapse' with number of loops, it will
8174 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008175 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00008176 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00008177 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00008178 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00008179
8180 if (NestedLoopCount == 0)
8181 return StmtError();
8182
8183 assert((CurContext->isDependentContext() || B.builtAll()) &&
8184 "omp teams distribute simd loop exprs were not built");
8185
8186 if (!CurContext->isDependentContext()) {
8187 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008188 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008189 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8190 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8191 B.NumIterations, *this, CurScope,
8192 DSAStack))
8193 return StmtError();
8194 }
8195 }
8196
8197 if (checkSimdlenSafelenSpecified(*this, Clauses))
8198 return StmtError();
8199
Reid Kleckner87a31802018-03-12 21:43:02 +00008200 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008201
8202 DSAStack->setParentTeamsRegionLoc(StartLoc);
8203
Kelvin Li4e325f72016-10-25 12:50:55 +00008204 return OMPTeamsDistributeSimdDirective::Create(
8205 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8206}
8207
Kelvin Li579e41c2016-11-30 23:51:03 +00008208StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8209 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008210 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008211 if (!AStmt)
8212 return StmtError();
8213
Alexey Bataeve3727102018-04-18 15:57:46 +00008214 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00008215 // 1.2.2 OpenMP Language Terminology
8216 // Structured block - An executable statement with a single entry at the
8217 // top and a single exit at the bottom.
8218 // The point of exit cannot be a branch out of the structured block.
8219 // longjmp() and throw() must not violate the entry/exit criteria.
8220 CS->getCapturedDecl()->setNothrow();
8221
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008222 for (int ThisCaptureLevel =
8223 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
8224 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8225 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8226 // 1.2.2 OpenMP Language Terminology
8227 // Structured block - An executable statement with a single entry at the
8228 // top and a single exit at the bottom.
8229 // The point of exit cannot be a branch out of the structured block.
8230 // longjmp() and throw() must not violate the entry/exit criteria.
8231 CS->getCapturedDecl()->setNothrow();
8232 }
8233
Kelvin Li579e41c2016-11-30 23:51:03 +00008234 OMPLoopDirective::HelperExprs B;
8235 // In presence of clause 'collapse' with number of loops, it will
8236 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008237 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00008238 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008239 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00008240 VarsWithImplicitDSA, B);
8241
8242 if (NestedLoopCount == 0)
8243 return StmtError();
8244
8245 assert((CurContext->isDependentContext() || B.builtAll()) &&
8246 "omp for loop exprs were not built");
8247
8248 if (!CurContext->isDependentContext()) {
8249 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008250 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008251 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8252 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8253 B.NumIterations, *this, CurScope,
8254 DSAStack))
8255 return StmtError();
8256 }
8257 }
8258
8259 if (checkSimdlenSafelenSpecified(*this, Clauses))
8260 return StmtError();
8261
Reid Kleckner87a31802018-03-12 21:43:02 +00008262 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008263
8264 DSAStack->setParentTeamsRegionLoc(StartLoc);
8265
Kelvin Li579e41c2016-11-30 23:51:03 +00008266 return OMPTeamsDistributeParallelForSimdDirective::Create(
8267 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8268}
8269
Kelvin Li7ade93f2016-12-09 03:24:30 +00008270StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
8271 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008272 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00008273 if (!AStmt)
8274 return StmtError();
8275
Alexey Bataeve3727102018-04-18 15:57:46 +00008276 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00008277 // 1.2.2 OpenMP Language Terminology
8278 // Structured block - An executable statement with a single entry at the
8279 // top and a single exit at the bottom.
8280 // The point of exit cannot be a branch out of the structured block.
8281 // longjmp() and throw() must not violate the entry/exit criteria.
8282 CS->getCapturedDecl()->setNothrow();
8283
Carlo Bertolli62fae152017-11-20 20:46:39 +00008284 for (int ThisCaptureLevel =
8285 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
8286 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8287 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8288 // 1.2.2 OpenMP Language Terminology
8289 // Structured block - An executable statement with a single entry at the
8290 // top and a single exit at the bottom.
8291 // The point of exit cannot be a branch out of the structured block.
8292 // longjmp() and throw() must not violate the entry/exit criteria.
8293 CS->getCapturedDecl()->setNothrow();
8294 }
8295
Kelvin Li7ade93f2016-12-09 03:24:30 +00008296 OMPLoopDirective::HelperExprs B;
8297 // In presence of clause 'collapse' with number of loops, it will
8298 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008299 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00008300 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00008301 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00008302 VarsWithImplicitDSA, B);
8303
8304 if (NestedLoopCount == 0)
8305 return StmtError();
8306
8307 assert((CurContext->isDependentContext() || B.builtAll()) &&
8308 "omp for loop exprs were not built");
8309
Reid Kleckner87a31802018-03-12 21:43:02 +00008310 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008311
8312 DSAStack->setParentTeamsRegionLoc(StartLoc);
8313
Kelvin Li7ade93f2016-12-09 03:24:30 +00008314 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008315 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8316 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00008317}
8318
Kelvin Libf594a52016-12-17 05:48:59 +00008319StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8320 Stmt *AStmt,
8321 SourceLocation StartLoc,
8322 SourceLocation EndLoc) {
8323 if (!AStmt)
8324 return StmtError();
8325
Alexey Bataeve3727102018-04-18 15:57:46 +00008326 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00008327 // 1.2.2 OpenMP Language Terminology
8328 // Structured block - An executable statement with a single entry at the
8329 // top and a single exit at the bottom.
8330 // The point of exit cannot be a branch out of the structured block.
8331 // longjmp() and throw() must not violate the entry/exit criteria.
8332 CS->getCapturedDecl()->setNothrow();
8333
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00008334 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
8335 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8336 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8337 // 1.2.2 OpenMP Language Terminology
8338 // Structured block - An executable statement with a single entry at the
8339 // top and a single exit at the bottom.
8340 // The point of exit cannot be a branch out of the structured block.
8341 // longjmp() and throw() must not violate the entry/exit criteria.
8342 CS->getCapturedDecl()->setNothrow();
8343 }
Reid Kleckner87a31802018-03-12 21:43:02 +00008344 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00008345
8346 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8347 AStmt);
8348}
8349
Kelvin Li83c451e2016-12-25 04:52:54 +00008350StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8351 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008352 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00008353 if (!AStmt)
8354 return StmtError();
8355
Alexey Bataeve3727102018-04-18 15:57:46 +00008356 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00008357 // 1.2.2 OpenMP Language Terminology
8358 // Structured block - An executable statement with a single entry at the
8359 // top and a single exit at the bottom.
8360 // The point of exit cannot be a branch out of the structured block.
8361 // longjmp() and throw() must not violate the entry/exit criteria.
8362 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008363 for (int ThisCaptureLevel =
8364 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8365 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8366 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8367 // 1.2.2 OpenMP Language Terminology
8368 // Structured block - An executable statement with a single entry at the
8369 // top and a single exit at the bottom.
8370 // The point of exit cannot be a branch out of the structured block.
8371 // longjmp() and throw() must not violate the entry/exit criteria.
8372 CS->getCapturedDecl()->setNothrow();
8373 }
Kelvin Li83c451e2016-12-25 04:52:54 +00008374
8375 OMPLoopDirective::HelperExprs B;
8376 // In presence of clause 'collapse' with number of loops, it will
8377 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008378 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008379 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8380 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00008381 VarsWithImplicitDSA, B);
8382 if (NestedLoopCount == 0)
8383 return StmtError();
8384
8385 assert((CurContext->isDependentContext() || B.builtAll()) &&
8386 "omp target teams distribute loop exprs were not built");
8387
Reid Kleckner87a31802018-03-12 21:43:02 +00008388 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00008389 return OMPTargetTeamsDistributeDirective::Create(
8390 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8391}
8392
Kelvin Li80e8f562016-12-29 22:16:30 +00008393StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8394 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008395 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00008396 if (!AStmt)
8397 return StmtError();
8398
Alexey Bataeve3727102018-04-18 15:57:46 +00008399 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00008400 // 1.2.2 OpenMP Language Terminology
8401 // Structured block - An executable statement with a single entry at the
8402 // top and a single exit at the bottom.
8403 // The point of exit cannot be a branch out of the structured block.
8404 // longjmp() and throw() must not violate the entry/exit criteria.
8405 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00008406 for (int ThisCaptureLevel =
8407 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8408 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8409 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8410 // 1.2.2 OpenMP Language Terminology
8411 // Structured block - An executable statement with a single entry at the
8412 // top and a single exit at the bottom.
8413 // The point of exit cannot be a branch out of the structured block.
8414 // longjmp() and throw() must not violate the entry/exit criteria.
8415 CS->getCapturedDecl()->setNothrow();
8416 }
8417
Kelvin Li80e8f562016-12-29 22:16:30 +00008418 OMPLoopDirective::HelperExprs B;
8419 // In presence of clause 'collapse' with number of loops, it will
8420 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008421 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00008422 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8423 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00008424 VarsWithImplicitDSA, B);
8425 if (NestedLoopCount == 0)
8426 return StmtError();
8427
8428 assert((CurContext->isDependentContext() || B.builtAll()) &&
8429 "omp target teams distribute parallel for loop exprs were not built");
8430
Alexey Bataev647dd842018-01-15 20:59:40 +00008431 if (!CurContext->isDependentContext()) {
8432 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008433 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00008434 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8435 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8436 B.NumIterations, *this, CurScope,
8437 DSAStack))
8438 return StmtError();
8439 }
8440 }
8441
Reid Kleckner87a31802018-03-12 21:43:02 +00008442 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00008443 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00008444 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8445 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00008446}
8447
Kelvin Li1851df52017-01-03 05:23:48 +00008448StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8449 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008450 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00008451 if (!AStmt)
8452 return StmtError();
8453
Alexey Bataeve3727102018-04-18 15:57:46 +00008454 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00008455 // 1.2.2 OpenMP Language Terminology
8456 // Structured block - An executable statement with a single entry at the
8457 // top and a single exit at the bottom.
8458 // The point of exit cannot be a branch out of the structured block.
8459 // longjmp() and throw() must not violate the entry/exit criteria.
8460 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00008461 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8462 OMPD_target_teams_distribute_parallel_for_simd);
8463 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8464 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8465 // 1.2.2 OpenMP Language Terminology
8466 // Structured block - An executable statement with a single entry at the
8467 // top and a single exit at the bottom.
8468 // The point of exit cannot be a branch out of the structured block.
8469 // longjmp() and throw() must not violate the entry/exit criteria.
8470 CS->getCapturedDecl()->setNothrow();
8471 }
Kelvin Li1851df52017-01-03 05:23:48 +00008472
8473 OMPLoopDirective::HelperExprs B;
8474 // In presence of clause 'collapse' with number of loops, it will
8475 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008476 unsigned NestedLoopCount =
8477 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00008478 getCollapseNumberExpr(Clauses),
8479 nullptr /*ordered not a clause on distribute*/, CS, *this,
8480 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00008481 if (NestedLoopCount == 0)
8482 return StmtError();
8483
8484 assert((CurContext->isDependentContext() || B.builtAll()) &&
8485 "omp target teams distribute parallel for simd loop exprs were not "
8486 "built");
8487
8488 if (!CurContext->isDependentContext()) {
8489 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008490 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00008491 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8492 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8493 B.NumIterations, *this, CurScope,
8494 DSAStack))
8495 return StmtError();
8496 }
8497 }
8498
Alexey Bataev438388c2017-11-22 18:34:02 +00008499 if (checkSimdlenSafelenSpecified(*this, Clauses))
8500 return StmtError();
8501
Reid Kleckner87a31802018-03-12 21:43:02 +00008502 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00008503 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8504 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8505}
8506
Kelvin Lida681182017-01-10 18:08:18 +00008507StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8508 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008509 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00008510 if (!AStmt)
8511 return StmtError();
8512
8513 auto *CS = cast<CapturedStmt>(AStmt);
8514 // 1.2.2 OpenMP Language Terminology
8515 // Structured block - An executable statement with a single entry at the
8516 // top and a single exit at the bottom.
8517 // The point of exit cannot be a branch out of the structured block.
8518 // longjmp() and throw() must not violate the entry/exit criteria.
8519 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008520 for (int ThisCaptureLevel =
8521 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
8522 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8523 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8524 // 1.2.2 OpenMP Language Terminology
8525 // Structured block - An executable statement with a single entry at the
8526 // top and a single exit at the bottom.
8527 // The point of exit cannot be a branch out of the structured block.
8528 // longjmp() and throw() must not violate the entry/exit criteria.
8529 CS->getCapturedDecl()->setNothrow();
8530 }
Kelvin Lida681182017-01-10 18:08:18 +00008531
8532 OMPLoopDirective::HelperExprs B;
8533 // In presence of clause 'collapse' with number of loops, it will
8534 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008535 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00008536 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008537 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00008538 VarsWithImplicitDSA, B);
8539 if (NestedLoopCount == 0)
8540 return StmtError();
8541
8542 assert((CurContext->isDependentContext() || B.builtAll()) &&
8543 "omp target teams distribute simd loop exprs were not built");
8544
Alexey Bataev438388c2017-11-22 18:34:02 +00008545 if (!CurContext->isDependentContext()) {
8546 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008547 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008548 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8549 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8550 B.NumIterations, *this, CurScope,
8551 DSAStack))
8552 return StmtError();
8553 }
8554 }
8555
8556 if (checkSimdlenSafelenSpecified(*this, Clauses))
8557 return StmtError();
8558
Reid Kleckner87a31802018-03-12 21:43:02 +00008559 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00008560 return OMPTargetTeamsDistributeSimdDirective::Create(
8561 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8562}
8563
Alexey Bataeved09d242014-05-28 05:53:51 +00008564OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008565 SourceLocation StartLoc,
8566 SourceLocation LParenLoc,
8567 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008568 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008569 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00008570 case OMPC_final:
8571 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8572 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00008573 case OMPC_num_threads:
8574 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8575 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008576 case OMPC_safelen:
8577 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8578 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00008579 case OMPC_simdlen:
8580 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8581 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00008582 case OMPC_allocator:
8583 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
8584 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00008585 case OMPC_collapse:
8586 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8587 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008588 case OMPC_ordered:
8589 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8590 break;
Michael Wonge710d542015-08-07 16:16:36 +00008591 case OMPC_device:
8592 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8593 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00008594 case OMPC_num_teams:
8595 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8596 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008597 case OMPC_thread_limit:
8598 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8599 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00008600 case OMPC_priority:
8601 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8602 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008603 case OMPC_grainsize:
8604 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8605 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00008606 case OMPC_num_tasks:
8607 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8608 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00008609 case OMPC_hint:
8610 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8611 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008612 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008613 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008614 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008615 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008616 case OMPC_private:
8617 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008618 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008619 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008620 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008621 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008622 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008623 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008624 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008625 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008626 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00008627 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008628 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008629 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008630 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008631 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008632 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008633 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008634 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008635 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008636 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008637 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008638 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00008639 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008640 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008641 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00008642 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008643 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008644 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008645 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008646 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008647 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008648 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008649 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008650 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00008651 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00008652 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00008653 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00008654 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00008655 case OMPC_atomic_default_mem_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008656 llvm_unreachable("Clause is not allowed.");
8657 }
8658 return Res;
8659}
8660
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008661// An OpenMP directive such as 'target parallel' has two captured regions:
8662// for the 'target' and 'parallel' respectively. This function returns
8663// the region in which to capture expressions associated with a clause.
8664// A return value of OMPD_unknown signifies that the expression should not
8665// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008666static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
8667 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
8668 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008669 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008670 switch (CKind) {
8671 case OMPC_if:
8672 switch (DKind) {
8673 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008674 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008675 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008676 // If this clause applies to the nested 'parallel' region, capture within
8677 // the 'target' region, otherwise do not capture.
8678 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8679 CaptureRegion = OMPD_target;
8680 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00008681 case OMPD_target_teams_distribute_parallel_for:
8682 case OMPD_target_teams_distribute_parallel_for_simd:
8683 // If this clause applies to the nested 'parallel' region, capture within
8684 // the 'teams' region, otherwise do not capture.
8685 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8686 CaptureRegion = OMPD_teams;
8687 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008688 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008689 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008690 CaptureRegion = OMPD_teams;
8691 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008692 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008693 case OMPD_target_enter_data:
8694 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008695 CaptureRegion = OMPD_task;
8696 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008697 case OMPD_cancel:
8698 case OMPD_parallel:
8699 case OMPD_parallel_sections:
8700 case OMPD_parallel_for:
8701 case OMPD_parallel_for_simd:
8702 case OMPD_target:
8703 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008704 case OMPD_target_teams:
8705 case OMPD_target_teams_distribute:
8706 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008707 case OMPD_distribute_parallel_for:
8708 case OMPD_distribute_parallel_for_simd:
8709 case OMPD_task:
8710 case OMPD_taskloop:
8711 case OMPD_taskloop_simd:
8712 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008713 // Do not capture if-clause expressions.
8714 break;
8715 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008716 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008717 case OMPD_taskyield:
8718 case OMPD_barrier:
8719 case OMPD_taskwait:
8720 case OMPD_cancellation_point:
8721 case OMPD_flush:
8722 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008723 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008724 case OMPD_declare_simd:
8725 case OMPD_declare_target:
8726 case OMPD_end_declare_target:
8727 case OMPD_teams:
8728 case OMPD_simd:
8729 case OMPD_for:
8730 case OMPD_for_simd:
8731 case OMPD_sections:
8732 case OMPD_section:
8733 case OMPD_single:
8734 case OMPD_master:
8735 case OMPD_critical:
8736 case OMPD_taskgroup:
8737 case OMPD_distribute:
8738 case OMPD_ordered:
8739 case OMPD_atomic:
8740 case OMPD_distribute_simd:
8741 case OMPD_teams_distribute:
8742 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008743 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008744 llvm_unreachable("Unexpected OpenMP directive with if-clause");
8745 case OMPD_unknown:
8746 llvm_unreachable("Unknown OpenMP directive");
8747 }
8748 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008749 case OMPC_num_threads:
8750 switch (DKind) {
8751 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008752 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008753 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008754 CaptureRegion = OMPD_target;
8755 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008756 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008757 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008758 case OMPD_target_teams_distribute_parallel_for:
8759 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008760 CaptureRegion = OMPD_teams;
8761 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008762 case OMPD_parallel:
8763 case OMPD_parallel_sections:
8764 case OMPD_parallel_for:
8765 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008766 case OMPD_distribute_parallel_for:
8767 case OMPD_distribute_parallel_for_simd:
8768 // Do not capture num_threads-clause expressions.
8769 break;
8770 case OMPD_target_data:
8771 case OMPD_target_enter_data:
8772 case OMPD_target_exit_data:
8773 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008774 case OMPD_target:
8775 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008776 case OMPD_target_teams:
8777 case OMPD_target_teams_distribute:
8778 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008779 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008780 case OMPD_task:
8781 case OMPD_taskloop:
8782 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008783 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008784 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008785 case OMPD_taskyield:
8786 case OMPD_barrier:
8787 case OMPD_taskwait:
8788 case OMPD_cancellation_point:
8789 case OMPD_flush:
8790 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008791 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008792 case OMPD_declare_simd:
8793 case OMPD_declare_target:
8794 case OMPD_end_declare_target:
8795 case OMPD_teams:
8796 case OMPD_simd:
8797 case OMPD_for:
8798 case OMPD_for_simd:
8799 case OMPD_sections:
8800 case OMPD_section:
8801 case OMPD_single:
8802 case OMPD_master:
8803 case OMPD_critical:
8804 case OMPD_taskgroup:
8805 case OMPD_distribute:
8806 case OMPD_ordered:
8807 case OMPD_atomic:
8808 case OMPD_distribute_simd:
8809 case OMPD_teams_distribute:
8810 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008811 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008812 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8813 case OMPD_unknown:
8814 llvm_unreachable("Unknown OpenMP directive");
8815 }
8816 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008817 case OMPC_num_teams:
8818 switch (DKind) {
8819 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008820 case OMPD_target_teams_distribute:
8821 case OMPD_target_teams_distribute_simd:
8822 case OMPD_target_teams_distribute_parallel_for:
8823 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008824 CaptureRegion = OMPD_target;
8825 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008826 case OMPD_teams_distribute_parallel_for:
8827 case OMPD_teams_distribute_parallel_for_simd:
8828 case OMPD_teams:
8829 case OMPD_teams_distribute:
8830 case OMPD_teams_distribute_simd:
8831 // Do not capture num_teams-clause expressions.
8832 break;
8833 case OMPD_distribute_parallel_for:
8834 case OMPD_distribute_parallel_for_simd:
8835 case OMPD_task:
8836 case OMPD_taskloop:
8837 case OMPD_taskloop_simd:
8838 case OMPD_target_data:
8839 case OMPD_target_enter_data:
8840 case OMPD_target_exit_data:
8841 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008842 case OMPD_cancel:
8843 case OMPD_parallel:
8844 case OMPD_parallel_sections:
8845 case OMPD_parallel_for:
8846 case OMPD_parallel_for_simd:
8847 case OMPD_target:
8848 case OMPD_target_simd:
8849 case OMPD_target_parallel:
8850 case OMPD_target_parallel_for:
8851 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008852 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008853 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008854 case OMPD_taskyield:
8855 case OMPD_barrier:
8856 case OMPD_taskwait:
8857 case OMPD_cancellation_point:
8858 case OMPD_flush:
8859 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008860 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008861 case OMPD_declare_simd:
8862 case OMPD_declare_target:
8863 case OMPD_end_declare_target:
8864 case OMPD_simd:
8865 case OMPD_for:
8866 case OMPD_for_simd:
8867 case OMPD_sections:
8868 case OMPD_section:
8869 case OMPD_single:
8870 case OMPD_master:
8871 case OMPD_critical:
8872 case OMPD_taskgroup:
8873 case OMPD_distribute:
8874 case OMPD_ordered:
8875 case OMPD_atomic:
8876 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008877 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008878 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8879 case OMPD_unknown:
8880 llvm_unreachable("Unknown OpenMP directive");
8881 }
8882 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008883 case OMPC_thread_limit:
8884 switch (DKind) {
8885 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008886 case OMPD_target_teams_distribute:
8887 case OMPD_target_teams_distribute_simd:
8888 case OMPD_target_teams_distribute_parallel_for:
8889 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008890 CaptureRegion = OMPD_target;
8891 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008892 case OMPD_teams_distribute_parallel_for:
8893 case OMPD_teams_distribute_parallel_for_simd:
8894 case OMPD_teams:
8895 case OMPD_teams_distribute:
8896 case OMPD_teams_distribute_simd:
8897 // Do not capture thread_limit-clause expressions.
8898 break;
8899 case OMPD_distribute_parallel_for:
8900 case OMPD_distribute_parallel_for_simd:
8901 case OMPD_task:
8902 case OMPD_taskloop:
8903 case OMPD_taskloop_simd:
8904 case OMPD_target_data:
8905 case OMPD_target_enter_data:
8906 case OMPD_target_exit_data:
8907 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008908 case OMPD_cancel:
8909 case OMPD_parallel:
8910 case OMPD_parallel_sections:
8911 case OMPD_parallel_for:
8912 case OMPD_parallel_for_simd:
8913 case OMPD_target:
8914 case OMPD_target_simd:
8915 case OMPD_target_parallel:
8916 case OMPD_target_parallel_for:
8917 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008918 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008919 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008920 case OMPD_taskyield:
8921 case OMPD_barrier:
8922 case OMPD_taskwait:
8923 case OMPD_cancellation_point:
8924 case OMPD_flush:
8925 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008926 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008927 case OMPD_declare_simd:
8928 case OMPD_declare_target:
8929 case OMPD_end_declare_target:
8930 case OMPD_simd:
8931 case OMPD_for:
8932 case OMPD_for_simd:
8933 case OMPD_sections:
8934 case OMPD_section:
8935 case OMPD_single:
8936 case OMPD_master:
8937 case OMPD_critical:
8938 case OMPD_taskgroup:
8939 case OMPD_distribute:
8940 case OMPD_ordered:
8941 case OMPD_atomic:
8942 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008943 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008944 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8945 case OMPD_unknown:
8946 llvm_unreachable("Unknown OpenMP directive");
8947 }
8948 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008949 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008950 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008951 case OMPD_parallel_for:
8952 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008953 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008954 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008955 case OMPD_teams_distribute_parallel_for:
8956 case OMPD_teams_distribute_parallel_for_simd:
8957 case OMPD_target_parallel_for:
8958 case OMPD_target_parallel_for_simd:
8959 case OMPD_target_teams_distribute_parallel_for:
8960 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008961 CaptureRegion = OMPD_parallel;
8962 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008963 case OMPD_for:
8964 case OMPD_for_simd:
8965 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008966 break;
8967 case OMPD_task:
8968 case OMPD_taskloop:
8969 case OMPD_taskloop_simd:
8970 case OMPD_target_data:
8971 case OMPD_target_enter_data:
8972 case OMPD_target_exit_data:
8973 case OMPD_target_update:
8974 case OMPD_teams:
8975 case OMPD_teams_distribute:
8976 case OMPD_teams_distribute_simd:
8977 case OMPD_target_teams_distribute:
8978 case OMPD_target_teams_distribute_simd:
8979 case OMPD_target:
8980 case OMPD_target_simd:
8981 case OMPD_target_parallel:
8982 case OMPD_cancel:
8983 case OMPD_parallel:
8984 case OMPD_parallel_sections:
8985 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008986 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008987 case OMPD_taskyield:
8988 case OMPD_barrier:
8989 case OMPD_taskwait:
8990 case OMPD_cancellation_point:
8991 case OMPD_flush:
8992 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008993 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008994 case OMPD_declare_simd:
8995 case OMPD_declare_target:
8996 case OMPD_end_declare_target:
8997 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008998 case OMPD_sections:
8999 case OMPD_section:
9000 case OMPD_single:
9001 case OMPD_master:
9002 case OMPD_critical:
9003 case OMPD_taskgroup:
9004 case OMPD_distribute:
9005 case OMPD_ordered:
9006 case OMPD_atomic:
9007 case OMPD_distribute_simd:
9008 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00009009 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009010 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9011 case OMPD_unknown:
9012 llvm_unreachable("Unknown OpenMP directive");
9013 }
9014 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009015 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009016 switch (DKind) {
9017 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009018 case OMPD_teams_distribute_parallel_for_simd:
9019 case OMPD_teams_distribute:
9020 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009021 case OMPD_target_teams_distribute_parallel_for:
9022 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009023 case OMPD_target_teams_distribute:
9024 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00009025 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009026 break;
9027 case OMPD_distribute_parallel_for:
9028 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009029 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009030 case OMPD_distribute_simd:
9031 // Do not capture thread_limit-clause expressions.
9032 break;
9033 case OMPD_parallel_for:
9034 case OMPD_parallel_for_simd:
9035 case OMPD_target_parallel_for_simd:
9036 case OMPD_target_parallel_for:
9037 case OMPD_task:
9038 case OMPD_taskloop:
9039 case OMPD_taskloop_simd:
9040 case OMPD_target_data:
9041 case OMPD_target_enter_data:
9042 case OMPD_target_exit_data:
9043 case OMPD_target_update:
9044 case OMPD_teams:
9045 case OMPD_target:
9046 case OMPD_target_simd:
9047 case OMPD_target_parallel:
9048 case OMPD_cancel:
9049 case OMPD_parallel:
9050 case OMPD_parallel_sections:
9051 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009052 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009053 case OMPD_taskyield:
9054 case OMPD_barrier:
9055 case OMPD_taskwait:
9056 case OMPD_cancellation_point:
9057 case OMPD_flush:
9058 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009059 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009060 case OMPD_declare_simd:
9061 case OMPD_declare_target:
9062 case OMPD_end_declare_target:
9063 case OMPD_simd:
9064 case OMPD_for:
9065 case OMPD_for_simd:
9066 case OMPD_sections:
9067 case OMPD_section:
9068 case OMPD_single:
9069 case OMPD_master:
9070 case OMPD_critical:
9071 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009072 case OMPD_ordered:
9073 case OMPD_atomic:
9074 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00009075 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009076 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9077 case OMPD_unknown:
9078 llvm_unreachable("Unknown OpenMP directive");
9079 }
9080 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009081 case OMPC_device:
9082 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009083 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00009084 case OMPD_target_enter_data:
9085 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00009086 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00009087 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00009088 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00009089 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00009090 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00009091 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00009092 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00009093 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00009094 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00009095 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009096 CaptureRegion = OMPD_task;
9097 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009098 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009099 // Do not capture device-clause expressions.
9100 break;
9101 case OMPD_teams_distribute_parallel_for:
9102 case OMPD_teams_distribute_parallel_for_simd:
9103 case OMPD_teams:
9104 case OMPD_teams_distribute:
9105 case OMPD_teams_distribute_simd:
9106 case OMPD_distribute_parallel_for:
9107 case OMPD_distribute_parallel_for_simd:
9108 case OMPD_task:
9109 case OMPD_taskloop:
9110 case OMPD_taskloop_simd:
9111 case OMPD_cancel:
9112 case OMPD_parallel:
9113 case OMPD_parallel_sections:
9114 case OMPD_parallel_for:
9115 case OMPD_parallel_for_simd:
9116 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009117 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009118 case OMPD_taskyield:
9119 case OMPD_barrier:
9120 case OMPD_taskwait:
9121 case OMPD_cancellation_point:
9122 case OMPD_flush:
9123 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009124 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009125 case OMPD_declare_simd:
9126 case OMPD_declare_target:
9127 case OMPD_end_declare_target:
9128 case OMPD_simd:
9129 case OMPD_for:
9130 case OMPD_for_simd:
9131 case OMPD_sections:
9132 case OMPD_section:
9133 case OMPD_single:
9134 case OMPD_master:
9135 case OMPD_critical:
9136 case OMPD_taskgroup:
9137 case OMPD_distribute:
9138 case OMPD_ordered:
9139 case OMPD_atomic:
9140 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009141 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009142 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
9143 case OMPD_unknown:
9144 llvm_unreachable("Unknown OpenMP directive");
9145 }
9146 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009147 case OMPC_firstprivate:
9148 case OMPC_lastprivate:
9149 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009150 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009151 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009152 case OMPC_linear:
9153 case OMPC_default:
9154 case OMPC_proc_bind:
9155 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009156 case OMPC_safelen:
9157 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009158 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009159 case OMPC_collapse:
9160 case OMPC_private:
9161 case OMPC_shared:
9162 case OMPC_aligned:
9163 case OMPC_copyin:
9164 case OMPC_copyprivate:
9165 case OMPC_ordered:
9166 case OMPC_nowait:
9167 case OMPC_untied:
9168 case OMPC_mergeable:
9169 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009170 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009171 case OMPC_flush:
9172 case OMPC_read:
9173 case OMPC_write:
9174 case OMPC_update:
9175 case OMPC_capture:
9176 case OMPC_seq_cst:
9177 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009178 case OMPC_threads:
9179 case OMPC_simd:
9180 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009181 case OMPC_priority:
9182 case OMPC_grainsize:
9183 case OMPC_nogroup:
9184 case OMPC_num_tasks:
9185 case OMPC_hint:
9186 case OMPC_defaultmap:
9187 case OMPC_unknown:
9188 case OMPC_uniform:
9189 case OMPC_to:
9190 case OMPC_from:
9191 case OMPC_use_device_ptr:
9192 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009193 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009194 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009195 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009196 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009197 case OMPC_atomic_default_mem_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009198 llvm_unreachable("Unexpected OpenMP clause.");
9199 }
9200 return CaptureRegion;
9201}
9202
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009203OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9204 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009205 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009206 SourceLocation NameModifierLoc,
9207 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009208 SourceLocation EndLoc) {
9209 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009210 Stmt *HelperValStmt = nullptr;
9211 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009212 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9213 !Condition->isInstantiationDependent() &&
9214 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009215 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009216 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009217 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009218
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009219 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009220
9221 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
9222 CaptureRegion =
9223 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00009224 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009225 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009226 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009227 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9228 HelperValStmt = buildPreInits(Context, Captures);
9229 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009230 }
9231
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009232 return new (Context)
9233 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
9234 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009235}
9236
Alexey Bataev3778b602014-07-17 07:32:53 +00009237OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
9238 SourceLocation StartLoc,
9239 SourceLocation LParenLoc,
9240 SourceLocation EndLoc) {
9241 Expr *ValExpr = Condition;
9242 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9243 !Condition->isInstantiationDependent() &&
9244 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009245 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00009246 if (Val.isInvalid())
9247 return nullptr;
9248
Richard Smith03a4aa32016-06-23 19:02:52 +00009249 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00009250 }
9251
9252 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9253}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009254ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
9255 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00009256 if (!Op)
9257 return ExprError();
9258
9259 class IntConvertDiagnoser : public ICEConvertDiagnoser {
9260 public:
9261 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00009262 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00009263 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9264 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009265 return S.Diag(Loc, diag::err_omp_not_integral) << T;
9266 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009267 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
9268 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009269 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
9270 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009271 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
9272 QualType T,
9273 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009274 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
9275 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009276 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
9277 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009278 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009279 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009280 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009281 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9282 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009283 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
9284 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009285 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
9286 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009287 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009288 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009289 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009290 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
9291 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009292 llvm_unreachable("conversion functions are permitted");
9293 }
9294 } ConvertDiagnoser;
9295 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
9296}
9297
Alexey Bataeve3727102018-04-18 15:57:46 +00009298static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00009299 OpenMPClauseKind CKind,
9300 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009301 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
9302 !ValExpr->isInstantiationDependent()) {
9303 SourceLocation Loc = ValExpr->getExprLoc();
9304 ExprResult Value =
9305 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9306 if (Value.isInvalid())
9307 return false;
9308
9309 ValExpr = Value.get();
9310 // The expression must evaluate to a non-negative integer value.
9311 llvm::APSInt Result;
9312 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00009313 Result.isSigned() &&
9314 !((!StrictlyPositive && Result.isNonNegative()) ||
9315 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009316 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009317 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9318 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009319 return false;
9320 }
9321 }
9322 return true;
9323}
9324
Alexey Bataev568a8332014-03-06 06:15:19 +00009325OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9326 SourceLocation StartLoc,
9327 SourceLocation LParenLoc,
9328 SourceLocation EndLoc) {
9329 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009330 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009331
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009332 // OpenMP [2.5, Restrictions]
9333 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +00009334 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +00009335 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009336 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009337
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009338 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00009339 OpenMPDirectiveKind CaptureRegion =
9340 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9341 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009342 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009343 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009344 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9345 HelperValStmt = buildPreInits(Context, Captures);
9346 }
9347
9348 return new (Context) OMPNumThreadsClause(
9349 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00009350}
9351
Alexey Bataev62c87d22014-03-21 04:51:18 +00009352ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009353 OpenMPClauseKind CKind,
9354 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009355 if (!E)
9356 return ExprError();
9357 if (E->isValueDependent() || E->isTypeDependent() ||
9358 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009359 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009360 llvm::APSInt Result;
9361 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9362 if (ICE.isInvalid())
9363 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009364 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9365 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009366 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009367 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9368 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00009369 return ExprError();
9370 }
Alexander Musman09184fe2014-09-30 05:29:28 +00009371 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9372 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9373 << E->getSourceRange();
9374 return ExprError();
9375 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009376 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9377 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00009378 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009379 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00009380 return ICE;
9381}
9382
9383OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9384 SourceLocation LParenLoc,
9385 SourceLocation EndLoc) {
9386 // OpenMP [2.8.1, simd construct, Description]
9387 // The parameter of the safelen clause must be a constant
9388 // positive integer expression.
9389 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9390 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009391 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009392 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009393 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00009394}
9395
Alexey Bataev66b15b52015-08-21 11:14:16 +00009396OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9397 SourceLocation LParenLoc,
9398 SourceLocation EndLoc) {
9399 // OpenMP [2.8.1, simd construct, Description]
9400 // The parameter of the simdlen clause must be a constant
9401 // positive integer expression.
9402 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9403 if (Simdlen.isInvalid())
9404 return nullptr;
9405 return new (Context)
9406 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9407}
9408
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009409/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +00009410static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
9411 DSAStackTy *Stack) {
9412 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009413 if (!OMPAllocatorHandleT.isNull())
9414 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +00009415 // Build the predefined allocator expressions.
9416 bool ErrorFound = false;
9417 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
9418 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
9419 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
9420 StringRef Allocator =
9421 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
9422 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
9423 auto *VD = dyn_cast_or_null<ValueDecl>(
9424 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
9425 if (!VD) {
9426 ErrorFound = true;
9427 break;
9428 }
9429 QualType AllocatorType =
9430 VD->getType().getNonLValueExprType(S.getASTContext());
9431 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
9432 if (!Res.isUsable()) {
9433 ErrorFound = true;
9434 break;
9435 }
9436 if (OMPAllocatorHandleT.isNull())
9437 OMPAllocatorHandleT = AllocatorType;
9438 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
9439 ErrorFound = true;
9440 break;
9441 }
9442 Stack->setAllocator(AllocatorKind, Res.get());
9443 }
9444 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009445 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
9446 return false;
9447 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00009448 OMPAllocatorHandleT.addConst();
9449 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009450 return true;
9451}
9452
9453OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
9454 SourceLocation LParenLoc,
9455 SourceLocation EndLoc) {
9456 // OpenMP [2.11.3, allocate Directive, Description]
9457 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +00009458 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009459 return nullptr;
9460
9461 ExprResult Allocator = DefaultLvalueConversion(A);
9462 if (Allocator.isInvalid())
9463 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +00009464 Allocator = PerformImplicitConversion(Allocator.get(),
9465 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009466 Sema::AA_Initializing,
9467 /*AllowExplicit=*/true);
9468 if (Allocator.isInvalid())
9469 return nullptr;
9470 return new (Context)
9471 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
9472}
9473
Alexander Musman64d33f12014-06-04 07:53:32 +00009474OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
9475 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00009476 SourceLocation LParenLoc,
9477 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00009478 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009479 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00009480 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009481 // The parameter of the collapse clause must be a constant
9482 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00009483 ExprResult NumForLoopsResult =
9484 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
9485 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00009486 return nullptr;
9487 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00009488 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00009489}
9490
Alexey Bataev10e775f2015-07-30 11:36:16 +00009491OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
9492 SourceLocation EndLoc,
9493 SourceLocation LParenLoc,
9494 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00009495 // OpenMP [2.7.1, loop construct, Description]
9496 // OpenMP [2.8.1, simd construct, Description]
9497 // OpenMP [2.9.6, distribute construct, Description]
9498 // The parameter of the ordered clause must be a constant
9499 // positive integer expression if any.
9500 if (NumForLoops && LParenLoc.isValid()) {
9501 ExprResult NumForLoopsResult =
9502 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
9503 if (NumForLoopsResult.isInvalid())
9504 return nullptr;
9505 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009506 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +00009507 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00009508 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009509 auto *Clause = OMPOrderedClause::Create(
9510 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
9511 StartLoc, LParenLoc, EndLoc);
9512 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
9513 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +00009514}
9515
Alexey Bataeved09d242014-05-28 05:53:51 +00009516OMPClause *Sema::ActOnOpenMPSimpleClause(
9517 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
9518 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009519 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009520 switch (Kind) {
9521 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009522 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00009523 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
9524 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009525 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009526 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00009527 Res = ActOnOpenMPProcBindClause(
9528 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
9529 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009530 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009531 case OMPC_atomic_default_mem_order:
9532 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
9533 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
9534 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9535 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009536 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009537 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009538 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009539 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009540 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009541 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009542 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009543 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009544 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009545 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00009546 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009547 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00009548 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009549 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009550 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00009551 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009552 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009553 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009554 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009555 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009556 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009557 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009558 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009559 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009560 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009561 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009562 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009563 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009564 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009565 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009566 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009567 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009568 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009569 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009570 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009571 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009572 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009573 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009574 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009575 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009576 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009577 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009578 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009579 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009580 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009581 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009582 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009583 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009584 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009585 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009586 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009587 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009588 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009589 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009590 case OMPC_dynamic_allocators:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009591 llvm_unreachable("Clause is not allowed.");
9592 }
9593 return Res;
9594}
9595
Alexey Bataev6402bca2015-12-28 07:25:51 +00009596static std::string
9597getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
9598 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009599 SmallString<256> Buffer;
9600 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +00009601 unsigned Bound = Last >= 2 ? Last - 2 : 0;
9602 unsigned Skipped = Exclude.size();
9603 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +00009604 for (unsigned I = First; I < Last; ++I) {
9605 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009606 --Skipped;
9607 continue;
9608 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009609 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
9610 if (I == Bound - Skipped)
9611 Out << " or ";
9612 else if (I != Bound + 1 - Skipped)
9613 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +00009614 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009615 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +00009616}
9617
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009618OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9619 SourceLocation KindKwLoc,
9620 SourceLocation StartLoc,
9621 SourceLocation LParenLoc,
9622 SourceLocation EndLoc) {
9623 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00009624 static_assert(OMPC_DEFAULT_unknown > 0,
9625 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009626 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009627 << getListOfPossibleValues(OMPC_default, /*First=*/0,
9628 /*Last=*/OMPC_DEFAULT_unknown)
9629 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009630 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009631 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00009632 switch (Kind) {
9633 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009634 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009635 break;
9636 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009637 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009638 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009639 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009640 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00009641 break;
9642 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009643 return new (Context)
9644 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009645}
9646
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009647OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9648 SourceLocation KindKwLoc,
9649 SourceLocation StartLoc,
9650 SourceLocation LParenLoc,
9651 SourceLocation EndLoc) {
9652 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009653 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009654 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
9655 /*Last=*/OMPC_PROC_BIND_unknown)
9656 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009657 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009658 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009659 return new (Context)
9660 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009661}
9662
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009663OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
9664 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
9665 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9666 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
9667 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9668 << getListOfPossibleValues(
9669 OMPC_atomic_default_mem_order, /*First=*/0,
9670 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
9671 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
9672 return nullptr;
9673 }
9674 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
9675 LParenLoc, EndLoc);
9676}
9677
Alexey Bataev56dafe82014-06-20 07:16:17 +00009678OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009679 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009680 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009681 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009682 SourceLocation EndLoc) {
9683 OMPClause *Res = nullptr;
9684 switch (Kind) {
9685 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009686 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
9687 assert(Argument.size() == NumberOfElements &&
9688 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009689 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009690 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
9691 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
9692 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
9693 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
9694 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009695 break;
9696 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009697 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
9698 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
9699 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
9700 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009701 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00009702 case OMPC_dist_schedule:
9703 Res = ActOnOpenMPDistScheduleClause(
9704 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
9705 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
9706 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009707 case OMPC_defaultmap:
9708 enum { Modifier, DefaultmapKind };
9709 Res = ActOnOpenMPDefaultmapClause(
9710 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
9711 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00009712 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
9713 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009714 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00009715 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009716 case OMPC_num_threads:
9717 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009718 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009719 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009720 case OMPC_collapse:
9721 case OMPC_default:
9722 case OMPC_proc_bind:
9723 case OMPC_private:
9724 case OMPC_firstprivate:
9725 case OMPC_lastprivate:
9726 case OMPC_shared:
9727 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009728 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009729 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009730 case OMPC_linear:
9731 case OMPC_aligned:
9732 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009733 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009734 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009735 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009736 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009737 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009738 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009739 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009740 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009741 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009742 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009743 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009744 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009745 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009746 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009747 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009748 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009749 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009750 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009751 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009752 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009753 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009754 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009755 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009756 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009757 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009758 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009759 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009760 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009761 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009762 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009763 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009764 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009765 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009766 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009767 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009768 case OMPC_atomic_default_mem_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009769 llvm_unreachable("Clause is not allowed.");
9770 }
9771 return Res;
9772}
9773
Alexey Bataev6402bca2015-12-28 07:25:51 +00009774static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
9775 OpenMPScheduleClauseModifier M2,
9776 SourceLocation M1Loc, SourceLocation M2Loc) {
9777 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
9778 SmallVector<unsigned, 2> Excluded;
9779 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
9780 Excluded.push_back(M2);
9781 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
9782 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
9783 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
9784 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
9785 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
9786 << getListOfPossibleValues(OMPC_schedule,
9787 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
9788 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9789 Excluded)
9790 << getOpenMPClauseName(OMPC_schedule);
9791 return true;
9792 }
9793 return false;
9794}
9795
Alexey Bataev56dafe82014-06-20 07:16:17 +00009796OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009797 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009798 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009799 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9800 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
9801 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
9802 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
9803 return nullptr;
9804 // OpenMP, 2.7.1, Loop Construct, Restrictions
9805 // Either the monotonic modifier or the nonmonotonic modifier can be specified
9806 // but not both.
9807 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
9808 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
9809 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
9810 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
9811 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
9812 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
9813 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
9814 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
9815 return nullptr;
9816 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009817 if (Kind == OMPC_SCHEDULE_unknown) {
9818 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00009819 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
9820 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
9821 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9822 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9823 Exclude);
9824 } else {
9825 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9826 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009827 }
9828 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
9829 << Values << getOpenMPClauseName(OMPC_schedule);
9830 return nullptr;
9831 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00009832 // OpenMP, 2.7.1, Loop Construct, Restrictions
9833 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
9834 // schedule(guided).
9835 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
9836 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
9837 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
9838 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
9839 diag::err_omp_schedule_nonmonotonic_static);
9840 return nullptr;
9841 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009842 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00009843 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00009844 if (ChunkSize) {
9845 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
9846 !ChunkSize->isInstantiationDependent() &&
9847 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009848 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +00009849 ExprResult Val =
9850 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
9851 if (Val.isInvalid())
9852 return nullptr;
9853
9854 ValExpr = Val.get();
9855
9856 // OpenMP [2.7.1, Restrictions]
9857 // chunk_size must be a loop invariant integer expression with a positive
9858 // value.
9859 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00009860 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
9861 if (Result.isSigned() && !Result.isStrictlyPositive()) {
9862 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009863 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00009864 return nullptr;
9865 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00009866 } else if (getOpenMPCaptureRegionForClause(
9867 DSAStack->getCurrentDirective(), OMPC_schedule) !=
9868 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00009869 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009870 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009871 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +00009872 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9873 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009874 }
9875 }
9876 }
9877
Alexey Bataev6402bca2015-12-28 07:25:51 +00009878 return new (Context)
9879 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00009880 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009881}
9882
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009883OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
9884 SourceLocation StartLoc,
9885 SourceLocation EndLoc) {
9886 OMPClause *Res = nullptr;
9887 switch (Kind) {
9888 case OMPC_ordered:
9889 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
9890 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00009891 case OMPC_nowait:
9892 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
9893 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009894 case OMPC_untied:
9895 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
9896 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009897 case OMPC_mergeable:
9898 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
9899 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009900 case OMPC_read:
9901 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
9902 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00009903 case OMPC_write:
9904 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
9905 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00009906 case OMPC_update:
9907 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
9908 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00009909 case OMPC_capture:
9910 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
9911 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009912 case OMPC_seq_cst:
9913 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
9914 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00009915 case OMPC_threads:
9916 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
9917 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009918 case OMPC_simd:
9919 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
9920 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00009921 case OMPC_nogroup:
9922 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9923 break;
Kelvin Li1408f912018-09-26 04:28:39 +00009924 case OMPC_unified_address:
9925 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
9926 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +00009927 case OMPC_unified_shared_memory:
9928 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9929 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009930 case OMPC_reverse_offload:
9931 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
9932 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009933 case OMPC_dynamic_allocators:
9934 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
9935 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009936 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009937 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009938 case OMPC_num_threads:
9939 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009940 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009941 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009942 case OMPC_collapse:
9943 case OMPC_schedule:
9944 case OMPC_private:
9945 case OMPC_firstprivate:
9946 case OMPC_lastprivate:
9947 case OMPC_shared:
9948 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009949 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009950 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009951 case OMPC_linear:
9952 case OMPC_aligned:
9953 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009954 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009955 case OMPC_default:
9956 case OMPC_proc_bind:
9957 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009958 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009959 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009960 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009961 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009962 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009963 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009964 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009965 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009966 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00009967 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009968 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009969 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009970 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009971 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009972 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009973 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009974 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009975 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009976 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009977 case OMPC_atomic_default_mem_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009978 llvm_unreachable("Clause is not allowed.");
9979 }
9980 return Res;
9981}
9982
Alexey Bataev236070f2014-06-20 11:19:47 +00009983OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9984 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009985 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00009986 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
9987}
9988
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009989OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9990 SourceLocation EndLoc) {
9991 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
9992}
9993
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009994OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9995 SourceLocation EndLoc) {
9996 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9997}
9998
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009999OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
10000 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010001 return new (Context) OMPReadClause(StartLoc, EndLoc);
10002}
10003
Alexey Bataevdea47612014-07-23 07:46:59 +000010004OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
10005 SourceLocation EndLoc) {
10006 return new (Context) OMPWriteClause(StartLoc, EndLoc);
10007}
10008
Alexey Bataev67a4f222014-07-23 10:25:33 +000010009OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
10010 SourceLocation EndLoc) {
10011 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
10012}
10013
Alexey Bataev459dec02014-07-24 06:46:57 +000010014OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10015 SourceLocation EndLoc) {
10016 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
10017}
10018
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010019OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10020 SourceLocation EndLoc) {
10021 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
10022}
10023
Alexey Bataev346265e2015-09-25 10:37:12 +000010024OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10025 SourceLocation EndLoc) {
10026 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
10027}
10028
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010029OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10030 SourceLocation EndLoc) {
10031 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
10032}
10033
Alexey Bataevb825de12015-12-07 10:51:44 +000010034OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10035 SourceLocation EndLoc) {
10036 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
10037}
10038
Kelvin Li1408f912018-09-26 04:28:39 +000010039OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10040 SourceLocation EndLoc) {
10041 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
10042}
10043
Patrick Lyster4a370b92018-10-01 13:47:43 +000010044OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10045 SourceLocation EndLoc) {
10046 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10047}
10048
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010049OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10050 SourceLocation EndLoc) {
10051 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
10052}
10053
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010054OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10055 SourceLocation EndLoc) {
10056 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
10057}
10058
Alexey Bataevc5e02582014-06-16 07:08:35 +000010059OMPClause *Sema::ActOnOpenMPVarListClause(
10060 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010061 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10062 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10063 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000010064 OpenMPLinearClauseKind LinKind,
10065 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010066 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
10067 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
10068 SourceLocation StartLoc = Locs.StartLoc;
10069 SourceLocation LParenLoc = Locs.LParenLoc;
10070 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010071 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010072 switch (Kind) {
10073 case OMPC_private:
10074 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10075 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010076 case OMPC_firstprivate:
10077 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10078 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010079 case OMPC_lastprivate:
10080 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10081 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010082 case OMPC_shared:
10083 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
10084 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010085 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000010086 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010087 EndLoc, ReductionOrMapperIdScopeSpec,
10088 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010089 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000010090 case OMPC_task_reduction:
10091 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010092 EndLoc, ReductionOrMapperIdScopeSpec,
10093 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000010094 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000010095 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010096 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10097 EndLoc, ReductionOrMapperIdScopeSpec,
10098 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000010099 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000010100 case OMPC_linear:
10101 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010102 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000010103 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010104 case OMPC_aligned:
10105 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
10106 ColonLoc, EndLoc);
10107 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010108 case OMPC_copyin:
10109 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
10110 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010111 case OMPC_copyprivate:
10112 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10113 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000010114 case OMPC_flush:
10115 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
10116 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010117 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000010118 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010119 StartLoc, LParenLoc, EndLoc);
10120 break;
10121 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010122 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
10123 ReductionOrMapperIdScopeSpec,
10124 ReductionOrMapperId, MapType, IsMapTypeImplicit,
10125 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010126 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010127 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000010128 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
10129 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000010130 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000010131 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000010132 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
10133 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000010134 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000010135 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010136 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010137 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000010138 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010139 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010140 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010141 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010142 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000010143 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000010144 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010145 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010146 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000010147 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010148 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010149 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010150 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010151 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010152 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010153 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010154 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010155 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010156 case OMPC_allocate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010157 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010158 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010159 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010160 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010161 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000010162 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010163 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010164 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010165 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010166 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010167 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010168 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000010169 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000010170 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010171 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010172 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010173 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010174 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010175 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000010176 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010177 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010178 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010179 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010180 case OMPC_atomic_default_mem_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010181 llvm_unreachable("Clause is not allowed.");
10182 }
10183 return Res;
10184}
10185
Alexey Bataev90c228f2016-02-08 09:29:13 +000010186ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000010187 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000010188 ExprResult Res = BuildDeclRefExpr(
10189 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
10190 if (!Res.isUsable())
10191 return ExprError();
10192 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
10193 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
10194 if (!Res.isUsable())
10195 return ExprError();
10196 }
10197 if (VK != VK_LValue && Res.get()->isGLValue()) {
10198 Res = DefaultLvalueConversion(Res.get());
10199 if (!Res.isUsable())
10200 return ExprError();
10201 }
10202 return Res;
10203}
10204
Alexey Bataev60da77e2016-02-29 05:54:20 +000010205static std::pair<ValueDecl *, bool>
10206getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
10207 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010208 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
10209 RefExpr->containsUnexpandedParameterPack())
10210 return std::make_pair(nullptr, true);
10211
Alexey Bataevd985eda2016-02-10 11:29:16 +000010212 // OpenMP [3.1, C/C++]
10213 // A list item is a variable name.
10214 // OpenMP [2.9.3.3, Restrictions, p.1]
10215 // A variable that is part of another variable (as an array or
10216 // structure element) cannot appear in a private clause.
10217 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010218 enum {
10219 NoArrayExpr = -1,
10220 ArraySubscript = 0,
10221 OMPArraySection = 1
10222 } IsArrayExpr = NoArrayExpr;
10223 if (AllowArraySection) {
10224 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010225 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010226 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
10227 Base = TempASE->getBase()->IgnoreParenImpCasts();
10228 RefExpr = Base;
10229 IsArrayExpr = ArraySubscript;
10230 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010231 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010232 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
10233 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10234 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
10235 Base = TempASE->getBase()->IgnoreParenImpCasts();
10236 RefExpr = Base;
10237 IsArrayExpr = OMPArraySection;
10238 }
10239 }
10240 ELoc = RefExpr->getExprLoc();
10241 ERange = RefExpr->getSourceRange();
10242 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +000010243 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
10244 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
10245 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
10246 (S.getCurrentThisType().isNull() || !ME ||
10247 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
10248 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010249 if (IsArrayExpr != NoArrayExpr) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010250 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
10251 << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000010252 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010253 S.Diag(ELoc,
10254 AllowArraySection
10255 ? diag::err_omp_expected_var_name_member_expr_or_array_item
10256 : diag::err_omp_expected_var_name_member_expr)
10257 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
10258 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010259 return std::make_pair(nullptr, false);
10260 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010261 return std::make_pair(
10262 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010263}
10264
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010265OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10266 SourceLocation StartLoc,
10267 SourceLocation LParenLoc,
10268 SourceLocation EndLoc) {
10269 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000010270 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000010271 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010272 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010273 SourceLocation ELoc;
10274 SourceRange ERange;
10275 Expr *SimpleRefExpr = RefExpr;
10276 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010277 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010278 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010279 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010280 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010281 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010282 ValueDecl *D = Res.first;
10283 if (!D)
10284 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010285
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010286 QualType Type = D->getType();
10287 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010288
10289 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10290 // A variable that appears in a private clause must not have an incomplete
10291 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010292 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010293 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010294 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010295
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010296 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10297 // A variable that is privatized must not have a const-qualified type
10298 // unless it is of class type with a mutable member. This restriction does
10299 // not apply to the firstprivate clause.
10300 //
10301 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
10302 // A variable that appears in a private clause must not have a
10303 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010304 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010305 continue;
10306
Alexey Bataev758e55e2013-09-06 18:03:48 +000010307 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10308 // in a Construct]
10309 // Variables with the predetermined data-sharing attributes may not be
10310 // listed in data-sharing attributes clauses, except for the cases
10311 // listed below. For these exceptions only, listing a predetermined
10312 // variable in a data-sharing attribute clause is allowed and overrides
10313 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010314 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010315 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010316 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10317 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000010318 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010319 continue;
10320 }
10321
Alexey Bataeve3727102018-04-18 15:57:46 +000010322 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010323 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010324 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000010325 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010326 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10327 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000010328 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010329 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010330 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010331 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010332 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010333 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010334 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010335 continue;
10336 }
10337
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010338 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10339 // A list item cannot appear in both a map clause and a data-sharing
10340 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000010341 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010342 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010343 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010344 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010345 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
10346 OpenMPClauseKind WhereFoundClauseKind) -> bool {
10347 ConflictKind = WhereFoundClauseKind;
10348 return true;
10349 })) {
10350 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010351 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000010352 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000010353 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000010354 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010355 continue;
10356 }
10357 }
10358
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010359 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
10360 // A variable of class type (or array thereof) that appears in a private
10361 // clause requires an accessible, unambiguous default constructor for the
10362 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000010363 // Generate helper private variable and initialize it with the default
10364 // value. The address of the original variable is replaced by the address of
10365 // the new private variable in CodeGen. This new variable is not added to
10366 // IdResolver, so the code in the OpenMP region uses original variable for
10367 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010368 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010369 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010370 buildVarDecl(*this, ELoc, Type, D->getName(),
10371 D->hasAttrs() ? &D->getAttrs() : nullptr,
10372 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000010373 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010374 if (VDPrivate->isInvalidDecl())
10375 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000010376 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010377 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010378
Alexey Bataev90c228f2016-02-08 09:29:13 +000010379 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010380 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010381 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000010382 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010383 Vars.push_back((VD || CurContext->isDependentContext())
10384 ? RefExpr->IgnoreParens()
10385 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010386 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010387 }
10388
Alexey Bataeved09d242014-05-28 05:53:51 +000010389 if (Vars.empty())
10390 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010391
Alexey Bataev03b340a2014-10-21 03:16:40 +000010392 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10393 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010394}
10395
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010396namespace {
10397class DiagsUninitializedSeveretyRAII {
10398private:
10399 DiagnosticsEngine &Diags;
10400 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000010401 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010402
10403public:
10404 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10405 bool IsIgnored)
10406 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10407 if (!IsIgnored) {
10408 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10409 /*Map*/ diag::Severity::Ignored, Loc);
10410 }
10411 }
10412 ~DiagsUninitializedSeveretyRAII() {
10413 if (!IsIgnored)
10414 Diags.popMappings(SavedLoc);
10415 }
10416};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010417}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010418
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010419OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10420 SourceLocation StartLoc,
10421 SourceLocation LParenLoc,
10422 SourceLocation EndLoc) {
10423 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010424 SmallVector<Expr *, 8> PrivateCopies;
10425 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000010426 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010427 bool IsImplicitClause =
10428 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000010429 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010430
Alexey Bataeve3727102018-04-18 15:57:46 +000010431 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010432 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010433 SourceLocation ELoc;
10434 SourceRange ERange;
10435 Expr *SimpleRefExpr = RefExpr;
10436 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010437 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010438 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010439 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010440 PrivateCopies.push_back(nullptr);
10441 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010442 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010443 ValueDecl *D = Res.first;
10444 if (!D)
10445 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010446
Alexey Bataev60da77e2016-02-29 05:54:20 +000010447 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010448 QualType Type = D->getType();
10449 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010450
10451 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10452 // A variable that appears in a private clause must not have an incomplete
10453 // type or a reference type.
10454 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000010455 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010456 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010457 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010458
10459 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10460 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000010461 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010462 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000010463 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010464
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010465 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000010466 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010467 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010468 DSAStackTy::DSAVarData DVar =
10469 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000010470 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010471 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010472 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010473 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10474 // A list item that specifies a given variable may not appear in more
10475 // than one clause on the same directive, except that a variable may be
10476 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010477 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10478 // A list item may appear in a firstprivate or lastprivate clause but not
10479 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010480 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010481 (isOpenMPDistributeDirective(CurrDir) ||
10482 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010483 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010484 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010485 << getOpenMPClauseName(DVar.CKind)
10486 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010487 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010488 continue;
10489 }
10490
10491 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10492 // in a Construct]
10493 // Variables with the predetermined data-sharing attributes may not be
10494 // listed in data-sharing attributes clauses, except for the cases
10495 // listed below. For these exceptions only, listing a predetermined
10496 // variable in a data-sharing attribute clause is allowed and overrides
10497 // the variable's predetermined data-sharing attributes.
10498 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10499 // in a Construct, C/C++, p.2]
10500 // Variables with const-qualified type having no mutable member may be
10501 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000010502 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010503 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
10504 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010505 << getOpenMPClauseName(DVar.CKind)
10506 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010507 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010508 continue;
10509 }
10510
10511 // OpenMP [2.9.3.4, Restrictions, p.2]
10512 // A list item that is private within a parallel region must not appear
10513 // in a firstprivate clause on a worksharing construct if any of the
10514 // worksharing regions arising from the worksharing construct ever bind
10515 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010516 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10517 // A list item that is private within a teams region must not appear in a
10518 // firstprivate clause on a distribute construct if any of the distribute
10519 // regions arising from the distribute construct ever bind to any of the
10520 // teams regions arising from the teams construct.
10521 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10522 // A list item that appears in a reduction clause of a teams construct
10523 // must not appear in a firstprivate clause on a distribute construct if
10524 // any of the distribute regions arising from the distribute construct
10525 // ever bind to any of the teams regions arising from the teams construct.
10526 if ((isOpenMPWorksharingDirective(CurrDir) ||
10527 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010528 !isOpenMPParallelDirective(CurrDir) &&
10529 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010530 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010531 if (DVar.CKind != OMPC_shared &&
10532 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010533 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010534 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000010535 Diag(ELoc, diag::err_omp_required_access)
10536 << getOpenMPClauseName(OMPC_firstprivate)
10537 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010538 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010539 continue;
10540 }
10541 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010542 // OpenMP [2.9.3.4, Restrictions, p.3]
10543 // A list item that appears in a reduction clause of a parallel construct
10544 // must not appear in a firstprivate clause on a worksharing or task
10545 // construct if any of the worksharing or task regions arising from the
10546 // worksharing or task construct ever bind to any of the parallel regions
10547 // arising from the parallel construct.
10548 // OpenMP [2.9.3.4, Restrictions, p.4]
10549 // A list item that appears in a reduction clause in worksharing
10550 // construct must not appear in a firstprivate clause in a task construct
10551 // encountered during execution of any of the worksharing regions arising
10552 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000010553 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010554 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010555 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10556 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010557 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010558 isOpenMPWorksharingDirective(K) ||
10559 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010560 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010561 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010562 if (DVar.CKind == OMPC_reduction &&
10563 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010564 isOpenMPWorksharingDirective(DVar.DKind) ||
10565 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010566 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10567 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000010568 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010569 continue;
10570 }
10571 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010572
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010573 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10574 // A list item cannot appear in both a map clause and a data-sharing
10575 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +000010576 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010577 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010578 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010579 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000010580 [&ConflictKind](
10581 OMPClauseMappableExprCommon::MappableExprComponentListRef,
10582 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000010583 ConflictKind = WhereFoundClauseKind;
10584 return true;
10585 })) {
10586 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010587 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000010588 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010589 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000010590 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010591 continue;
10592 }
10593 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010594 }
10595
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010596 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010597 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000010598 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010599 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10600 << getOpenMPClauseName(OMPC_firstprivate) << Type
10601 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10602 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010603 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010604 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010605 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010606 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000010607 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010608 continue;
10609 }
10610
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010611 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010612 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010613 buildVarDecl(*this, ELoc, Type, D->getName(),
10614 D->hasAttrs() ? &D->getAttrs() : nullptr,
10615 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010616 // Generate helper private variable and initialize it with the value of the
10617 // original variable. The address of the original variable is replaced by
10618 // the address of the new private variable in the CodeGen. This new variable
10619 // is not added to IdResolver, so the code in the OpenMP region uses
10620 // original variable for proper diagnostics and variable capturing.
10621 Expr *VDInitRefExpr = nullptr;
10622 // For arrays generate initializer for single element and replace it by the
10623 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010624 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010625 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010626 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010627 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010628 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010629 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010630 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
10631 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000010632 InitializedEntity Entity =
10633 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010634 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
10635
10636 InitializationSequence InitSeq(*this, Entity, Kind, Init);
10637 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
10638 if (Result.isInvalid())
10639 VDPrivate->setInvalidDecl();
10640 else
10641 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010642 // Remove temp variable declaration.
10643 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010644 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000010645 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
10646 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000010647 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10648 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000010649 AddInitializerToDecl(VDPrivate,
10650 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010651 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010652 }
10653 if (VDPrivate->isInvalidDecl()) {
10654 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010655 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010656 diag::note_omp_task_predetermined_firstprivate_here);
10657 }
10658 continue;
10659 }
10660 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010661 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000010662 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10663 RefExpr->getExprLoc());
10664 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010665 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010666 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010667 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010668 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010669 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010670 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010671 ExprCaptures.push_back(Ref->getDecl());
10672 }
Alexey Bataev417089f2016-02-17 13:19:37 +000010673 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010674 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010675 Vars.push_back((VD || CurContext->isDependentContext())
10676 ? RefExpr->IgnoreParens()
10677 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010678 PrivateCopies.push_back(VDPrivateRefExpr);
10679 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010680 }
10681
Alexey Bataeved09d242014-05-28 05:53:51 +000010682 if (Vars.empty())
10683 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010684
10685 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010686 Vars, PrivateCopies, Inits,
10687 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010688}
10689
Alexander Musman1bb328c2014-06-04 13:06:39 +000010690OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
10691 SourceLocation StartLoc,
10692 SourceLocation LParenLoc,
10693 SourceLocation EndLoc) {
10694 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000010695 SmallVector<Expr *, 8> SrcExprs;
10696 SmallVector<Expr *, 8> DstExprs;
10697 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000010698 SmallVector<Decl *, 4> ExprCaptures;
10699 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000010700 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010701 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010702 SourceLocation ELoc;
10703 SourceRange ERange;
10704 Expr *SimpleRefExpr = RefExpr;
10705 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000010706 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010707 // It will be analyzed later.
10708 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010709 SrcExprs.push_back(nullptr);
10710 DstExprs.push_back(nullptr);
10711 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010712 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010713 ValueDecl *D = Res.first;
10714 if (!D)
10715 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010716
Alexey Bataev74caaf22016-02-20 04:09:36 +000010717 QualType Type = D->getType();
10718 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010719
10720 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
10721 // A variable that appears in a lastprivate clause must not have an
10722 // incomplete type or a reference type.
10723 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000010724 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000010725 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010726 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010727
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010728 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10729 // A variable that is privatized must not have a const-qualified type
10730 // unless it is of class type with a mutable member. This restriction does
10731 // not apply to the firstprivate clause.
10732 //
10733 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
10734 // A variable that appears in a lastprivate clause must not have a
10735 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010736 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010737 continue;
10738
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010739 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010740 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10741 // in a Construct]
10742 // Variables with the predetermined data-sharing attributes may not be
10743 // listed in data-sharing attributes clauses, except for the cases
10744 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010745 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10746 // A list item may appear in a firstprivate or lastprivate clause but not
10747 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000010748 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010749 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010750 (isOpenMPDistributeDirective(CurrDir) ||
10751 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000010752 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
10753 Diag(ELoc, diag::err_omp_wrong_dsa)
10754 << getOpenMPClauseName(DVar.CKind)
10755 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010756 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010757 continue;
10758 }
10759
Alexey Bataevf29276e2014-06-18 04:14:57 +000010760 // OpenMP [2.14.3.5, Restrictions, p.2]
10761 // A list item that is private within a parallel region, or that appears in
10762 // the reduction clause of a parallel construct, must not appear in a
10763 // lastprivate clause on a worksharing construct if any of the corresponding
10764 // worksharing regions ever binds to any of the corresponding parallel
10765 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000010766 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000010767 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010768 !isOpenMPParallelDirective(CurrDir) &&
10769 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000010770 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010771 if (DVar.CKind != OMPC_shared) {
10772 Diag(ELoc, diag::err_omp_required_access)
10773 << getOpenMPClauseName(OMPC_lastprivate)
10774 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010775 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010776 continue;
10777 }
10778 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010779
Alexander Musman1bb328c2014-06-04 13:06:39 +000010780 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000010781 // A variable of class type (or array thereof) that appears in a
10782 // lastprivate clause requires an accessible, unambiguous default
10783 // constructor for the class type, unless the list item is also specified
10784 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000010785 // A variable of class type (or array thereof) that appears in a
10786 // lastprivate clause requires an accessible, unambiguous copy assignment
10787 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000010788 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010789 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
10790 Type.getUnqualifiedType(), ".lastprivate.src",
10791 D->hasAttrs() ? &D->getAttrs() : nullptr);
10792 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000010793 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010794 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010795 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000010796 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000010797 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000010798 // For arrays generate assignment operation for single element and replace
10799 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010800 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
10801 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010802 if (AssignmentOp.isInvalid())
10803 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000010804 AssignmentOp =
10805 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000010806 if (AssignmentOp.isInvalid())
10807 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010808
Alexey Bataev74caaf22016-02-20 04:09:36 +000010809 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010810 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010811 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010812 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010813 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010814 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000010815 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010816 ExprCaptures.push_back(Ref->getDecl());
10817 }
10818 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000010819 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010820 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010821 ExprResult RefRes = DefaultLvalueConversion(Ref);
10822 if (!RefRes.isUsable())
10823 continue;
10824 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010825 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10826 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010827 if (!PostUpdateRes.isUsable())
10828 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010829 ExprPostUpdates.push_back(
10830 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010831 }
10832 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010833 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010834 Vars.push_back((VD || CurContext->isDependentContext())
10835 ? RefExpr->IgnoreParens()
10836 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000010837 SrcExprs.push_back(PseudoSrcExpr);
10838 DstExprs.push_back(PseudoDstExpr);
10839 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000010840 }
10841
10842 if (Vars.empty())
10843 return nullptr;
10844
10845 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000010846 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010847 buildPreInits(Context, ExprCaptures),
10848 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000010849}
10850
Alexey Bataev758e55e2013-09-06 18:03:48 +000010851OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10852 SourceLocation StartLoc,
10853 SourceLocation LParenLoc,
10854 SourceLocation EndLoc) {
10855 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000010856 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010857 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010858 SourceLocation ELoc;
10859 SourceRange ERange;
10860 Expr *SimpleRefExpr = RefExpr;
10861 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010862 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000010863 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010864 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010865 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010866 ValueDecl *D = Res.first;
10867 if (!D)
10868 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010869
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010870 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010871 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10872 // in a Construct]
10873 // Variables with the predetermined data-sharing attributes may not be
10874 // listed in data-sharing attributes clauses, except for the cases
10875 // listed below. For these exceptions only, listing a predetermined
10876 // variable in a data-sharing attribute clause is allowed and overrides
10877 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010878 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000010879 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
10880 DVar.RefExpr) {
10881 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10882 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010883 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010884 continue;
10885 }
10886
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010887 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010888 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010889 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010890 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010891 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
10892 ? RefExpr->IgnoreParens()
10893 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010894 }
10895
Alexey Bataeved09d242014-05-28 05:53:51 +000010896 if (Vars.empty())
10897 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010898
10899 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
10900}
10901
Alexey Bataevc5e02582014-06-16 07:08:35 +000010902namespace {
10903class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
10904 DSAStackTy *Stack;
10905
10906public:
10907 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010908 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
10909 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010910 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
10911 return false;
10912 if (DVar.CKind != OMPC_unknown)
10913 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010914 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010915 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010916 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010917 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010918 }
10919 return false;
10920 }
10921 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010922 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010923 if (Child && Visit(Child))
10924 return true;
10925 }
10926 return false;
10927 }
Alexey Bataev23b69422014-06-18 07:08:49 +000010928 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010929};
Alexey Bataev23b69422014-06-18 07:08:49 +000010930} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000010931
Alexey Bataev60da77e2016-02-29 05:54:20 +000010932namespace {
10933// Transform MemberExpression for specified FieldDecl of current class to
10934// DeclRefExpr to specified OMPCapturedExprDecl.
10935class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
10936 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000010937 ValueDecl *Field = nullptr;
10938 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010939
10940public:
10941 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
10942 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
10943
10944 ExprResult TransformMemberExpr(MemberExpr *E) {
10945 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
10946 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000010947 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010948 return CapturedExpr;
10949 }
10950 return BaseTransform::TransformMemberExpr(E);
10951 }
10952 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
10953};
10954} // namespace
10955
Alexey Bataev97d18bf2018-04-11 19:21:00 +000010956template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000010957static T filterLookupForUDReductionAndMapper(
10958 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010959 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010960 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010961 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010962 return Res;
10963 }
10964 }
10965 return T();
10966}
10967
Alexey Bataev43b90b72018-09-12 16:31:59 +000010968static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
10969 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
10970
10971 for (auto RD : D->redecls()) {
10972 // Don't bother with extra checks if we already know this one isn't visible.
10973 if (RD == D)
10974 continue;
10975
10976 auto ND = cast<NamedDecl>(RD);
10977 if (LookupResult::isVisible(SemaRef, ND))
10978 return ND;
10979 }
10980
10981 return nullptr;
10982}
10983
10984static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000010985argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000010986 SourceLocation Loc, QualType Ty,
10987 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
10988 // Find all of the associated namespaces and classes based on the
10989 // arguments we have.
10990 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10991 Sema::AssociatedClassSet AssociatedClasses;
10992 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
10993 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
10994 AssociatedClasses);
10995
10996 // C++ [basic.lookup.argdep]p3:
10997 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10998 // and let Y be the lookup set produced by argument dependent
10999 // lookup (defined as follows). If X contains [...] then Y is
11000 // empty. Otherwise Y is the set of declarations found in the
11001 // namespaces associated with the argument types as described
11002 // below. The set of declarations found by the lookup of the name
11003 // is the union of X and Y.
11004 //
11005 // Here, we compute Y and add its members to the overloaded
11006 // candidate set.
11007 for (auto *NS : AssociatedNamespaces) {
11008 // When considering an associated namespace, the lookup is the
11009 // same as the lookup performed when the associated namespace is
11010 // used as a qualifier (3.4.3.2) except that:
11011 //
11012 // -- Any using-directives in the associated namespace are
11013 // ignored.
11014 //
11015 // -- Any namespace-scope friend functions declared in
11016 // associated classes are visible within their respective
11017 // namespaces even if they are not visible during an ordinary
11018 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000011019 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000011020 for (auto *D : R) {
11021 auto *Underlying = D;
11022 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11023 Underlying = USD->getTargetDecl();
11024
Michael Kruse4304e9d2019-02-19 16:38:20 +000011025 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
11026 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000011027 continue;
11028
11029 if (!SemaRef.isVisible(D)) {
11030 D = findAcceptableDecl(SemaRef, D);
11031 if (!D)
11032 continue;
11033 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11034 Underlying = USD->getTargetDecl();
11035 }
11036 Lookups.emplace_back();
11037 Lookups.back().addDecl(Underlying);
11038 }
11039 }
11040}
11041
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011042static ExprResult
11043buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
11044 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
11045 const DeclarationNameInfo &ReductionId, QualType Ty,
11046 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
11047 if (ReductionIdScopeSpec.isInvalid())
11048 return ExprError();
11049 SmallVector<UnresolvedSet<8>, 4> Lookups;
11050 if (S) {
11051 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11052 Lookup.suppressDiagnostics();
11053 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011054 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011055 do {
11056 S = S->getParent();
11057 } while (S && !S->isDeclScope(D));
11058 if (S)
11059 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000011060 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011061 Lookups.back().append(Lookup.begin(), Lookup.end());
11062 Lookup.clear();
11063 }
11064 } else if (auto *ULE =
11065 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
11066 Lookups.push_back(UnresolvedSet<8>());
11067 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011068 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011069 if (D == PrevD)
11070 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000011071 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011072 Lookups.back().addDecl(DRD);
11073 PrevD = D;
11074 }
11075 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000011076 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
11077 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011078 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000011079 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011080 return !D->isInvalidDecl() &&
11081 (D->getType()->isDependentType() ||
11082 D->getType()->isInstantiationDependentType() ||
11083 D->getType()->containsUnexpandedParameterPack());
11084 })) {
11085 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000011086 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000011087 if (Set.empty())
11088 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011089 ResSet.append(Set.begin(), Set.end());
11090 // The last item marks the end of all declarations at the specified scope.
11091 ResSet.addDecl(Set[Set.size() - 1]);
11092 }
11093 return UnresolvedLookupExpr::Create(
11094 SemaRef.Context, /*NamingClass=*/nullptr,
11095 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
11096 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
11097 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000011098 // Lookup inside the classes.
11099 // C++ [over.match.oper]p3:
11100 // For a unary operator @ with an operand of a type whose
11101 // cv-unqualified version is T1, and for a binary operator @ with
11102 // a left operand of a type whose cv-unqualified version is T1 and
11103 // a right operand of a type whose cv-unqualified version is T2,
11104 // three sets of candidate functions, designated member
11105 // candidates, non-member candidates and built-in candidates, are
11106 // constructed as follows:
11107 // -- If T1 is a complete class type or a class currently being
11108 // defined, the set of member candidates is the result of the
11109 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
11110 // the set of member candidates is empty.
11111 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11112 Lookup.suppressDiagnostics();
11113 if (const auto *TyRec = Ty->getAs<RecordType>()) {
11114 // Complete the type if it can be completed.
11115 // If the type is neither complete nor being defined, bail out now.
11116 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
11117 TyRec->getDecl()->getDefinition()) {
11118 Lookup.clear();
11119 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
11120 if (Lookup.empty()) {
11121 Lookups.emplace_back();
11122 Lookups.back().append(Lookup.begin(), Lookup.end());
11123 }
11124 }
11125 }
11126 // Perform ADL.
Alexey Bataev74a04e82019-03-13 19:31:34 +000011127 if (SemaRef.getLangOpts().CPlusPlus) {
11128 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
11129 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11130 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
11131 if (!D->isInvalidDecl() &&
11132 SemaRef.Context.hasSameType(D->getType(), Ty))
11133 return D;
11134 return nullptr;
11135 }))
11136 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
11137 VK_LValue, Loc);
11138 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11139 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
11140 if (!D->isInvalidDecl() &&
11141 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
11142 !Ty.isMoreQualifiedThan(D->getType()))
11143 return D;
11144 return nullptr;
11145 })) {
11146 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
11147 /*DetectVirtual=*/false);
11148 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
11149 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
11150 VD->getType().getUnqualifiedType()))) {
11151 if (SemaRef.CheckBaseClassAccess(
11152 Loc, VD->getType(), Ty, Paths.front(),
11153 /*DiagID=*/0) != Sema::AR_inaccessible) {
11154 SemaRef.BuildBasePathArray(Paths, BasePath);
11155 return SemaRef.BuildDeclRefExpr(
11156 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
11157 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011158 }
11159 }
11160 }
11161 }
11162 if (ReductionIdScopeSpec.isSet()) {
11163 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
11164 return ExprError();
11165 }
11166 return ExprEmpty();
11167}
11168
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011169namespace {
11170/// Data for the reduction-based clauses.
11171struct ReductionData {
11172 /// List of original reduction items.
11173 SmallVector<Expr *, 8> Vars;
11174 /// List of private copies of the reduction items.
11175 SmallVector<Expr *, 8> Privates;
11176 /// LHS expressions for the reduction_op expressions.
11177 SmallVector<Expr *, 8> LHSs;
11178 /// RHS expressions for the reduction_op expressions.
11179 SmallVector<Expr *, 8> RHSs;
11180 /// Reduction operation expression.
11181 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000011182 /// Taskgroup descriptors for the corresponding reduction items in
11183 /// in_reduction clauses.
11184 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011185 /// List of captures for clause.
11186 SmallVector<Decl *, 4> ExprCaptures;
11187 /// List of postupdate expressions.
11188 SmallVector<Expr *, 4> ExprPostUpdates;
11189 ReductionData() = delete;
11190 /// Reserves required memory for the reduction data.
11191 ReductionData(unsigned Size) {
11192 Vars.reserve(Size);
11193 Privates.reserve(Size);
11194 LHSs.reserve(Size);
11195 RHSs.reserve(Size);
11196 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000011197 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011198 ExprCaptures.reserve(Size);
11199 ExprPostUpdates.reserve(Size);
11200 }
11201 /// Stores reduction item and reduction operation only (required for dependent
11202 /// reduction item).
11203 void push(Expr *Item, Expr *ReductionOp) {
11204 Vars.emplace_back(Item);
11205 Privates.emplace_back(nullptr);
11206 LHSs.emplace_back(nullptr);
11207 RHSs.emplace_back(nullptr);
11208 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011209 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011210 }
11211 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000011212 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
11213 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011214 Vars.emplace_back(Item);
11215 Privates.emplace_back(Private);
11216 LHSs.emplace_back(LHS);
11217 RHSs.emplace_back(RHS);
11218 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011219 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011220 }
11221};
11222} // namespace
11223
Alexey Bataeve3727102018-04-18 15:57:46 +000011224static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011225 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
11226 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
11227 const Expr *Length = OASE->getLength();
11228 if (Length == nullptr) {
11229 // For array sections of the form [1:] or [:], we would need to analyze
11230 // the lower bound...
11231 if (OASE->getColonLoc().isValid())
11232 return false;
11233
11234 // This is an array subscript which has implicit length 1!
11235 SingleElement = true;
11236 ArraySizes.push_back(llvm::APSInt::get(1));
11237 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011238 Expr::EvalResult Result;
11239 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011240 return false;
11241
Fangrui Song407659a2018-11-30 23:41:18 +000011242 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011243 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
11244 ArraySizes.push_back(ConstantLengthValue);
11245 }
11246
11247 // Get the base of this array section and walk up from there.
11248 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
11249
11250 // We require length = 1 for all array sections except the right-most to
11251 // guarantee that the memory region is contiguous and has no holes in it.
11252 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
11253 Length = TempOASE->getLength();
11254 if (Length == nullptr) {
11255 // For array sections of the form [1:] or [:], we would need to analyze
11256 // the lower bound...
11257 if (OASE->getColonLoc().isValid())
11258 return false;
11259
11260 // This is an array subscript which has implicit length 1!
11261 ArraySizes.push_back(llvm::APSInt::get(1));
11262 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011263 Expr::EvalResult Result;
11264 if (!Length->EvaluateAsInt(Result, Context))
11265 return false;
11266
11267 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
11268 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011269 return false;
11270
11271 ArraySizes.push_back(ConstantLengthValue);
11272 }
11273 Base = TempOASE->getBase()->IgnoreParenImpCasts();
11274 }
11275
11276 // If we have a single element, we don't need to add the implicit lengths.
11277 if (!SingleElement) {
11278 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
11279 // Has implicit length 1!
11280 ArraySizes.push_back(llvm::APSInt::get(1));
11281 Base = TempASE->getBase()->IgnoreParenImpCasts();
11282 }
11283 }
11284
11285 // This array section can be privatized as a single value or as a constant
11286 // sized array.
11287 return true;
11288}
11289
Alexey Bataeve3727102018-04-18 15:57:46 +000011290static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000011291 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
11292 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11293 SourceLocation ColonLoc, SourceLocation EndLoc,
11294 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011295 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011296 DeclarationName DN = ReductionId.getName();
11297 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011298 BinaryOperatorKind BOK = BO_Comma;
11299
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011300 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011301 // OpenMP [2.14.3.6, reduction clause]
11302 // C
11303 // reduction-identifier is either an identifier or one of the following
11304 // operators: +, -, *, &, |, ^, && and ||
11305 // C++
11306 // reduction-identifier is either an id-expression or one of the following
11307 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000011308 switch (OOK) {
11309 case OO_Plus:
11310 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011311 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011312 break;
11313 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011314 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011315 break;
11316 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011317 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011318 break;
11319 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011320 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011321 break;
11322 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011323 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011324 break;
11325 case OO_AmpAmp:
11326 BOK = BO_LAnd;
11327 break;
11328 case OO_PipePipe:
11329 BOK = BO_LOr;
11330 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011331 case OO_New:
11332 case OO_Delete:
11333 case OO_Array_New:
11334 case OO_Array_Delete:
11335 case OO_Slash:
11336 case OO_Percent:
11337 case OO_Tilde:
11338 case OO_Exclaim:
11339 case OO_Equal:
11340 case OO_Less:
11341 case OO_Greater:
11342 case OO_LessEqual:
11343 case OO_GreaterEqual:
11344 case OO_PlusEqual:
11345 case OO_MinusEqual:
11346 case OO_StarEqual:
11347 case OO_SlashEqual:
11348 case OO_PercentEqual:
11349 case OO_CaretEqual:
11350 case OO_AmpEqual:
11351 case OO_PipeEqual:
11352 case OO_LessLess:
11353 case OO_GreaterGreater:
11354 case OO_LessLessEqual:
11355 case OO_GreaterGreaterEqual:
11356 case OO_EqualEqual:
11357 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000011358 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011359 case OO_PlusPlus:
11360 case OO_MinusMinus:
11361 case OO_Comma:
11362 case OO_ArrowStar:
11363 case OO_Arrow:
11364 case OO_Call:
11365 case OO_Subscript:
11366 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000011367 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011368 case NUM_OVERLOADED_OPERATORS:
11369 llvm_unreachable("Unexpected reduction identifier");
11370 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000011371 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011372 if (II->isStr("max"))
11373 BOK = BO_GT;
11374 else if (II->isStr("min"))
11375 BOK = BO_LT;
11376 }
11377 break;
11378 }
11379 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011380 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000011381 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011382 else
11383 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011384 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011385
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011386 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11387 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000011388 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011389 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000011390 // OpenMP [2.1, C/C++]
11391 // A list item is a variable or array section, subject to the restrictions
11392 // specified in Section 2.4 on page 42 and in each of the sections
11393 // describing clauses and directives for which a list appears.
11394 // OpenMP [2.14.3.3, Restrictions, p.1]
11395 // A variable that is part of another variable (as an array or
11396 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011397 if (!FirstIter && IR != ER)
11398 ++IR;
11399 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011400 SourceLocation ELoc;
11401 SourceRange ERange;
11402 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011403 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000011404 /*AllowArraySection=*/true);
11405 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011406 // Try to find 'declare reduction' corresponding construct before using
11407 // builtin/overloaded operators.
11408 QualType Type = Context.DependentTy;
11409 CXXCastPath BasePath;
11410 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011411 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011412 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011413 Expr *ReductionOp = nullptr;
11414 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011415 (DeclareReductionRef.isUnset() ||
11416 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011417 ReductionOp = DeclareReductionRef.get();
11418 // It will be analyzed later.
11419 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011420 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011421 ValueDecl *D = Res.first;
11422 if (!D)
11423 continue;
11424
Alexey Bataev88202be2017-07-27 13:20:36 +000011425 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000011426 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011427 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11428 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000011429 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000011430 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011431 } else if (OASE) {
11432 QualType BaseType =
11433 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11434 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000011435 Type = ATy->getElementType();
11436 else
11437 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000011438 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011439 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011440 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000011441 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011442 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000011443
Alexey Bataevc5e02582014-06-16 07:08:35 +000011444 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11445 // A variable that appears in a private clause must not have an incomplete
11446 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000011447 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011448 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011449 continue;
11450 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000011451 // A list item that appears in a reduction clause must not be
11452 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011453 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11454 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011455 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000011456
11457 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011458 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11459 // If a list-item is a reference type then it must bind to the same object
11460 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000011461 if (!ASE && !OASE) {
11462 if (VD) {
11463 VarDecl *VDDef = VD->getDefinition();
11464 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11465 DSARefChecker Check(Stack);
11466 if (Check.Visit(VDDef->getInit())) {
11467 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11468 << getOpenMPClauseName(ClauseKind) << ERange;
11469 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11470 continue;
11471 }
Alexey Bataeva1764212015-09-30 09:22:36 +000011472 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000011473 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011474
Alexey Bataevbc529672018-09-28 19:33:14 +000011475 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11476 // in a Construct]
11477 // Variables with the predetermined data-sharing attributes may not be
11478 // listed in data-sharing attributes clauses, except for the cases
11479 // listed below. For these exceptions only, listing a predetermined
11480 // variable in a data-sharing attribute clause is allowed and overrides
11481 // the variable's predetermined data-sharing attributes.
11482 // OpenMP [2.14.3.6, Restrictions, p.3]
11483 // Any number of reduction clauses can be specified on the directive,
11484 // but a list item can appear only once in the reduction clauses for that
11485 // directive.
11486 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11487 if (DVar.CKind == OMPC_reduction) {
11488 S.Diag(ELoc, diag::err_omp_once_referenced)
11489 << getOpenMPClauseName(ClauseKind);
11490 if (DVar.RefExpr)
11491 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
11492 continue;
11493 }
11494 if (DVar.CKind != OMPC_unknown) {
11495 S.Diag(ELoc, diag::err_omp_wrong_dsa)
11496 << getOpenMPClauseName(DVar.CKind)
11497 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000011498 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011499 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000011500 }
Alexey Bataevbc529672018-09-28 19:33:14 +000011501
11502 // OpenMP [2.14.3.6, Restrictions, p.1]
11503 // A list item that appears in a reduction clause of a worksharing
11504 // construct must be shared in the parallel regions to which any of the
11505 // worksharing regions arising from the worksharing construct bind.
11506 if (isOpenMPWorksharingDirective(CurrDir) &&
11507 !isOpenMPParallelDirective(CurrDir) &&
11508 !isOpenMPTeamsDirective(CurrDir)) {
11509 DVar = Stack->getImplicitDSA(D, true);
11510 if (DVar.CKind != OMPC_shared) {
11511 S.Diag(ELoc, diag::err_omp_required_access)
11512 << getOpenMPClauseName(OMPC_reduction)
11513 << getOpenMPClauseName(OMPC_shared);
11514 reportOriginalDsa(S, Stack, D, DVar);
11515 continue;
11516 }
11517 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000011518 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011519
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011520 // Try to find 'declare reduction' corresponding construct before using
11521 // builtin/overloaded operators.
11522 CXXCastPath BasePath;
11523 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011524 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011525 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11526 if (DeclareReductionRef.isInvalid())
11527 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011528 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011529 (DeclareReductionRef.isUnset() ||
11530 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011531 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011532 continue;
11533 }
11534 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
11535 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011536 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011537 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011538 << Type << ReductionIdRange;
11539 continue;
11540 }
11541
11542 // OpenMP [2.14.3.6, reduction clause, Restrictions]
11543 // The type of a list item that appears in a reduction clause must be valid
11544 // for the reduction-identifier. For a max or min reduction in C, the type
11545 // of the list item must be an allowed arithmetic data type: char, int,
11546 // float, double, or _Bool, possibly modified with long, short, signed, or
11547 // unsigned. For a max or min reduction in C++, the type of the list item
11548 // must be an allowed arithmetic data type: char, wchar_t, int, float,
11549 // double, or bool, possibly modified with long, short, signed, or unsigned.
11550 if (DeclareReductionRef.isUnset()) {
11551 if ((BOK == BO_GT || BOK == BO_LT) &&
11552 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011553 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
11554 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000011555 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011556 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011557 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11558 VarDecl::DeclarationOnly;
11559 S.Diag(D->getLocation(),
11560 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011561 << D;
11562 }
11563 continue;
11564 }
11565 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011566 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000011567 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11568 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011569 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011570 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11571 VarDecl::DeclarationOnly;
11572 S.Diag(D->getLocation(),
11573 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011574 << D;
11575 }
11576 continue;
11577 }
11578 }
11579
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011580 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011581 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
11582 D->hasAttrs() ? &D->getAttrs() : nullptr);
11583 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
11584 D->hasAttrs() ? &D->getAttrs() : nullptr);
11585 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011586
11587 // Try if we can determine constant lengths for all array sections and avoid
11588 // the VLA.
11589 bool ConstantLengthOASE = false;
11590 if (OASE) {
11591 bool SingleElement;
11592 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000011593 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011594 Context, OASE, SingleElement, ArraySizes);
11595
11596 // If we don't have a single element, we must emit a constant array type.
11597 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011598 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011599 PrivateTy = Context.getConstantArrayType(
11600 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011601 }
11602 }
11603
11604 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000011605 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000011606 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000011607 if (!Context.getTargetInfo().isVLASupported() &&
11608 S.shouldDiagnoseTargetSupportFromOpenMP()) {
11609 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
11610 S.Diag(ELoc, diag::note_vla_unsupported);
11611 continue;
11612 }
David Majnemer9d168222016-08-05 17:44:54 +000011613 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011614 // Create pseudo array type for private copy. The size for this array will
11615 // be generated during codegen.
11616 // For array subscripts or single variables Private Ty is the same as Type
11617 // (type of the variable or single array element).
11618 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011619 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000011620 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011621 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000011622 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000011623 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011624 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011625 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011626 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000011627 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011628 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
11629 D->hasAttrs() ? &D->getAttrs() : nullptr,
11630 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011631 // Add initializer for private variable.
11632 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011633 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
11634 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011635 if (DeclareReductionRef.isUsable()) {
11636 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
11637 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
11638 if (DRD->getInitializer()) {
11639 Init = DRDRef;
11640 RHSVD->setInit(DRDRef);
11641 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011642 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011643 } else {
11644 switch (BOK) {
11645 case BO_Add:
11646 case BO_Xor:
11647 case BO_Or:
11648 case BO_LOr:
11649 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
11650 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011651 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011652 break;
11653 case BO_Mul:
11654 case BO_LAnd:
11655 if (Type->isScalarType() || Type->isAnyComplexType()) {
11656 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011657 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011658 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011659 break;
11660 case BO_And: {
11661 // '&' reduction op - initializer is '~0'.
11662 QualType OrigType = Type;
11663 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
11664 Type = ComplexTy->getElementType();
11665 if (Type->isRealFloatingType()) {
11666 llvm::APFloat InitValue =
11667 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
11668 /*isIEEE=*/true);
11669 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11670 Type, ELoc);
11671 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011672 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011673 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11674 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11675 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11676 }
11677 if (Init && OrigType->isAnyComplexType()) {
11678 // Init = 0xFFFF + 0xFFFFi;
11679 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011680 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011681 }
11682 Type = OrigType;
11683 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011684 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011685 case BO_LT:
11686 case BO_GT: {
11687 // 'min' reduction op - initializer is 'Largest representable number in
11688 // the reduction list item type'.
11689 // 'max' reduction op - initializer is 'Least representable number in
11690 // the reduction list item type'.
11691 if (Type->isIntegerType() || Type->isPointerType()) {
11692 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000011693 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011694 QualType IntTy =
11695 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
11696 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011697 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
11698 : llvm::APInt::getMinValue(Size)
11699 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
11700 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011701 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11702 if (Type->isPointerType()) {
11703 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000011704 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000011705 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011706 if (CastExpr.isInvalid())
11707 continue;
11708 Init = CastExpr.get();
11709 }
11710 } else if (Type->isRealFloatingType()) {
11711 llvm::APFloat InitValue = llvm::APFloat::getLargest(
11712 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
11713 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11714 Type, ELoc);
11715 }
11716 break;
11717 }
11718 case BO_PtrMemD:
11719 case BO_PtrMemI:
11720 case BO_MulAssign:
11721 case BO_Div:
11722 case BO_Rem:
11723 case BO_Sub:
11724 case BO_Shl:
11725 case BO_Shr:
11726 case BO_LE:
11727 case BO_GE:
11728 case BO_EQ:
11729 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000011730 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011731 case BO_AndAssign:
11732 case BO_XorAssign:
11733 case BO_OrAssign:
11734 case BO_Assign:
11735 case BO_AddAssign:
11736 case BO_SubAssign:
11737 case BO_DivAssign:
11738 case BO_RemAssign:
11739 case BO_ShlAssign:
11740 case BO_ShrAssign:
11741 case BO_Comma:
11742 llvm_unreachable("Unexpected reduction operation");
11743 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011744 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011745 if (Init && DeclareReductionRef.isUnset())
11746 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
11747 else if (!Init)
11748 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011749 if (RHSVD->isInvalidDecl())
11750 continue;
11751 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011752 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
11753 << Type << ReductionIdRange;
11754 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11755 VarDecl::DeclarationOnly;
11756 S.Diag(D->getLocation(),
11757 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000011758 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011759 continue;
11760 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011761 // Store initializer for single element in private copy. Will be used during
11762 // codegen.
11763 PrivateVD->setInit(RHSVD->getInit());
11764 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000011765 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011766 ExprResult ReductionOp;
11767 if (DeclareReductionRef.isUsable()) {
11768 QualType RedTy = DeclareReductionRef.get()->getType();
11769 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011770 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
11771 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011772 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011773 LHS = S.DefaultLvalueConversion(LHS.get());
11774 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011775 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11776 CK_UncheckedDerivedToBase, LHS.get(),
11777 &BasePath, LHS.get()->getValueKind());
11778 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11779 CK_UncheckedDerivedToBase, RHS.get(),
11780 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011781 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011782 FunctionProtoType::ExtProtoInfo EPI;
11783 QualType Params[] = {PtrRedTy, PtrRedTy};
11784 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
11785 auto *OVE = new (Context) OpaqueValueExpr(
11786 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011787 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011788 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000011789 ReductionOp =
11790 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011791 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011792 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011793 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011794 if (ReductionOp.isUsable()) {
11795 if (BOK != BO_LT && BOK != BO_GT) {
11796 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011797 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011798 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011799 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000011800 auto *ConditionalOp = new (Context)
11801 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
11802 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011803 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011804 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011805 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011806 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011807 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011808 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
11809 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011810 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011811 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011812 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011813 }
11814
Alexey Bataevfa312f32017-07-21 18:48:21 +000011815 // OpenMP [2.15.4.6, Restrictions, p.2]
11816 // A list item that appears in an in_reduction clause of a task construct
11817 // must appear in a task_reduction clause of a construct associated with a
11818 // taskgroup region that includes the participating task in its taskgroup
11819 // set. The construct associated with the innermost region that meets this
11820 // condition must specify the same reduction-identifier as the in_reduction
11821 // clause.
11822 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000011823 SourceRange ParentSR;
11824 BinaryOperatorKind ParentBOK;
11825 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000011826 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000011827 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011828 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
11829 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011830 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011831 Stack->getTopMostTaskgroupReductionData(
11832 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011833 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
11834 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
11835 if (!IsParentBOK && !IsParentReductionOp) {
11836 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
11837 continue;
11838 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000011839 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
11840 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
11841 IsParentReductionOp) {
11842 bool EmitError = true;
11843 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
11844 llvm::FoldingSetNodeID RedId, ParentRedId;
11845 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
11846 DeclareReductionRef.get()->Profile(RedId, Context,
11847 /*Canonical=*/true);
11848 EmitError = RedId != ParentRedId;
11849 }
11850 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011851 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000011852 diag::err_omp_reduction_identifier_mismatch)
11853 << ReductionIdRange << RefExpr->getSourceRange();
11854 S.Diag(ParentSR.getBegin(),
11855 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000011856 << ParentSR
11857 << (IsParentBOK ? ParentBOKDSA.RefExpr
11858 : ParentReductionOpDSA.RefExpr)
11859 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000011860 continue;
11861 }
11862 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011863 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
11864 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000011865 }
11866
Alexey Bataev60da77e2016-02-29 05:54:20 +000011867 DeclRefExpr *Ref = nullptr;
11868 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011869 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011870 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011871 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000011872 VarsExpr =
11873 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
11874 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000011875 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011876 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011877 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011878 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011879 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011880 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011881 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011882 if (!RefRes.isUsable())
11883 continue;
11884 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011885 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11886 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011887 if (!PostUpdateRes.isUsable())
11888 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011889 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
11890 Stack->getCurrentDirective() == OMPD_taskgroup) {
11891 S.Diag(RefExpr->getExprLoc(),
11892 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000011893 << RefExpr->getSourceRange();
11894 continue;
11895 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011896 RD.ExprPostUpdates.emplace_back(
11897 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000011898 }
11899 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011900 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000011901 // All reduction items are still marked as reduction (to do not increase
11902 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011903 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011904 if (CurrDir == OMPD_taskgroup) {
11905 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011906 Stack->addTaskgroupReductionData(D, ReductionIdRange,
11907 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000011908 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011909 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011910 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011911 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
11912 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011913 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011914 return RD.Vars.empty();
11915}
Alexey Bataevc5e02582014-06-16 07:08:35 +000011916
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011917OMPClause *Sema::ActOnOpenMPReductionClause(
11918 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11919 SourceLocation ColonLoc, SourceLocation EndLoc,
11920 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11921 ArrayRef<Expr *> UnresolvedReductions) {
11922 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011923 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011924 StartLoc, LParenLoc, ColonLoc, EndLoc,
11925 ReductionIdScopeSpec, ReductionId,
11926 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011927 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000011928
Alexey Bataevc5e02582014-06-16 07:08:35 +000011929 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011930 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11931 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11932 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11933 buildPreInits(Context, RD.ExprCaptures),
11934 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000011935}
11936
Alexey Bataev169d96a2017-07-18 20:17:46 +000011937OMPClause *Sema::ActOnOpenMPTaskReductionClause(
11938 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11939 SourceLocation ColonLoc, SourceLocation EndLoc,
11940 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11941 ArrayRef<Expr *> UnresolvedReductions) {
11942 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011943 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
11944 StartLoc, LParenLoc, ColonLoc, EndLoc,
11945 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011946 UnresolvedReductions, RD))
11947 return nullptr;
11948
11949 return OMPTaskReductionClause::Create(
11950 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11951 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11952 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11953 buildPreInits(Context, RD.ExprCaptures),
11954 buildPostUpdate(*this, RD.ExprPostUpdates));
11955}
11956
Alexey Bataevfa312f32017-07-21 18:48:21 +000011957OMPClause *Sema::ActOnOpenMPInReductionClause(
11958 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11959 SourceLocation ColonLoc, SourceLocation EndLoc,
11960 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11961 ArrayRef<Expr *> UnresolvedReductions) {
11962 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011963 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011964 StartLoc, LParenLoc, ColonLoc, EndLoc,
11965 ReductionIdScopeSpec, ReductionId,
11966 UnresolvedReductions, RD))
11967 return nullptr;
11968
11969 return OMPInReductionClause::Create(
11970 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11971 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000011972 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011973 buildPreInits(Context, RD.ExprCaptures),
11974 buildPostUpdate(*this, RD.ExprPostUpdates));
11975}
11976
Alexey Bataevecba70f2016-04-12 11:02:11 +000011977bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11978 SourceLocation LinLoc) {
11979 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
11980 LinKind == OMPC_LINEAR_unknown) {
11981 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
11982 return true;
11983 }
11984 return false;
11985}
11986
Alexey Bataeve3727102018-04-18 15:57:46 +000011987bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000011988 OpenMPLinearClauseKind LinKind,
11989 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011990 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000011991 // A variable must not have an incomplete type or a reference type.
11992 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
11993 return true;
11994 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
11995 !Type->isReferenceType()) {
11996 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
11997 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
11998 return true;
11999 }
12000 Type = Type.getNonReferenceType();
12001
Joel E. Dennybae586f2019-01-04 22:12:13 +000012002 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12003 // A variable that is privatized must not have a const-qualified type
12004 // unless it is of class type with a mutable member. This restriction does
12005 // not apply to the firstprivate clause.
12006 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000012007 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012008
12009 // A list item must be of integral or pointer type.
12010 Type = Type.getUnqualifiedType().getCanonicalType();
12011 const auto *Ty = Type.getTypePtrOrNull();
12012 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
12013 !Ty->isPointerType())) {
12014 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
12015 if (D) {
12016 bool IsDecl =
12017 !VD ||
12018 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12019 Diag(D->getLocation(),
12020 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12021 << D;
12022 }
12023 return true;
12024 }
12025 return false;
12026}
12027
Alexey Bataev182227b2015-08-20 10:54:39 +000012028OMPClause *Sema::ActOnOpenMPLinearClause(
12029 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
12030 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
12031 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012032 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012033 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000012034 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000012035 SmallVector<Decl *, 4> ExprCaptures;
12036 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012037 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000012038 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000012039 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012040 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012041 SourceLocation ELoc;
12042 SourceRange ERange;
12043 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012044 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012045 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012046 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012047 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012048 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000012049 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000012050 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012051 ValueDecl *D = Res.first;
12052 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000012053 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000012054
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012055 QualType Type = D->getType();
12056 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000012057
12058 // OpenMP [2.14.3.7, linear clause]
12059 // A list-item cannot appear in more than one linear clause.
12060 // A list-item that appears in a linear clause cannot appear in any
12061 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012062 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000012063 if (DVar.RefExpr) {
12064 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12065 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000012066 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000012067 continue;
12068 }
12069
Alexey Bataevecba70f2016-04-12 11:02:11 +000012070 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000012071 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012072 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000012073
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012074 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000012075 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012076 buildVarDecl(*this, ELoc, Type, D->getName(),
12077 D->hasAttrs() ? &D->getAttrs() : nullptr,
12078 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012079 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012080 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012081 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012082 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012083 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012084 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012085 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012086 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012087 ExprCaptures.push_back(Ref->getDecl());
12088 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
12089 ExprResult RefRes = DefaultLvalueConversion(Ref);
12090 if (!RefRes.isUsable())
12091 continue;
12092 ExprResult PostUpdateRes =
12093 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
12094 SimpleRefExpr, RefRes.get());
12095 if (!PostUpdateRes.isUsable())
12096 continue;
12097 ExprPostUpdates.push_back(
12098 IgnoredValueConversions(PostUpdateRes.get()).get());
12099 }
12100 }
12101 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012102 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012103 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012104 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012105 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012106 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012107 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012108 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012109
12110 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012111 Vars.push_back((VD || CurContext->isDependentContext())
12112 ? RefExpr->IgnoreParens()
12113 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012114 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000012115 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000012116 }
12117
12118 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012119 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012120
12121 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000012122 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012123 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
12124 !Step->isInstantiationDependent() &&
12125 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012126 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000012127 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000012128 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012129 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012130 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000012131
Alexander Musman3276a272015-03-21 10:12:56 +000012132 // Build var to save the step value.
12133 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012134 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000012135 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012136 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012137 ExprResult CalcStep =
12138 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012139 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012140
Alexander Musman8dba6642014-04-22 13:09:42 +000012141 // Warn about zero linear step (it would be probably better specified as
12142 // making corresponding variables 'const').
12143 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000012144 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
12145 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000012146 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
12147 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000012148 if (!IsConstant && CalcStep.isUsable()) {
12149 // Calculate the step beforehand instead of doing this on each iteration.
12150 // (This is not used if the number of iterations may be kfold-ed).
12151 CalcStepExpr = CalcStep.get();
12152 }
Alexander Musman8dba6642014-04-22 13:09:42 +000012153 }
12154
Alexey Bataev182227b2015-08-20 10:54:39 +000012155 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
12156 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012157 StepExpr, CalcStepExpr,
12158 buildPreInits(Context, ExprCaptures),
12159 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000012160}
12161
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012162static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
12163 Expr *NumIterations, Sema &SemaRef,
12164 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000012165 // Walk the vars and build update/final expressions for the CodeGen.
12166 SmallVector<Expr *, 8> Updates;
12167 SmallVector<Expr *, 8> Finals;
12168 Expr *Step = Clause.getStep();
12169 Expr *CalcStep = Clause.getCalcStep();
12170 // OpenMP [2.14.3.7, linear clause]
12171 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000012172 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000012173 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012174 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000012175 Step = cast<BinaryOperator>(CalcStep)->getLHS();
12176 bool HasErrors = false;
12177 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012178 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000012179 OpenMPLinearClauseKind LinKind = Clause.getModifier();
12180 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012181 SourceLocation ELoc;
12182 SourceRange ERange;
12183 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012184 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012185 ValueDecl *D = Res.first;
12186 if (Res.second || !D) {
12187 Updates.push_back(nullptr);
12188 Finals.push_back(nullptr);
12189 HasErrors = true;
12190 continue;
12191 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012192 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000012193 // OpenMP [2.15.11, distribute simd Construct]
12194 // A list item may not appear in a linear clause, unless it is the loop
12195 // iteration variable.
12196 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
12197 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
12198 SemaRef.Diag(ELoc,
12199 diag::err_omp_linear_distribute_var_non_loop_iteration);
12200 Updates.push_back(nullptr);
12201 Finals.push_back(nullptr);
12202 HasErrors = true;
12203 continue;
12204 }
Alexander Musman3276a272015-03-21 10:12:56 +000012205 Expr *InitExpr = *CurInit;
12206
12207 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000012208 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012209 Expr *CapturedRef;
12210 if (LinKind == OMPC_LINEAR_uval)
12211 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
12212 else
12213 CapturedRef =
12214 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
12215 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
12216 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000012217
12218 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012219 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000012220 if (!Info.first)
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012221 Update =
Alexey Bataeve3727102018-04-18 15:57:46 +000012222 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012223 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012224 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012225 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012226 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012227 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012228
12229 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012230 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000012231 if (!Info.first)
12232 Final =
12233 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
12234 InitExpr, NumIterations, Step, /*Subtract=*/false);
12235 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012236 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012237 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012238 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012239
Alexander Musman3276a272015-03-21 10:12:56 +000012240 if (!Update.isUsable() || !Final.isUsable()) {
12241 Updates.push_back(nullptr);
12242 Finals.push_back(nullptr);
12243 HasErrors = true;
12244 } else {
12245 Updates.push_back(Update.get());
12246 Finals.push_back(Final.get());
12247 }
Richard Trieucc3949d2016-02-18 22:34:54 +000012248 ++CurInit;
12249 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000012250 }
12251 Clause.setUpdates(Updates);
12252 Clause.setFinals(Finals);
12253 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000012254}
12255
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012256OMPClause *Sema::ActOnOpenMPAlignedClause(
12257 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
12258 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012259 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012260 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000012261 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12262 SourceLocation ELoc;
12263 SourceRange ERange;
12264 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012265 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000012266 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012267 // It will be analyzed later.
12268 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012269 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000012270 ValueDecl *D = Res.first;
12271 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012272 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012273
Alexey Bataev1efd1662016-03-29 10:59:56 +000012274 QualType QType = D->getType();
12275 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012276
12277 // OpenMP [2.8.1, simd construct, Restrictions]
12278 // The type of list items appearing in the aligned clause must be
12279 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012280 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012281 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000012282 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012283 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012284 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012285 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000012286 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012287 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000012288 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012289 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012290 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012291 continue;
12292 }
12293
12294 // OpenMP [2.8.1, simd construct, Restrictions]
12295 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012296 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000012297 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012298 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
12299 << getOpenMPClauseName(OMPC_aligned);
12300 continue;
12301 }
12302
Alexey Bataev1efd1662016-03-29 10:59:56 +000012303 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012304 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000012305 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12306 Vars.push_back(DefaultFunctionArrayConversion(
12307 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
12308 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012309 }
12310
12311 // OpenMP [2.8.1, simd construct, Description]
12312 // The parameter of the aligned clause, alignment, must be a constant
12313 // positive integer expression.
12314 // If no optional parameter is specified, implementation-defined default
12315 // alignments for SIMD instructions on the target platforms are assumed.
12316 if (Alignment != nullptr) {
12317 ExprResult AlignResult =
12318 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
12319 if (AlignResult.isInvalid())
12320 return nullptr;
12321 Alignment = AlignResult.get();
12322 }
12323 if (Vars.empty())
12324 return nullptr;
12325
12326 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
12327 EndLoc, Vars, Alignment);
12328}
12329
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012330OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12331 SourceLocation StartLoc,
12332 SourceLocation LParenLoc,
12333 SourceLocation EndLoc) {
12334 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012335 SmallVector<Expr *, 8> SrcExprs;
12336 SmallVector<Expr *, 8> DstExprs;
12337 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012338 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012339 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
12340 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012341 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012342 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012343 SrcExprs.push_back(nullptr);
12344 DstExprs.push_back(nullptr);
12345 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012346 continue;
12347 }
12348
Alexey Bataeved09d242014-05-28 05:53:51 +000012349 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012350 // OpenMP [2.1, C/C++]
12351 // A list item is a variable name.
12352 // OpenMP [2.14.4.1, Restrictions, p.1]
12353 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000012354 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012355 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012356 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
12357 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012358 continue;
12359 }
12360
12361 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000012362 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012363
12364 QualType Type = VD->getType();
12365 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
12366 // It will be analyzed later.
12367 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012368 SrcExprs.push_back(nullptr);
12369 DstExprs.push_back(nullptr);
12370 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012371 continue;
12372 }
12373
12374 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
12375 // A list item that appears in a copyin clause must be threadprivate.
12376 if (!DSAStack->isThreadPrivate(VD)) {
12377 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000012378 << getOpenMPClauseName(OMPC_copyin)
12379 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012380 continue;
12381 }
12382
12383 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12384 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000012385 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012386 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012387 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12388 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012389 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012390 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012391 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012392 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000012393 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012394 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012395 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012396 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012397 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012398 // For arrays generate assignment operation for single element and replace
12399 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012400 ExprResult AssignmentOp =
12401 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12402 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012403 if (AssignmentOp.isInvalid())
12404 continue;
12405 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012406 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012407 if (AssignmentOp.isInvalid())
12408 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012409
12410 DSAStack->addDSA(VD, DE, OMPC_copyin);
12411 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012412 SrcExprs.push_back(PseudoSrcExpr);
12413 DstExprs.push_back(PseudoDstExpr);
12414 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012415 }
12416
Alexey Bataeved09d242014-05-28 05:53:51 +000012417 if (Vars.empty())
12418 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012419
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012420 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12421 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012422}
12423
Alexey Bataevbae9a792014-06-27 10:37:06 +000012424OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12425 SourceLocation StartLoc,
12426 SourceLocation LParenLoc,
12427 SourceLocation EndLoc) {
12428 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000012429 SmallVector<Expr *, 8> SrcExprs;
12430 SmallVector<Expr *, 8> DstExprs;
12431 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012432 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012433 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12434 SourceLocation ELoc;
12435 SourceRange ERange;
12436 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012437 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000012438 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012439 // It will be analyzed later.
12440 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012441 SrcExprs.push_back(nullptr);
12442 DstExprs.push_back(nullptr);
12443 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012444 }
Alexey Bataeve122da12016-03-17 10:50:17 +000012445 ValueDecl *D = Res.first;
12446 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000012447 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012448
Alexey Bataeve122da12016-03-17 10:50:17 +000012449 QualType Type = D->getType();
12450 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012451
12452 // OpenMP [2.14.4.2, Restrictions, p.2]
12453 // A list item that appears in a copyprivate clause may not appear in a
12454 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000012455 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012456 DSAStackTy::DSAVarData DVar =
12457 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012458 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12459 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012460 Diag(ELoc, diag::err_omp_wrong_dsa)
12461 << getOpenMPClauseName(DVar.CKind)
12462 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012463 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012464 continue;
12465 }
12466
12467 // OpenMP [2.11.4.2, Restrictions, p.1]
12468 // All list items that appear in a copyprivate clause must be either
12469 // threadprivate or private in the enclosing context.
12470 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012471 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012472 if (DVar.CKind == OMPC_shared) {
12473 Diag(ELoc, diag::err_omp_required_access)
12474 << getOpenMPClauseName(OMPC_copyprivate)
12475 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000012476 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012477 continue;
12478 }
12479 }
12480 }
12481
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012482 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012483 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012484 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012485 << getOpenMPClauseName(OMPC_copyprivate) << Type
12486 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012487 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000012488 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012489 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000012490 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012491 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000012492 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012493 continue;
12494 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012495
Alexey Bataevbae9a792014-06-27 10:37:06 +000012496 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12497 // A variable of class type (or array thereof) that appears in a
12498 // copyin clause requires an accessible, unambiguous copy assignment
12499 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012500 Type = Context.getBaseElementType(Type.getNonReferenceType())
12501 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012502 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012503 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000012504 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012505 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
12506 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012507 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000012508 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012509 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
12510 ExprResult AssignmentOp = BuildBinOp(
12511 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012512 if (AssignmentOp.isInvalid())
12513 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012514 AssignmentOp =
12515 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012516 if (AssignmentOp.isInvalid())
12517 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012518
12519 // No need to mark vars as copyprivate, they are already threadprivate or
12520 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000012521 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000012522 Vars.push_back(
12523 VD ? RefExpr->IgnoreParens()
12524 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000012525 SrcExprs.push_back(PseudoSrcExpr);
12526 DstExprs.push_back(PseudoDstExpr);
12527 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000012528 }
12529
12530 if (Vars.empty())
12531 return nullptr;
12532
Alexey Bataeva63048e2015-03-23 06:18:07 +000012533 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12534 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012535}
12536
Alexey Bataev6125da92014-07-21 11:26:11 +000012537OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12538 SourceLocation StartLoc,
12539 SourceLocation LParenLoc,
12540 SourceLocation EndLoc) {
12541 if (VarList.empty())
12542 return nullptr;
12543
12544 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
12545}
Alexey Bataevdea47612014-07-23 07:46:59 +000012546
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012547OMPClause *
12548Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12549 SourceLocation DepLoc, SourceLocation ColonLoc,
12550 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12551 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012552 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012553 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012554 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012555 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000012556 return nullptr;
12557 }
12558 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012559 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12560 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000012561 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012562 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012563 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12564 /*Last=*/OMPC_DEPEND_unknown, Except)
12565 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012566 return nullptr;
12567 }
12568 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000012569 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012570 llvm::APSInt DepCounter(/*BitWidth=*/32);
12571 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000012572 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12573 if (const Expr *OrderedCountExpr =
12574 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012575 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
12576 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012577 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012578 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012579 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000012580 assert(RefExpr && "NULL expr in OpenMP shared clause.");
12581 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12582 // It will be analyzed later.
12583 Vars.push_back(RefExpr);
12584 continue;
12585 }
12586
12587 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000012588 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000012589 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000012590 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012591 DepCounter >= TotalDepCount) {
12592 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
12593 continue;
12594 }
12595 ++DepCounter;
12596 // OpenMP [2.13.9, Summary]
12597 // depend(dependence-type : vec), where dependence-type is:
12598 // 'sink' and where vec is the iteration vector, which has the form:
12599 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
12600 // where n is the value specified by the ordered clause in the loop
12601 // directive, xi denotes the loop iteration variable of the i-th nested
12602 // loop associated with the loop directive, and di is a constant
12603 // non-negative integer.
12604 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012605 // It will be analyzed later.
12606 Vars.push_back(RefExpr);
12607 continue;
12608 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012609 SimpleExpr = SimpleExpr->IgnoreImplicit();
12610 OverloadedOperatorKind OOK = OO_None;
12611 SourceLocation OOLoc;
12612 Expr *LHS = SimpleExpr;
12613 Expr *RHS = nullptr;
12614 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
12615 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
12616 OOLoc = BO->getOperatorLoc();
12617 LHS = BO->getLHS()->IgnoreParenImpCasts();
12618 RHS = BO->getRHS()->IgnoreParenImpCasts();
12619 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
12620 OOK = OCE->getOperator();
12621 OOLoc = OCE->getOperatorLoc();
12622 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12623 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
12624 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
12625 OOK = MCE->getMethodDecl()
12626 ->getNameInfo()
12627 .getName()
12628 .getCXXOverloadedOperator();
12629 OOLoc = MCE->getCallee()->getExprLoc();
12630 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
12631 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012632 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012633 SourceLocation ELoc;
12634 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000012635 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012636 if (Res.second) {
12637 // It will be analyzed later.
12638 Vars.push_back(RefExpr);
12639 }
12640 ValueDecl *D = Res.first;
12641 if (!D)
12642 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012643
Alexey Bataev17daedf2018-02-15 22:42:57 +000012644 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
12645 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
12646 continue;
12647 }
12648 if (RHS) {
12649 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
12650 RHS, OMPC_depend, /*StrictlyPositive=*/false);
12651 if (RHSRes.isInvalid())
12652 continue;
12653 }
12654 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012655 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012656 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012657 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000012658 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000012659 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000012660 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
12661 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000012662 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000012663 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000012664 continue;
12665 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012666 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012667 } else {
12668 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12669 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12670 (ASE &&
12671 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12672 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12673 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12674 << RefExpr->getSourceRange();
12675 continue;
12676 }
12677 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12678 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12679 ExprResult Res =
12680 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12681 getDiagnostics().setSuppressAllDiagnostics(Suppress);
12682 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12683 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12684 << RefExpr->getSourceRange();
12685 continue;
12686 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012687 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012688 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012689 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012690
12691 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
12692 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012693 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012694 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
12695 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
12696 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
12697 }
12698 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
12699 Vars.empty())
12700 return nullptr;
12701
Alexey Bataev8b427062016-05-25 12:36:08 +000012702 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000012703 DepKind, DepLoc, ColonLoc, Vars,
12704 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000012705 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
12706 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000012707 DSAStack->addDoacrossDependClause(C, OpsOffs);
12708 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012709}
Michael Wonge710d542015-08-07 16:16:36 +000012710
12711OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
12712 SourceLocation LParenLoc,
12713 SourceLocation EndLoc) {
12714 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012715 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000012716
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012717 // OpenMP [2.9.1, Restrictions]
12718 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000012719 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000012720 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012721 return nullptr;
12722
Alexey Bataev931e19b2017-10-02 16:32:39 +000012723 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012724 OpenMPDirectiveKind CaptureRegion =
12725 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
12726 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012727 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012728 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012729 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12730 HelperValStmt = buildPreInits(Context, Captures);
12731 }
12732
Alexey Bataev8451efa2018-01-15 19:06:12 +000012733 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
12734 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000012735}
Kelvin Li0bff7af2015-11-23 05:32:03 +000012736
Alexey Bataeve3727102018-04-18 15:57:46 +000012737static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000012738 DSAStackTy *Stack, QualType QTy,
12739 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000012740 NamedDecl *ND;
12741 if (QTy->isIncompleteType(&ND)) {
12742 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
12743 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012744 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000012745 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
12746 !QTy.isTrivialType(SemaRef.Context))
12747 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012748 return true;
12749}
12750
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012751/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012752/// (array section or array subscript) does NOT specify the whole size of the
12753/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012754static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012755 const Expr *E,
12756 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012757 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012758
12759 // If this is an array subscript, it refers to the whole size if the size of
12760 // the dimension is constant and equals 1. Also, an array section assumes the
12761 // format of an array subscript if no colon is used.
12762 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012763 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012764 return ATy->getSize().getSExtValue() != 1;
12765 // Size can't be evaluated statically.
12766 return false;
12767 }
12768
12769 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012770 const Expr *LowerBound = OASE->getLowerBound();
12771 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012772
12773 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000012774 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012775 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000012776 Expr::EvalResult Result;
12777 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012778 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000012779
12780 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012781 if (ConstLowerBound.getSExtValue())
12782 return true;
12783 }
12784
12785 // If we don't have a length we covering the whole dimension.
12786 if (!Length)
12787 return false;
12788
12789 // If the base is a pointer, we don't have a way to get the size of the
12790 // pointee.
12791 if (BaseQTy->isPointerType())
12792 return false;
12793
12794 // We can only check if the length is the same as the size of the dimension
12795 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000012796 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012797 if (!CATy)
12798 return false;
12799
Fangrui Song407659a2018-11-30 23:41:18 +000012800 Expr::EvalResult Result;
12801 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012802 return false; // Can't get the integer value as a constant.
12803
Fangrui Song407659a2018-11-30 23:41:18 +000012804 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012805 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
12806}
12807
12808// Return true if it can be proven that the provided array expression (array
12809// section or array subscript) does NOT specify a single element of the array
12810// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012811static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000012812 const Expr *E,
12813 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012814 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012815
12816 // An array subscript always refer to a single element. Also, an array section
12817 // assumes the format of an array subscript if no colon is used.
12818 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
12819 return false;
12820
12821 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012822 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012823
12824 // If we don't have a length we have to check if the array has unitary size
12825 // for this dimension. Also, we should always expect a length if the base type
12826 // is pointer.
12827 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012828 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012829 return ATy->getSize().getSExtValue() != 1;
12830 // We cannot assume anything.
12831 return false;
12832 }
12833
12834 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000012835 Expr::EvalResult Result;
12836 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012837 return false; // Can't get the integer value as a constant.
12838
Fangrui Song407659a2018-11-30 23:41:18 +000012839 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012840 return ConstLength.getSExtValue() != 1;
12841}
12842
Samuel Antao661c0902016-05-26 17:39:58 +000012843// Return the expression of the base of the mappable expression or null if it
12844// cannot be determined and do all the necessary checks to see if the expression
12845// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000012846// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000012847static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000012848 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000012849 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012850 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012851 SourceLocation ELoc = E->getExprLoc();
12852 SourceRange ERange = E->getSourceRange();
12853
12854 // The base of elements of list in a map clause have to be either:
12855 // - a reference to variable or field.
12856 // - a member expression.
12857 // - an array expression.
12858 //
12859 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
12860 // reference to 'r'.
12861 //
12862 // If we have:
12863 //
12864 // struct SS {
12865 // Bla S;
12866 // foo() {
12867 // #pragma omp target map (S.Arr[:12]);
12868 // }
12869 // }
12870 //
12871 // We want to retrieve the member expression 'this->S';
12872
Alexey Bataeve3727102018-04-18 15:57:46 +000012873 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012874
Samuel Antao5de996e2016-01-22 20:21:36 +000012875 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
12876 // If a list item is an array section, it must specify contiguous storage.
12877 //
12878 // For this restriction it is sufficient that we make sure only references
12879 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012880 // exist except in the rightmost expression (unless they cover the whole
12881 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000012882 //
12883 // r.ArrS[3:5].Arr[6:7]
12884 //
12885 // r.ArrS[3:5].x
12886 //
12887 // but these would be valid:
12888 // r.ArrS[3].Arr[6:7]
12889 //
12890 // r.ArrS[3].x
12891
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012892 bool AllowUnitySizeArraySection = true;
12893 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012894
Dmitry Polukhin644a9252016-03-11 07:58:34 +000012895 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012896 E = E->IgnoreParenImpCasts();
12897
12898 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
12899 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000012900 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012901
12902 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012903
12904 // If we got a reference to a declaration, we should not expect any array
12905 // section before that.
12906 AllowUnitySizeArraySection = false;
12907 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012908
12909 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012910 CurComponents.emplace_back(CurE, CurE->getDecl());
12911 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012912 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000012913
12914 if (isa<CXXThisExpr>(BaseE))
12915 // We found a base expression: this->Val.
12916 RelevantExpr = CurE;
12917 else
12918 E = BaseE;
12919
12920 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012921 if (!NoDiagnose) {
12922 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
12923 << CurE->getSourceRange();
12924 return nullptr;
12925 }
12926 if (RelevantExpr)
12927 return nullptr;
12928 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012929 }
12930
12931 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
12932
12933 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
12934 // A bit-field cannot appear in a map clause.
12935 //
12936 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012937 if (!NoDiagnose) {
12938 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
12939 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
12940 return nullptr;
12941 }
12942 if (RelevantExpr)
12943 return nullptr;
12944 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012945 }
12946
12947 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12948 // If the type of a list item is a reference to a type T then the type
12949 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012950 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012951
12952 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
12953 // A list item cannot be a variable that is a member of a structure with
12954 // a union type.
12955 //
Alexey Bataeve3727102018-04-18 15:57:46 +000012956 if (CurType->isUnionType()) {
12957 if (!NoDiagnose) {
12958 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
12959 << CurE->getSourceRange();
12960 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012961 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012962 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012963 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012964
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012965 // If we got a member expression, we should not expect any array section
12966 // before that:
12967 //
12968 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
12969 // If a list item is an element of a structure, only the rightmost symbol
12970 // of the variable reference can be an array section.
12971 //
12972 AllowUnitySizeArraySection = false;
12973 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012974
12975 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012976 CurComponents.emplace_back(CurE, FD);
12977 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012978 E = CurE->getBase()->IgnoreParenImpCasts();
12979
12980 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012981 if (!NoDiagnose) {
12982 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12983 << 0 << CurE->getSourceRange();
12984 return nullptr;
12985 }
12986 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012987 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012988
12989 // If we got an array subscript that express the whole dimension we
12990 // can have any array expressions before. If it only expressing part of
12991 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000012992 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012993 E->getType()))
12994 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012995
Patrick Lystere13b1e32019-01-02 19:28:48 +000012996 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12997 Expr::EvalResult Result;
12998 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
12999 if (!Result.Val.getInt().isNullValue()) {
13000 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13001 diag::err_omp_invalid_map_this_expr);
13002 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13003 diag::note_omp_invalid_subscript_on_this_ptr_map);
13004 }
13005 }
13006 RelevantExpr = TE;
13007 }
13008
Samuel Antao90927002016-04-26 14:54:23 +000013009 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013010 CurComponents.emplace_back(CurE, nullptr);
13011 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013012 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000013013 E = CurE->getBase()->IgnoreParenImpCasts();
13014
Alexey Bataev27041fa2017-12-05 15:22:49 +000013015 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013016 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13017
Samuel Antao5de996e2016-01-22 20:21:36 +000013018 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13019 // If the type of a list item is a reference to a type T then the type
13020 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000013021 if (CurType->isReferenceType())
13022 CurType = CurType->getPointeeType();
13023
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013024 bool IsPointer = CurType->isAnyPointerType();
13025
13026 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013027 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13028 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013029 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013030 }
13031
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013032 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000013033 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013034 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000013035 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013036
Samuel Antaodab51bb2016-07-18 23:22:11 +000013037 if (AllowWholeSizeArraySection) {
13038 // Any array section is currently allowed. Allowing a whole size array
13039 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013040 //
13041 // If this array section refers to the whole dimension we can still
13042 // accept other array sections before this one, except if the base is a
13043 // pointer. Otherwise, only unitary sections are accepted.
13044 if (NotWhole || IsPointer)
13045 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000013046 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013047 // A unity or whole array section is not allowed and that is not
13048 // compatible with the properties of the current array section.
13049 SemaRef.Diag(
13050 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
13051 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013052 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013053 }
Samuel Antao90927002016-04-26 14:54:23 +000013054
Patrick Lystere13b1e32019-01-02 19:28:48 +000013055 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13056 Expr::EvalResult ResultR;
13057 Expr::EvalResult ResultL;
13058 if (CurE->getLength()->EvaluateAsInt(ResultR,
13059 SemaRef.getASTContext())) {
13060 if (!ResultR.Val.getInt().isOneValue()) {
13061 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13062 diag::err_omp_invalid_map_this_expr);
13063 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13064 diag::note_omp_invalid_length_on_this_ptr_mapping);
13065 }
13066 }
13067 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
13068 ResultL, SemaRef.getASTContext())) {
13069 if (!ResultL.Val.getInt().isNullValue()) {
13070 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13071 diag::err_omp_invalid_map_this_expr);
13072 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13073 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
13074 }
13075 }
13076 RelevantExpr = TE;
13077 }
13078
Samuel Antao90927002016-04-26 14:54:23 +000013079 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013080 CurComponents.emplace_back(CurE, nullptr);
13081 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013082 if (!NoDiagnose) {
13083 // If nothing else worked, this is not a valid map clause expression.
13084 SemaRef.Diag(
13085 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
13086 << ERange;
13087 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000013088 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013089 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013090 }
13091
13092 return RelevantExpr;
13093}
13094
13095// Return true if expression E associated with value VD has conflicts with other
13096// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000013097static bool checkMapConflicts(
13098 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000013099 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000013100 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
13101 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013102 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000013103 SourceLocation ELoc = E->getExprLoc();
13104 SourceRange ERange = E->getSourceRange();
13105
13106 // In order to easily check the conflicts we need to match each component of
13107 // the expression under test with the components of the expressions that are
13108 // already in the stack.
13109
Samuel Antao5de996e2016-01-22 20:21:36 +000013110 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013111 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013112 "Map clause expression with unexpected base!");
13113
13114 // Variables to help detecting enclosing problems in data environment nests.
13115 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000013116 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013117
Samuel Antao90927002016-04-26 14:54:23 +000013118 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
13119 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000013120 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
13121 ERange, CKind, &EnclosingExpr,
13122 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
13123 StackComponents,
13124 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013125 assert(!StackComponents.empty() &&
13126 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013127 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013128 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000013129 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013130
Samuel Antao90927002016-04-26 14:54:23 +000013131 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000013132 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000013133
Samuel Antao5de996e2016-01-22 20:21:36 +000013134 // Expressions must start from the same base. Here we detect at which
13135 // point both expressions diverge from each other and see if we can
13136 // detect if the memory referred to both expressions is contiguous and
13137 // do not overlap.
13138 auto CI = CurComponents.rbegin();
13139 auto CE = CurComponents.rend();
13140 auto SI = StackComponents.rbegin();
13141 auto SE = StackComponents.rend();
13142 for (; CI != CE && SI != SE; ++CI, ++SI) {
13143
13144 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
13145 // At most one list item can be an array item derived from a given
13146 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000013147 if (CurrentRegionOnly &&
13148 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
13149 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
13150 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
13151 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
13152 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000013153 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000013154 << CI->getAssociatedExpression()->getSourceRange();
13155 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
13156 diag::note_used_here)
13157 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000013158 return true;
13159 }
13160
13161 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000013162 if (CI->getAssociatedExpression()->getStmtClass() !=
13163 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000013164 break;
13165
13166 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000013167 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000013168 break;
13169 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000013170 // Check if the extra components of the expressions in the enclosing
13171 // data environment are redundant for the current base declaration.
13172 // If they are, the maps completely overlap, which is legal.
13173 for (; SI != SE; ++SI) {
13174 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000013175 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000013176 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000013177 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013178 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000013179 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013180 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000013181 Type =
13182 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13183 }
13184 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013185 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000013186 SemaRef, SI->getAssociatedExpression(), Type))
13187 break;
13188 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013189
13190 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13191 // List items of map clauses in the same construct must not share
13192 // original storage.
13193 //
13194 // If the expressions are exactly the same or one is a subset of the
13195 // other, it means they are sharing storage.
13196 if (CI == CE && SI == SE) {
13197 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013198 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000013199 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013200 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013201 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013202 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13203 << ERange;
13204 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013205 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13206 << RE->getSourceRange();
13207 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013208 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013209 // If we find the same expression in the enclosing data environment,
13210 // that is legal.
13211 IsEnclosedByDataEnvironmentExpr = true;
13212 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000013213 }
13214
Samuel Antao90927002016-04-26 14:54:23 +000013215 QualType DerivedType =
13216 std::prev(CI)->getAssociatedDeclaration()->getType();
13217 SourceLocation DerivedLoc =
13218 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000013219
13220 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13221 // If the type of a list item is a reference to a type T then the type
13222 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000013223 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013224
13225 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
13226 // A variable for which the type is pointer and an array section
13227 // derived from that variable must not appear as list items of map
13228 // clauses of the same construct.
13229 //
13230 // Also, cover one of the cases in:
13231 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13232 // If any part of the original storage of a list item has corresponding
13233 // storage in the device data environment, all of the original storage
13234 // must have corresponding storage in the device data environment.
13235 //
13236 if (DerivedType->isAnyPointerType()) {
13237 if (CI == CE || SI == SE) {
13238 SemaRef.Diag(
13239 DerivedLoc,
13240 diag::err_omp_pointer_mapped_along_with_derived_section)
13241 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013242 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13243 << RE->getSourceRange();
13244 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013245 }
13246 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000013247 SI->getAssociatedExpression()->getStmtClass() ||
13248 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
13249 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013250 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000013251 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000013252 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013253 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13254 << RE->getSourceRange();
13255 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013256 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013257 }
13258
13259 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13260 // List items of map clauses in the same construct must not share
13261 // original storage.
13262 //
13263 // An expression is a subset of the other.
13264 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013265 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000013266 if (CI != CE || SI != SE) {
13267 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
13268 // a pointer.
13269 auto Begin =
13270 CI != CE ? CurComponents.begin() : StackComponents.begin();
13271 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
13272 auto It = Begin;
13273 while (It != End && !It->getAssociatedDeclaration())
13274 std::advance(It, 1);
13275 assert(It != End &&
13276 "Expected at least one component with the declaration.");
13277 if (It != Begin && It->getAssociatedDeclaration()
13278 ->getType()
13279 .getCanonicalType()
13280 ->isAnyPointerType()) {
13281 IsEnclosedByDataEnvironmentExpr = false;
13282 EnclosingExpr = nullptr;
13283 return false;
13284 }
13285 }
Samuel Antao661c0902016-05-26 17:39:58 +000013286 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013287 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013288 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013289 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13290 << ERange;
13291 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013292 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13293 << RE->getSourceRange();
13294 return true;
13295 }
13296
13297 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000013298 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000013299 if (!CurrentRegionOnly && SI != SE)
13300 EnclosingExpr = RE;
13301
13302 // The current expression is a subset of the expression in the data
13303 // environment.
13304 IsEnclosedByDataEnvironmentExpr |=
13305 (!CurrentRegionOnly && CI != CE && SI == SE);
13306
13307 return false;
13308 });
13309
13310 if (CurrentRegionOnly)
13311 return FoundError;
13312
13313 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13314 // If any part of the original storage of a list item has corresponding
13315 // storage in the device data environment, all of the original storage must
13316 // have corresponding storage in the device data environment.
13317 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
13318 // If a list item is an element of a structure, and a different element of
13319 // the structure has a corresponding list item in the device data environment
13320 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000013321 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000013322 // data environment prior to the task encountering the construct.
13323 //
13324 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
13325 SemaRef.Diag(ELoc,
13326 diag::err_omp_original_storage_is_shared_and_does_not_contain)
13327 << ERange;
13328 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
13329 << EnclosingExpr->getSourceRange();
13330 return true;
13331 }
13332
13333 return FoundError;
13334}
13335
Michael Kruse4304e9d2019-02-19 16:38:20 +000013336// Look up the user-defined mapper given the mapper name and mapped type, and
13337// build a reference to it.
13338ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
13339 CXXScopeSpec &MapperIdScopeSpec,
13340 const DeclarationNameInfo &MapperId,
13341 QualType Type, Expr *UnresolvedMapper) {
13342 if (MapperIdScopeSpec.isInvalid())
13343 return ExprError();
13344 // Find all user-defined mappers with the given MapperId.
13345 SmallVector<UnresolvedSet<8>, 4> Lookups;
13346 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
13347 Lookup.suppressDiagnostics();
13348 if (S) {
13349 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
13350 NamedDecl *D = Lookup.getRepresentativeDecl();
13351 while (S && !S->isDeclScope(D))
13352 S = S->getParent();
13353 if (S)
13354 S = S->getParent();
13355 Lookups.emplace_back();
13356 Lookups.back().append(Lookup.begin(), Lookup.end());
13357 Lookup.clear();
13358 }
13359 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
13360 // Extract the user-defined mappers with the given MapperId.
13361 Lookups.push_back(UnresolvedSet<8>());
13362 for (NamedDecl *D : ULE->decls()) {
13363 auto *DMD = cast<OMPDeclareMapperDecl>(D);
13364 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
13365 Lookups.back().addDecl(DMD);
13366 }
13367 }
13368 // Defer the lookup for dependent types. The results will be passed through
13369 // UnresolvedMapper on instantiation.
13370 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
13371 Type->isInstantiationDependentType() ||
13372 Type->containsUnexpandedParameterPack() ||
13373 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
13374 return !D->isInvalidDecl() &&
13375 (D->getType()->isDependentType() ||
13376 D->getType()->isInstantiationDependentType() ||
13377 D->getType()->containsUnexpandedParameterPack());
13378 })) {
13379 UnresolvedSet<8> URS;
13380 for (const UnresolvedSet<8> &Set : Lookups) {
13381 if (Set.empty())
13382 continue;
13383 URS.append(Set.begin(), Set.end());
13384 }
13385 return UnresolvedLookupExpr::Create(
13386 SemaRef.Context, /*NamingClass=*/nullptr,
13387 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
13388 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
13389 }
13390 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13391 // The type must be of struct, union or class type in C and C++
13392 if (!Type->isStructureOrClassType() && !Type->isUnionType())
13393 return ExprEmpty();
13394 SourceLocation Loc = MapperId.getLoc();
13395 // Perform argument dependent lookup.
13396 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
13397 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
13398 // Return the first user-defined mapper with the desired type.
13399 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13400 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
13401 if (!D->isInvalidDecl() &&
13402 SemaRef.Context.hasSameType(D->getType(), Type))
13403 return D;
13404 return nullptr;
13405 }))
13406 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13407 // Find the first user-defined mapper with a type derived from the desired
13408 // type.
13409 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13410 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
13411 if (!D->isInvalidDecl() &&
13412 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
13413 !Type.isMoreQualifiedThan(D->getType()))
13414 return D;
13415 return nullptr;
13416 })) {
13417 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13418 /*DetectVirtual=*/false);
13419 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
13420 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13421 VD->getType().getUnqualifiedType()))) {
13422 if (SemaRef.CheckBaseClassAccess(
13423 Loc, VD->getType(), Type, Paths.front(),
13424 /*DiagID=*/0) != Sema::AR_inaccessible) {
13425 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13426 }
13427 }
13428 }
13429 }
13430 // Report error if a mapper is specified, but cannot be found.
13431 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
13432 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
13433 << Type << MapperId.getName();
13434 return ExprError();
13435 }
13436 return ExprEmpty();
13437}
13438
Samuel Antao661c0902016-05-26 17:39:58 +000013439namespace {
13440// Utility struct that gathers all the related lists associated with a mappable
13441// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013442struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000013443 // The list of expressions.
13444 ArrayRef<Expr *> VarList;
13445 // The list of processed expressions.
13446 SmallVector<Expr *, 16> ProcessedVarList;
13447 // The mappble components for each expression.
13448 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
13449 // The base declaration of the variable.
13450 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000013451 // The reference to the user-defined mapper associated with every expression.
13452 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000013453
13454 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
13455 // We have a list of components and base declarations for each entry in the
13456 // variable list.
13457 VarComponents.reserve(VarList.size());
13458 VarBaseDeclarations.reserve(VarList.size());
13459 }
13460};
13461}
13462
13463// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000013464// \a CKind. In the check process the valid expressions, mappable expression
13465// components, variables, and user-defined mappers are extracted and used to
13466// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
13467// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
13468// and \a MapperId are expected to be valid if the clause kind is 'map'.
13469static void checkMappableExpressionList(
13470 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
13471 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013472 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
13473 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000013474 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000013475 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013476 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
13477 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000013478 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000013479
13480 // If the identifier of user-defined mapper is not specified, it is "default".
13481 // We do not change the actual name in this clause to distinguish whether a
13482 // mapper is specified explicitly, i.e., it is not explicitly specified when
13483 // MapperId.getName() is empty.
13484 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
13485 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
13486 MapperId.setName(DeclNames.getIdentifier(
13487 &SemaRef.getASTContext().Idents.get("default")));
13488 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013489
13490 // Iterators to find the current unresolved mapper expression.
13491 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
13492 bool UpdateUMIt = false;
13493 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013494
Samuel Antao90927002016-04-26 14:54:23 +000013495 // Keep track of the mappable components and base declarations in this clause.
13496 // Each entry in the list is going to have a list of components associated. We
13497 // record each set of the components so that we can build the clause later on.
13498 // In the end we should have the same amount of declarations and component
13499 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000013500
Alexey Bataeve3727102018-04-18 15:57:46 +000013501 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013502 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013503 SourceLocation ELoc = RE->getExprLoc();
13504
Michael Kruse4304e9d2019-02-19 16:38:20 +000013505 // Find the current unresolved mapper expression.
13506 if (UpdateUMIt && UMIt != UMEnd) {
13507 UMIt++;
13508 assert(
13509 UMIt != UMEnd &&
13510 "Expect the size of UnresolvedMappers to match with that of VarList");
13511 }
13512 UpdateUMIt = true;
13513 if (UMIt != UMEnd)
13514 UnresolvedMapper = *UMIt;
13515
Alexey Bataeve3727102018-04-18 15:57:46 +000013516 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013517
13518 if (VE->isValueDependent() || VE->isTypeDependent() ||
13519 VE->isInstantiationDependent() ||
13520 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000013521 // Try to find the associated user-defined mapper.
13522 ExprResult ER = buildUserDefinedMapperRef(
13523 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13524 VE->getType().getCanonicalType(), UnresolvedMapper);
13525 if (ER.isInvalid())
13526 continue;
13527 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000013528 // We can only analyze this information once the missing information is
13529 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000013530 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013531 continue;
13532 }
13533
Alexey Bataeve3727102018-04-18 15:57:46 +000013534 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013535
Samuel Antao5de996e2016-01-22 20:21:36 +000013536 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000013537 SemaRef.Diag(ELoc,
13538 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000013539 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013540 continue;
13541 }
13542
Samuel Antao90927002016-04-26 14:54:23 +000013543 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
13544 ValueDecl *CurDeclaration = nullptr;
13545
13546 // Obtain the array or member expression bases if required. Also, fill the
13547 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000013548 const Expr *BE = checkMapClauseExpressionBase(
13549 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000013550 if (!BE)
13551 continue;
13552
Samuel Antao90927002016-04-26 14:54:23 +000013553 assert(!CurComponents.empty() &&
13554 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013555
Patrick Lystere13b1e32019-01-02 19:28:48 +000013556 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
13557 // Add store "this" pointer to class in DSAStackTy for future checking
13558 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000013559 // Try to find the associated user-defined mapper.
13560 ExprResult ER = buildUserDefinedMapperRef(
13561 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13562 VE->getType().getCanonicalType(), UnresolvedMapper);
13563 if (ER.isInvalid())
13564 continue;
13565 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000013566 // Skip restriction checking for variable or field declarations
13567 MVLI.ProcessedVarList.push_back(RE);
13568 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13569 MVLI.VarComponents.back().append(CurComponents.begin(),
13570 CurComponents.end());
13571 MVLI.VarBaseDeclarations.push_back(nullptr);
13572 continue;
13573 }
13574
Samuel Antao90927002016-04-26 14:54:23 +000013575 // For the following checks, we rely on the base declaration which is
13576 // expected to be associated with the last component. The declaration is
13577 // expected to be a variable or a field (if 'this' is being mapped).
13578 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
13579 assert(CurDeclaration && "Null decl on map clause.");
13580 assert(
13581 CurDeclaration->isCanonicalDecl() &&
13582 "Expecting components to have associated only canonical declarations.");
13583
13584 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000013585 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000013586
13587 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000013588 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013589
13590 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000013591 // threadprivate variables cannot appear in a map clause.
13592 // OpenMP 4.5 [2.10.5, target update Construct]
13593 // threadprivate variables cannot appear in a from clause.
13594 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013595 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013596 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
13597 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000013598 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013599 continue;
13600 }
13601
Samuel Antao5de996e2016-01-22 20:21:36 +000013602 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13603 // A list item cannot appear in both a map clause and a data-sharing
13604 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000013605
Samuel Antao5de996e2016-01-22 20:21:36 +000013606 // Check conflicts with other map clause expressions. We check the conflicts
13607 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000013608 // environment, because the restrictions are different. We only have to
13609 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000013610 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013611 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013612 break;
Samuel Antao661c0902016-05-26 17:39:58 +000013613 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013614 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013615 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013616 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013617
Samuel Antao661c0902016-05-26 17:39:58 +000013618 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000013619 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13620 // If the type of a list item is a reference to a type T then the type will
13621 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000013622 auto I = llvm::find_if(
13623 CurComponents,
13624 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
13625 return MC.getAssociatedDeclaration();
13626 });
13627 assert(I != CurComponents.end() && "Null decl on map clause.");
13628 QualType Type =
13629 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013630
Samuel Antao661c0902016-05-26 17:39:58 +000013631 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
13632 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000013633 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000013634 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013635 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000013636 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000013637 continue;
13638
Samuel Antao661c0902016-05-26 17:39:58 +000013639 if (CKind == OMPC_map) {
13640 // target enter data
13641 // OpenMP [2.10.2, Restrictions, p. 99]
13642 // A map-type must be specified in all map clauses and must be either
13643 // to or alloc.
13644 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
13645 if (DKind == OMPD_target_enter_data &&
13646 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
13647 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13648 << (IsMapTypeImplicit ? 1 : 0)
13649 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13650 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013651 continue;
13652 }
Samuel Antao661c0902016-05-26 17:39:58 +000013653
13654 // target exit_data
13655 // OpenMP [2.10.3, Restrictions, p. 102]
13656 // A map-type must be specified in all map clauses and must be either
13657 // from, release, or delete.
13658 if (DKind == OMPD_target_exit_data &&
13659 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
13660 MapType == OMPC_MAP_delete)) {
13661 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13662 << (IsMapTypeImplicit ? 1 : 0)
13663 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13664 << getOpenMPDirectiveName(DKind);
13665 continue;
13666 }
13667
13668 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13669 // A list item cannot appear in both a map clause and a data-sharing
13670 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000013671 if (VD && isOpenMPTargetExecutionDirective(DKind)) {
13672 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013673 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000013674 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000013675 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000013676 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000013677 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000013678 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000013679 continue;
13680 }
13681 }
Michael Kruse01f670d2019-02-22 22:29:42 +000013682 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013683
Michael Kruse01f670d2019-02-22 22:29:42 +000013684 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000013685 ExprResult ER = buildUserDefinedMapperRef(
13686 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13687 Type.getCanonicalType(), UnresolvedMapper);
13688 if (ER.isInvalid())
13689 continue;
13690 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013691
Samuel Antao90927002016-04-26 14:54:23 +000013692 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000013693 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000013694
13695 // Store the components in the stack so that they can be used to check
13696 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000013697 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
13698 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000013699
13700 // Save the components and declaration to create the clause. For purposes of
13701 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000013702 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000013703 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13704 MVLI.VarComponents.back().append(CurComponents.begin(),
13705 CurComponents.end());
13706 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
13707 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013708 }
Samuel Antao661c0902016-05-26 17:39:58 +000013709}
13710
Michael Kruse4304e9d2019-02-19 16:38:20 +000013711OMPClause *Sema::ActOnOpenMPMapClause(
13712 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13713 ArrayRef<SourceLocation> MapTypeModifiersLoc,
13714 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
13715 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
13716 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
13717 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
13718 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
13719 OMPC_MAP_MODIFIER_unknown,
13720 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000013721 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
13722
13723 // Process map-type-modifiers, flag errors for duplicate modifiers.
13724 unsigned Count = 0;
13725 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
13726 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
13727 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
13728 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
13729 continue;
13730 }
13731 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000013732 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000013733 Modifiers[Count] = MapTypeModifiers[I];
13734 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
13735 ++Count;
13736 }
13737
Michael Kruse4304e9d2019-02-19 16:38:20 +000013738 MappableVarListInfo MVLI(VarList);
13739 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013740 MapperIdScopeSpec, MapperId, UnresolvedMappers,
13741 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000013742
Samuel Antao5de996e2016-01-22 20:21:36 +000013743 // We need to produce a map clause even if we don't have variables so that
13744 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000013745 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
13746 MVLI.VarBaseDeclarations, MVLI.VarComponents,
13747 MVLI.UDMapperList, Modifiers, ModifiersLoc,
13748 MapperIdScopeSpec.getWithLocInContext(Context),
13749 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013750}
Kelvin Li099bb8c2015-11-24 20:50:12 +000013751
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013752QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
13753 TypeResult ParsedType) {
13754 assert(ParsedType.isUsable());
13755
13756 QualType ReductionType = GetTypeFromParser(ParsedType.get());
13757 if (ReductionType.isNull())
13758 return QualType();
13759
13760 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
13761 // A type name in a declare reduction directive cannot be a function type, an
13762 // array type, a reference type, or a type qualified with const, volatile or
13763 // restrict.
13764 if (ReductionType.hasQualifiers()) {
13765 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
13766 return QualType();
13767 }
13768
13769 if (ReductionType->isFunctionType()) {
13770 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
13771 return QualType();
13772 }
13773 if (ReductionType->isReferenceType()) {
13774 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
13775 return QualType();
13776 }
13777 if (ReductionType->isArrayType()) {
13778 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
13779 return QualType();
13780 }
13781 return ReductionType;
13782}
13783
13784Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
13785 Scope *S, DeclContext *DC, DeclarationName Name,
13786 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
13787 AccessSpecifier AS, Decl *PrevDeclInScope) {
13788 SmallVector<Decl *, 8> Decls;
13789 Decls.reserve(ReductionTypes.size());
13790
13791 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000013792 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013793 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
13794 // A reduction-identifier may not be re-declared in the current scope for the
13795 // same type or for a type that is compatible according to the base language
13796 // rules.
13797 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13798 OMPDeclareReductionDecl *PrevDRD = nullptr;
13799 bool InCompoundScope = true;
13800 if (S != nullptr) {
13801 // Find previous declaration with the same name not referenced in other
13802 // declarations.
13803 FunctionScopeInfo *ParentFn = getEnclosingFunction();
13804 InCompoundScope =
13805 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13806 LookupName(Lookup, S);
13807 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13808 /*AllowInlineNamespace=*/false);
13809 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000013810 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013811 while (Filter.hasNext()) {
13812 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
13813 if (InCompoundScope) {
13814 auto I = UsedAsPrevious.find(PrevDecl);
13815 if (I == UsedAsPrevious.end())
13816 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000013817 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013818 UsedAsPrevious[D] = true;
13819 }
13820 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13821 PrevDecl->getLocation();
13822 }
13823 Filter.done();
13824 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013825 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013826 if (!PrevData.second) {
13827 PrevDRD = PrevData.first;
13828 break;
13829 }
13830 }
13831 }
13832 } else if (PrevDeclInScope != nullptr) {
13833 auto *PrevDRDInScope = PrevDRD =
13834 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
13835 do {
13836 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
13837 PrevDRDInScope->getLocation();
13838 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
13839 } while (PrevDRDInScope != nullptr);
13840 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013841 for (const auto &TyData : ReductionTypes) {
13842 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013843 bool Invalid = false;
13844 if (I != PreviousRedeclTypes.end()) {
13845 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
13846 << TyData.first;
13847 Diag(I->second, diag::note_previous_definition);
13848 Invalid = true;
13849 }
13850 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
13851 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
13852 Name, TyData.first, PrevDRD);
13853 DC->addDecl(DRD);
13854 DRD->setAccess(AS);
13855 Decls.push_back(DRD);
13856 if (Invalid)
13857 DRD->setInvalidDecl();
13858 else
13859 PrevDRD = DRD;
13860 }
13861
13862 return DeclGroupPtrTy::make(
13863 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
13864}
13865
13866void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
13867 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13868
13869 // Enter new function scope.
13870 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013871 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013872 getCurFunction()->setHasOMPDeclareReductionCombiner();
13873
13874 if (S != nullptr)
13875 PushDeclContext(S, DRD);
13876 else
13877 CurContext = DRD;
13878
Faisal Valid143a0c2017-04-01 21:30:49 +000013879 PushExpressionEvaluationContext(
13880 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013881
13882 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013883 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
13884 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
13885 // uses semantics of argument handles by value, but it should be passed by
13886 // reference. C lang does not support references, so pass all parameters as
13887 // pointers.
13888 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013889 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013890 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013891 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
13892 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
13893 // uses semantics of argument handles by value, but it should be passed by
13894 // reference. C lang does not support references, so pass all parameters as
13895 // pointers.
13896 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013897 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013898 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
13899 if (S != nullptr) {
13900 PushOnScopeChains(OmpInParm, S);
13901 PushOnScopeChains(OmpOutParm, S);
13902 } else {
13903 DRD->addDecl(OmpInParm);
13904 DRD->addDecl(OmpOutParm);
13905 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013906 Expr *InE =
13907 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
13908 Expr *OutE =
13909 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
13910 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013911}
13912
13913void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
13914 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13915 DiscardCleanupsInEvaluationContext();
13916 PopExpressionEvaluationContext();
13917
13918 PopDeclContext();
13919 PopFunctionScopeInfo();
13920
13921 if (Combiner != nullptr)
13922 DRD->setCombiner(Combiner);
13923 else
13924 DRD->setInvalidDecl();
13925}
13926
Alexey Bataev070f43a2017-09-06 14:49:58 +000013927VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013928 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13929
13930 // Enter new function scope.
13931 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013932 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013933
13934 if (S != nullptr)
13935 PushDeclContext(S, DRD);
13936 else
13937 CurContext = DRD;
13938
Faisal Valid143a0c2017-04-01 21:30:49 +000013939 PushExpressionEvaluationContext(
13940 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013941
13942 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013943 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
13944 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
13945 // uses semantics of argument handles by value, but it should be passed by
13946 // reference. C lang does not support references, so pass all parameters as
13947 // pointers.
13948 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013949 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013950 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013951 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
13952 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
13953 // uses semantics of argument handles by value, but it should be passed by
13954 // reference. C lang does not support references, so pass all parameters as
13955 // pointers.
13956 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013957 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013958 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013959 if (S != nullptr) {
13960 PushOnScopeChains(OmpPrivParm, S);
13961 PushOnScopeChains(OmpOrigParm, S);
13962 } else {
13963 DRD->addDecl(OmpPrivParm);
13964 DRD->addDecl(OmpOrigParm);
13965 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013966 Expr *OrigE =
13967 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
13968 Expr *PrivE =
13969 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
13970 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000013971 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013972}
13973
Alexey Bataev070f43a2017-09-06 14:49:58 +000013974void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
13975 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013976 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13977 DiscardCleanupsInEvaluationContext();
13978 PopExpressionEvaluationContext();
13979
13980 PopDeclContext();
13981 PopFunctionScopeInfo();
13982
Alexey Bataev070f43a2017-09-06 14:49:58 +000013983 if (Initializer != nullptr) {
13984 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
13985 } else if (OmpPrivParm->hasInit()) {
13986 DRD->setInitializer(OmpPrivParm->getInit(),
13987 OmpPrivParm->isDirectInit()
13988 ? OMPDeclareReductionDecl::DirectInit
13989 : OMPDeclareReductionDecl::CopyInit);
13990 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013991 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000013992 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013993}
13994
13995Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
13996 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013997 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013998 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013999 if (S)
14000 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
14001 /*AddToContext=*/false);
14002 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014003 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014004 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014005 }
14006 return DeclReductions;
14007}
14008
Michael Kruse251e1482019-02-01 20:25:04 +000014009TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
14010 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14011 QualType T = TInfo->getType();
14012 if (D.isInvalidType())
14013 return true;
14014
14015 if (getLangOpts().CPlusPlus) {
14016 // Check that there are no default arguments (C++ only).
14017 CheckExtraCXXDefaultArguments(D);
14018 }
14019
14020 return CreateParsedType(T, TInfo);
14021}
14022
14023QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
14024 TypeResult ParsedType) {
14025 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
14026
14027 QualType MapperType = GetTypeFromParser(ParsedType.get());
14028 assert(!MapperType.isNull() && "Expect valid mapper type");
14029
14030 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14031 // The type must be of struct, union or class type in C and C++
14032 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
14033 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
14034 return QualType();
14035 }
14036 return MapperType;
14037}
14038
14039OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
14040 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
14041 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
14042 Decl *PrevDeclInScope) {
14043 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
14044 forRedeclarationInCurContext());
14045 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14046 // A mapper-identifier may not be redeclared in the current scope for the
14047 // same type or for a type that is compatible according to the base language
14048 // rules.
14049 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
14050 OMPDeclareMapperDecl *PrevDMD = nullptr;
14051 bool InCompoundScope = true;
14052 if (S != nullptr) {
14053 // Find previous declaration with the same name not referenced in other
14054 // declarations.
14055 FunctionScopeInfo *ParentFn = getEnclosingFunction();
14056 InCompoundScope =
14057 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
14058 LookupName(Lookup, S);
14059 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14060 /*AllowInlineNamespace=*/false);
14061 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
14062 LookupResult::Filter Filter = Lookup.makeFilter();
14063 while (Filter.hasNext()) {
14064 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
14065 if (InCompoundScope) {
14066 auto I = UsedAsPrevious.find(PrevDecl);
14067 if (I == UsedAsPrevious.end())
14068 UsedAsPrevious[PrevDecl] = false;
14069 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
14070 UsedAsPrevious[D] = true;
14071 }
14072 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14073 PrevDecl->getLocation();
14074 }
14075 Filter.done();
14076 if (InCompoundScope) {
14077 for (const auto &PrevData : UsedAsPrevious) {
14078 if (!PrevData.second) {
14079 PrevDMD = PrevData.first;
14080 break;
14081 }
14082 }
14083 }
14084 } else if (PrevDeclInScope) {
14085 auto *PrevDMDInScope = PrevDMD =
14086 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
14087 do {
14088 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
14089 PrevDMDInScope->getLocation();
14090 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
14091 } while (PrevDMDInScope != nullptr);
14092 }
14093 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
14094 bool Invalid = false;
14095 if (I != PreviousRedeclTypes.end()) {
14096 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
14097 << MapperType << Name;
14098 Diag(I->second, diag::note_previous_definition);
14099 Invalid = true;
14100 }
14101 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
14102 MapperType, VN, PrevDMD);
14103 DC->addDecl(DMD);
14104 DMD->setAccess(AS);
14105 if (Invalid)
14106 DMD->setInvalidDecl();
14107
14108 // Enter new function scope.
14109 PushFunctionScope();
14110 setFunctionHasBranchProtectedScope();
14111
14112 CurContext = DMD;
14113
14114 return DMD;
14115}
14116
14117void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
14118 Scope *S,
14119 QualType MapperType,
14120 SourceLocation StartLoc,
14121 DeclarationName VN) {
14122 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
14123 if (S)
14124 PushOnScopeChains(VD, S);
14125 else
14126 DMD->addDecl(VD);
14127 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
14128 DMD->setMapperVarRef(MapperVarRefExpr);
14129}
14130
14131Sema::DeclGroupPtrTy
14132Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
14133 ArrayRef<OMPClause *> ClauseList) {
14134 PopDeclContext();
14135 PopFunctionScopeInfo();
14136
14137 if (D) {
14138 if (S)
14139 PushOnScopeChains(D, S, /*AddToContext=*/false);
14140 D->CreateClauses(Context, ClauseList);
14141 }
14142
14143 return DeclGroupPtrTy::make(DeclGroupRef(D));
14144}
14145
David Majnemer9d168222016-08-05 17:44:54 +000014146OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000014147 SourceLocation StartLoc,
14148 SourceLocation LParenLoc,
14149 SourceLocation EndLoc) {
14150 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014151 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014152
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014153 // OpenMP [teams Constrcut, Restrictions]
14154 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014155 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000014156 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014157 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014158
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014159 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014160 OpenMPDirectiveKind CaptureRegion =
14161 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
14162 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014163 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014164 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014165 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14166 HelperValStmt = buildPreInits(Context, Captures);
14167 }
14168
14169 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
14170 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000014171}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014172
14173OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
14174 SourceLocation StartLoc,
14175 SourceLocation LParenLoc,
14176 SourceLocation EndLoc) {
14177 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014178 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014179
14180 // OpenMP [teams Constrcut, Restrictions]
14181 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014182 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000014183 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014184 return nullptr;
14185
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014186 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014187 OpenMPDirectiveKind CaptureRegion =
14188 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
14189 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014190 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014191 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014192 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14193 HelperValStmt = buildPreInits(Context, Captures);
14194 }
14195
14196 return new (Context) OMPThreadLimitClause(
14197 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014198}
Alexey Bataeva0569352015-12-01 10:17:31 +000014199
14200OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
14201 SourceLocation StartLoc,
14202 SourceLocation LParenLoc,
14203 SourceLocation EndLoc) {
14204 Expr *ValExpr = Priority;
14205
14206 // OpenMP [2.9.1, task Constrcut]
14207 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014208 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000014209 /*StrictlyPositive=*/false))
14210 return nullptr;
14211
14212 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14213}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014214
14215OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
14216 SourceLocation StartLoc,
14217 SourceLocation LParenLoc,
14218 SourceLocation EndLoc) {
14219 Expr *ValExpr = Grainsize;
14220
14221 // OpenMP [2.9.2, taskloop Constrcut]
14222 // The parameter of the grainsize clause must be a positive integer
14223 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014224 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014225 /*StrictlyPositive=*/true))
14226 return nullptr;
14227
14228 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14229}
Alexey Bataev382967a2015-12-08 12:06:20 +000014230
14231OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
14232 SourceLocation StartLoc,
14233 SourceLocation LParenLoc,
14234 SourceLocation EndLoc) {
14235 Expr *ValExpr = NumTasks;
14236
14237 // OpenMP [2.9.2, taskloop Constrcut]
14238 // The parameter of the num_tasks clause must be a positive integer
14239 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014240 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000014241 /*StrictlyPositive=*/true))
14242 return nullptr;
14243
14244 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14245}
14246
Alexey Bataev28c75412015-12-15 08:19:24 +000014247OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
14248 SourceLocation LParenLoc,
14249 SourceLocation EndLoc) {
14250 // OpenMP [2.13.2, critical construct, Description]
14251 // ... where hint-expression is an integer constant expression that evaluates
14252 // to a valid lock hint.
14253 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
14254 if (HintExpr.isInvalid())
14255 return nullptr;
14256 return new (Context)
14257 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
14258}
14259
Carlo Bertollib4adf552016-01-15 18:50:31 +000014260OMPClause *Sema::ActOnOpenMPDistScheduleClause(
14261 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14262 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
14263 SourceLocation EndLoc) {
14264 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
14265 std::string Values;
14266 Values += "'";
14267 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
14268 Values += "'";
14269 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14270 << Values << getOpenMPClauseName(OMPC_dist_schedule);
14271 return nullptr;
14272 }
14273 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000014274 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000014275 if (ChunkSize) {
14276 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14277 !ChunkSize->isInstantiationDependent() &&
14278 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014279 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000014280 ExprResult Val =
14281 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14282 if (Val.isInvalid())
14283 return nullptr;
14284
14285 ValExpr = Val.get();
14286
14287 // OpenMP [2.7.1, Restrictions]
14288 // chunk_size must be a loop invariant integer expression with a positive
14289 // value.
14290 llvm::APSInt Result;
14291 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
14292 if (Result.isSigned() && !Result.isStrictlyPositive()) {
14293 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14294 << "dist_schedule" << ChunkSize->getSourceRange();
14295 return nullptr;
14296 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000014297 } else if (getOpenMPCaptureRegionForClause(
14298 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
14299 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000014300 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014301 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014302 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000014303 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14304 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014305 }
14306 }
14307 }
14308
14309 return new (Context)
14310 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000014311 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014312}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014313
14314OMPClause *Sema::ActOnOpenMPDefaultmapClause(
14315 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
14316 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
14317 SourceLocation KindLoc, SourceLocation EndLoc) {
14318 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000014319 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014320 std::string Value;
14321 SourceLocation Loc;
14322 Value += "'";
14323 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
14324 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014325 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014326 Loc = MLoc;
14327 } else {
14328 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014329 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014330 Loc = KindLoc;
14331 }
14332 Value += "'";
14333 Diag(Loc, diag::err_omp_unexpected_clause_value)
14334 << Value << getOpenMPClauseName(OMPC_defaultmap);
14335 return nullptr;
14336 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000014337 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014338
14339 return new (Context)
14340 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
14341}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014342
14343bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
14344 DeclContext *CurLexicalContext = getCurLexicalContext();
14345 if (!CurLexicalContext->isFileContext() &&
14346 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000014347 !CurLexicalContext->isExternCXXContext() &&
14348 !isa<CXXRecordDecl>(CurLexicalContext) &&
14349 !isa<ClassTemplateDecl>(CurLexicalContext) &&
14350 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
14351 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014352 Diag(Loc, diag::err_omp_region_not_file_context);
14353 return false;
14354 }
Kelvin Libc38e632018-09-10 02:07:09 +000014355 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014356 return true;
14357}
14358
14359void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000014360 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014361 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000014362 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014363}
14364
David Majnemer9d168222016-08-05 17:44:54 +000014365void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
14366 CXXScopeSpec &ScopeSpec,
14367 const DeclarationNameInfo &Id,
14368 OMPDeclareTargetDeclAttr::MapTypeTy MT,
14369 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014370 LookupResult Lookup(*this, Id, LookupOrdinaryName);
14371 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
14372
14373 if (Lookup.isAmbiguous())
14374 return;
14375 Lookup.suppressDiagnostics();
14376
14377 if (!Lookup.isSingleResult()) {
14378 if (TypoCorrection Corrected =
14379 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
14380 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
14381 CTK_ErrorRecovery)) {
14382 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
14383 << Id.getName());
14384 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
14385 return;
14386 }
14387
14388 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
14389 return;
14390 }
14391
14392 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev30a78212018-09-11 13:59:10 +000014393 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
14394 isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014395 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
14396 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
Alexey Bataev30a78212018-09-11 13:59:10 +000014397 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14398 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
14399 cast<ValueDecl>(ND));
14400 if (!Res) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014401 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014402 ND->addAttr(A);
14403 if (ASTMutationListener *ML = Context.getASTMutationListener())
14404 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000014405 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Alexey Bataev30a78212018-09-11 13:59:10 +000014406 } else if (*Res != MT) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014407 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
14408 << Id.getName();
14409 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014410 } else {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014411 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataeve3727102018-04-18 15:57:46 +000014412 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014413}
14414
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014415static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
14416 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014417 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014418 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000014419 auto *VD = cast<VarDecl>(D);
14420 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
14421 return;
14422 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
14423 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014424}
14425
14426static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
14427 Sema &SemaRef, DSAStackTy *Stack,
14428 ValueDecl *VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014429 return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14430 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
14431 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014432}
14433
Kelvin Li1ce87c72017-12-12 20:08:12 +000014434void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
14435 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014436 if (!D || D->isInvalidDecl())
14437 return;
14438 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014439 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014440 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000014441 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000014442 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
14443 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000014444 return;
14445 // 2.10.6: threadprivate variable cannot appear in a declare target
14446 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014447 if (DSAStack->isThreadPrivate(VD)) {
14448 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000014449 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014450 return;
14451 }
14452 }
Alexey Bataev97b72212018-08-14 18:31:20 +000014453 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
14454 D = FTD->getTemplatedDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014455 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014456 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14457 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
14458 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000014459 assert(IdLoc.isValid() && "Source location is expected");
14460 Diag(IdLoc, diag::err_omp_function_in_link_clause);
14461 Diag(FD->getLocation(), diag::note_defined_here) << FD;
14462 return;
14463 }
14464 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014465 if (auto *VD = dyn_cast<ValueDecl>(D)) {
14466 // Problem if any with var declared with incomplete type will be reported
14467 // as normal, so no need to check it here.
14468 if ((E || !VD->getType()->isIncompleteType()) &&
14469 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
14470 return;
14471 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
14472 // Checking declaration inside declare target region.
14473 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
14474 isa<FunctionTemplateDecl>(D)) {
14475 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
14476 Context, OMPDeclareTargetDeclAttr::MT_To);
14477 D->addAttr(A);
14478 if (ASTMutationListener *ML = Context.getASTMutationListener())
14479 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
14480 }
14481 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014482 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014483 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014484 if (!E)
14485 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014486 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
14487}
Samuel Antao661c0902016-05-26 17:39:58 +000014488
14489OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000014490 CXXScopeSpec &MapperIdScopeSpec,
14491 DeclarationNameInfo &MapperId,
14492 const OMPVarListLocTy &Locs,
14493 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000014494 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014495 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
14496 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000014497 if (MVLI.ProcessedVarList.empty())
14498 return nullptr;
14499
Michael Kruse01f670d2019-02-22 22:29:42 +000014500 return OMPToClause::Create(
14501 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14502 MVLI.VarComponents, MVLI.UDMapperList,
14503 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000014504}
Samuel Antaoec172c62016-05-26 17:49:04 +000014505
14506OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000014507 CXXScopeSpec &MapperIdScopeSpec,
14508 DeclarationNameInfo &MapperId,
14509 const OMPVarListLocTy &Locs,
14510 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014511 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014512 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
14513 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000014514 if (MVLI.ProcessedVarList.empty())
14515 return nullptr;
14516
Michael Kruse0336c752019-02-25 20:34:15 +000014517 return OMPFromClause::Create(
14518 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14519 MVLI.VarComponents, MVLI.UDMapperList,
14520 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000014521}
Carlo Bertolli2404b172016-07-13 15:37:16 +000014522
14523OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014524 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000014525 MappableVarListInfo MVLI(VarList);
14526 SmallVector<Expr *, 8> PrivateCopies;
14527 SmallVector<Expr *, 8> Inits;
14528
Alexey Bataeve3727102018-04-18 15:57:46 +000014529 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014530 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
14531 SourceLocation ELoc;
14532 SourceRange ERange;
14533 Expr *SimpleRefExpr = RefExpr;
14534 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14535 if (Res.second) {
14536 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000014537 MVLI.ProcessedVarList.push_back(RefExpr);
14538 PrivateCopies.push_back(nullptr);
14539 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014540 }
14541 ValueDecl *D = Res.first;
14542 if (!D)
14543 continue;
14544
14545 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000014546 Type = Type.getNonReferenceType().getUnqualifiedType();
14547
14548 auto *VD = dyn_cast<VarDecl>(D);
14549
14550 // Item should be a pointer or reference to pointer.
14551 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014552 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
14553 << 0 << RefExpr->getSourceRange();
14554 continue;
14555 }
Samuel Antaocc10b852016-07-28 14:23:26 +000014556
14557 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014558 auto VDPrivate =
14559 buildVarDecl(*this, ELoc, Type, D->getName(),
14560 D->hasAttrs() ? &D->getAttrs() : nullptr,
14561 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000014562 if (VDPrivate->isInvalidDecl())
14563 continue;
14564
14565 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014566 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000014567 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
14568
14569 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000014570 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000014571 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000014572 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
14573 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000014574 AddInitializerToDecl(VDPrivate,
14575 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014576 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000014577
14578 // If required, build a capture to implement the privatization initialized
14579 // with the current list item value.
14580 DeclRefExpr *Ref = nullptr;
14581 if (!VD)
14582 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14583 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
14584 PrivateCopies.push_back(VDPrivateRefExpr);
14585 Inits.push_back(VDInitRefExpr);
14586
14587 // We need to add a data sharing attribute for this variable to make sure it
14588 // is correctly captured. A variable that shows up in a use_device_ptr has
14589 // similar properties of a first private variable.
14590 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
14591
14592 // Create a mappable component for the list item. List items in this clause
14593 // only need a component.
14594 MVLI.VarBaseDeclarations.push_back(D);
14595 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14596 MVLI.VarComponents.back().push_back(
14597 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000014598 }
14599
Samuel Antaocc10b852016-07-28 14:23:26 +000014600 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000014601 return nullptr;
14602
Samuel Antaocc10b852016-07-28 14:23:26 +000014603 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000014604 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
14605 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014606}
Carlo Bertolli70594e92016-07-13 17:16:49 +000014607
14608OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014609 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000014610 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000014611 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000014612 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000014613 SourceLocation ELoc;
14614 SourceRange ERange;
14615 Expr *SimpleRefExpr = RefExpr;
14616 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14617 if (Res.second) {
14618 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000014619 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014620 }
14621 ValueDecl *D = Res.first;
14622 if (!D)
14623 continue;
14624
14625 QualType Type = D->getType();
14626 // item should be a pointer or array or reference to pointer or array
14627 if (!Type.getNonReferenceType()->isPointerType() &&
14628 !Type.getNonReferenceType()->isArrayType()) {
14629 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
14630 << 0 << RefExpr->getSourceRange();
14631 continue;
14632 }
Samuel Antao6890b092016-07-28 14:25:09 +000014633
14634 // Check if the declaration in the clause does not show up in any data
14635 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000014636 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000014637 if (isOpenMPPrivate(DVar.CKind)) {
14638 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
14639 << getOpenMPClauseName(DVar.CKind)
14640 << getOpenMPClauseName(OMPC_is_device_ptr)
14641 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000014642 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000014643 continue;
14644 }
14645
Alexey Bataeve3727102018-04-18 15:57:46 +000014646 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000014647 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000014648 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000014649 [&ConflictExpr](
14650 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
14651 OpenMPClauseKind) -> bool {
14652 ConflictExpr = R.front().getAssociatedExpression();
14653 return true;
14654 })) {
14655 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
14656 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
14657 << ConflictExpr->getSourceRange();
14658 continue;
14659 }
14660
14661 // Store the components in the stack so that they can be used to check
14662 // against other clauses later on.
14663 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
14664 DSAStack->addMappableExpressionComponents(
14665 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
14666
14667 // Record the expression we've just processed.
14668 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
14669
14670 // Create a mappable component for the list item. List items in this clause
14671 // only need a component. We use a null declaration to signal fields in
14672 // 'this'.
14673 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
14674 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
14675 "Unexpected device pointer expression!");
14676 MVLI.VarBaseDeclarations.push_back(
14677 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
14678 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14679 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014680 }
14681
Samuel Antao6890b092016-07-28 14:25:09 +000014682 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000014683 return nullptr;
14684
Michael Kruse4304e9d2019-02-19 16:38:20 +000014685 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
14686 MVLI.VarBaseDeclarations,
14687 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014688}