blob: f541d75ce5e6942b759e6a8f180921b602bec79d [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 Bataevf4936072019-03-22 15:32:02 +00002257 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2258 // allocate directives that appear in a target region must specify an
2259 // allocator clause unless a requires directive with the dynamic_allocators
2260 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002261 if (LangOpts.OpenMPIsDevice &&
2262 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002263 targetDiag(Loc, diag::err_expected_allocator_clause);
2264 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002265 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002266 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002267 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2268 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002269 SmallVector<Expr *, 8> Vars;
2270 for (Expr *RefExpr : VarList) {
2271 auto *DE = cast<DeclRefExpr>(RefExpr);
2272 auto *VD = cast<VarDecl>(DE->getDecl());
2273
2274 // Check if this is a TLS variable or global register.
2275 if (VD->getTLSKind() != VarDecl::TLS_None ||
2276 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2277 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2278 !VD->isLocalVarDecl()))
2279 continue;
2280 // Do not apply for parameters.
2281 if (isa<ParmVarDecl>(VD))
2282 continue;
2283
Alexey Bataev282555a2019-03-19 20:33:44 +00002284 // If the used several times in the allocate directive, the same allocator
2285 // must be used.
2286 if (VD->hasAttr<OMPAllocateDeclAttr>()) {
2287 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002288 Expr *PrevAllocator = A->getAllocator();
2289 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2290 getAllocatorKind(*this, DSAStack, PrevAllocator);
2291 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2292 if (AllocatorsMatch && Allocator && PrevAllocator) {
Alexey Bataev282555a2019-03-19 20:33:44 +00002293 const Expr *AE = Allocator->IgnoreParenImpCasts();
2294 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2295 llvm::FoldingSetNodeID AEId, PAEId;
2296 AE->Profile(AEId, Context, /*Canonical=*/true);
2297 PAE->Profile(PAEId, Context, /*Canonical=*/true);
2298 AllocatorsMatch = AEId == PAEId;
Alexey Bataev282555a2019-03-19 20:33:44 +00002299 }
2300 if (!AllocatorsMatch) {
2301 SmallString<256> AllocatorBuffer;
2302 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2303 if (Allocator)
2304 Allocator->printPretty(AllocatorStream, nullptr, getPrintingPolicy());
2305 SmallString<256> PrevAllocatorBuffer;
2306 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2307 if (PrevAllocator)
2308 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2309 getPrintingPolicy());
2310
2311 SourceLocation AllocatorLoc =
2312 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2313 SourceRange AllocatorRange =
2314 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2315 SourceLocation PrevAllocatorLoc =
2316 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2317 SourceRange PrevAllocatorRange =
2318 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2319 Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2320 << (Allocator ? 1 : 0) << AllocatorStream.str()
2321 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2322 << AllocatorRange;
2323 Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2324 << PrevAllocatorRange;
2325 continue;
2326 }
2327 }
2328
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002329 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2330 // If a list item has a static storage type, the allocator expression in the
2331 // allocator clause must be a constant expression that evaluates to one of
2332 // the predefined memory allocator values.
2333 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002334 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002335 Diag(Allocator->getExprLoc(),
2336 diag::err_omp_expected_predefined_allocator)
2337 << Allocator->getSourceRange();
2338 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2339 VarDecl::DeclarationOnly;
2340 Diag(VD->getLocation(),
2341 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2342 << VD;
2343 continue;
2344 }
2345 }
2346
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002347 Vars.push_back(RefExpr);
Alexey Bataev282555a2019-03-19 20:33:44 +00002348 if ((!Allocator || (Allocator && !Allocator->isTypeDependent() &&
2349 !Allocator->isValueDependent() &&
2350 !Allocator->isInstantiationDependent() &&
2351 !Allocator->containsUnexpandedParameterPack())) &&
2352 !VD->hasAttr<OMPAllocateDeclAttr>()) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002353 Attr *A = OMPAllocateDeclAttr::CreateImplicit(
2354 Context, AllocatorKind, Allocator, DE->getSourceRange());
Alexey Bataev282555a2019-03-19 20:33:44 +00002355 VD->addAttr(A);
2356 if (ASTMutationListener *ML = Context.getASTMutationListener())
2357 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2358 }
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002359 }
2360 if (Vars.empty())
2361 return nullptr;
2362 if (!Owner)
2363 Owner = getCurLexicalContext();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002364 OMPAllocateDecl *D =
2365 OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002366 D->setAccess(AS_public);
2367 Owner->addDecl(D);
2368 return DeclGroupPtrTy::make(DeclGroupRef(D));
2369}
2370
2371Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002372Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2373 ArrayRef<OMPClause *> ClauseList) {
2374 OMPRequiresDecl *D = nullptr;
2375 if (!CurContext->isFileContext()) {
2376 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2377 } else {
2378 D = CheckOMPRequiresDecl(Loc, ClauseList);
2379 if (D) {
2380 CurContext->addDecl(D);
2381 DSAStack->addRequiresDecl(D);
2382 }
2383 }
2384 return DeclGroupPtrTy::make(DeclGroupRef(D));
2385}
2386
2387OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2388 ArrayRef<OMPClause *> ClauseList) {
2389 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2390 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2391 ClauseList);
2392 return nullptr;
2393}
2394
Alexey Bataeve3727102018-04-18 15:57:46 +00002395static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2396 const ValueDecl *D,
2397 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002398 bool IsLoopIterVar = false) {
2399 if (DVar.RefExpr) {
2400 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2401 << getOpenMPClauseName(DVar.CKind);
2402 return;
2403 }
2404 enum {
2405 PDSA_StaticMemberShared,
2406 PDSA_StaticLocalVarShared,
2407 PDSA_LoopIterVarPrivate,
2408 PDSA_LoopIterVarLinear,
2409 PDSA_LoopIterVarLastprivate,
2410 PDSA_ConstVarShared,
2411 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002412 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002413 PDSA_LocalVarPrivate,
2414 PDSA_Implicit
2415 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002416 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002417 auto ReportLoc = D->getLocation();
2418 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002419 if (IsLoopIterVar) {
2420 if (DVar.CKind == OMPC_private)
2421 Reason = PDSA_LoopIterVarPrivate;
2422 else if (DVar.CKind == OMPC_lastprivate)
2423 Reason = PDSA_LoopIterVarLastprivate;
2424 else
2425 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002426 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2427 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002428 Reason = PDSA_TaskVarFirstprivate;
2429 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002430 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002431 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002432 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002433 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002434 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002435 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002436 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002437 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002438 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002439 ReportHint = true;
2440 Reason = PDSA_LocalVarPrivate;
2441 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002442 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002443 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002444 << Reason << ReportHint
2445 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2446 } else if (DVar.ImplicitDSALoc.isValid()) {
2447 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2448 << getOpenMPClauseName(DVar.CKind);
2449 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002450}
2451
Alexey Bataev758e55e2013-09-06 18:03:48 +00002452namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002453class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002454 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002455 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002456 bool ErrorFound = false;
2457 CapturedStmt *CS = nullptr;
2458 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2459 llvm::SmallVector<Expr *, 4> ImplicitMap;
2460 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2461 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002462
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002463 void VisitSubCaptures(OMPExecutableDirective *S) {
2464 // Check implicitly captured variables.
2465 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2466 return;
2467 for (const CapturedStmt::Capture &Cap :
2468 S->getInnermostCapturedStmt()->captures()) {
2469 if (!Cap.capturesVariable())
2470 continue;
2471 VarDecl *VD = Cap.getCapturedVar();
2472 // Do not try to map the variable if it or its sub-component was mapped
2473 // already.
2474 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2475 Stack->checkMappableExprComponentListsForDecl(
2476 VD, /*CurrentRegionOnly=*/true,
2477 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2478 OpenMPClauseKind) { return true; }))
2479 continue;
2480 DeclRefExpr *DRE = buildDeclRefExpr(
2481 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2482 Cap.getLocation(), /*RefersToCapture=*/true);
2483 Visit(DRE);
2484 }
2485 }
2486
Alexey Bataev758e55e2013-09-06 18:03:48 +00002487public:
2488 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002489 if (E->isTypeDependent() || E->isValueDependent() ||
2490 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2491 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002492 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002493 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002494 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002495 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002496 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002497
Alexey Bataeve3727102018-04-18 15:57:46 +00002498 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002499 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002500 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002501 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002502
Alexey Bataevafe50572017-10-06 17:00:28 +00002503 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002504 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002505 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002506 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2507 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002508 return;
2509
Alexey Bataeve3727102018-04-18 15:57:46 +00002510 SourceLocation ELoc = E->getExprLoc();
2511 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002512 // The default(none) clause requires that each variable that is referenced
2513 // in the construct, and does not have a predetermined data-sharing
2514 // attribute, must have its data-sharing attribute explicitly determined
2515 // by being listed in a data-sharing attribute clause.
2516 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002517 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002518 VarsWithInheritedDSA.count(VD) == 0) {
2519 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002520 return;
2521 }
2522
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002523 if (isOpenMPTargetExecutionDirective(DKind) &&
2524 !Stack->isLoopControlVariable(VD).first) {
2525 if (!Stack->checkMappableExprComponentListsForDecl(
2526 VD, /*CurrentRegionOnly=*/true,
2527 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2528 StackComponents,
2529 OpenMPClauseKind) {
2530 // Variable is used if it has been marked as an array, array
2531 // section or the variable iself.
2532 return StackComponents.size() == 1 ||
2533 std::all_of(
2534 std::next(StackComponents.rbegin()),
2535 StackComponents.rend(),
2536 [](const OMPClauseMappableExprCommon::
2537 MappableComponent &MC) {
2538 return MC.getAssociatedDeclaration() ==
2539 nullptr &&
2540 (isa<OMPArraySectionExpr>(
2541 MC.getAssociatedExpression()) ||
2542 isa<ArraySubscriptExpr>(
2543 MC.getAssociatedExpression()));
2544 });
2545 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002546 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002547 // By default lambdas are captured as firstprivates.
2548 if (const auto *RD =
2549 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002550 IsFirstprivate = RD->isLambda();
2551 IsFirstprivate =
2552 IsFirstprivate ||
2553 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002554 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002555 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002556 ImplicitFirstprivate.emplace_back(E);
2557 else
2558 ImplicitMap.emplace_back(E);
2559 return;
2560 }
2561 }
2562
Alexey Bataev758e55e2013-09-06 18:03:48 +00002563 // OpenMP [2.9.3.6, Restrictions, p.2]
2564 // A list item that appears in a reduction clause of the innermost
2565 // enclosing worksharing or parallel construct may not be accessed in an
2566 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002567 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002568 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2569 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002570 return isOpenMPParallelDirective(K) ||
2571 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2572 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002573 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002574 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002575 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002576 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002577 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002578 return;
2579 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002580
2581 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002582 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002583 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00002584 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002585 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00002586 return;
2587 }
2588
2589 // Store implicitly used globals with declare target link for parent
2590 // target.
2591 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2592 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2593 Stack->addToParentTargetRegionLinkGlobals(E);
2594 return;
2595 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002596 }
2597 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002598 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002599 if (E->isTypeDependent() || E->isValueDependent() ||
2600 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2601 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002602 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002603 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002604 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002605 if (!FD)
2606 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002607 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002608 // Check if the variable has explicit DSA set and stop analysis if it
2609 // so.
2610 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2611 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002612
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002613 if (isOpenMPTargetExecutionDirective(DKind) &&
2614 !Stack->isLoopControlVariable(FD).first &&
2615 !Stack->checkMappableExprComponentListsForDecl(
2616 FD, /*CurrentRegionOnly=*/true,
2617 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2618 StackComponents,
2619 OpenMPClauseKind) {
2620 return isa<CXXThisExpr>(
2621 cast<MemberExpr>(
2622 StackComponents.back().getAssociatedExpression())
2623 ->getBase()
2624 ->IgnoreParens());
2625 })) {
2626 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2627 // A bit-field cannot appear in a map clause.
2628 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002629 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002630 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002631
2632 // Check to see if the member expression is referencing a class that
2633 // has already been explicitly mapped
2634 if (Stack->isClassPreviouslyMapped(TE->getType()))
2635 return;
2636
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002637 ImplicitMap.emplace_back(E);
2638 return;
2639 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002640
Alexey Bataeve3727102018-04-18 15:57:46 +00002641 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002642 // OpenMP [2.9.3.6, Restrictions, p.2]
2643 // A list item that appears in a reduction clause of the innermost
2644 // enclosing worksharing or parallel construct may not be accessed in
2645 // an explicit task.
2646 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002647 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2648 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002649 return isOpenMPParallelDirective(K) ||
2650 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2651 },
2652 /*FromParent=*/true);
2653 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2654 ErrorFound = true;
2655 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002656 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002657 return;
2658 }
2659
2660 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002661 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002662 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002663 !Stack->isLoopControlVariable(FD).first) {
2664 // Check if there is a captured expression for the current field in the
2665 // region. Do not mark it as firstprivate unless there is no captured
2666 // expression.
2667 // TODO: try to make it firstprivate.
2668 if (DVar.CKind != OMPC_unknown)
2669 ImplicitFirstprivate.push_back(E);
2670 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002671 return;
2672 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002673 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002674 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002675 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002676 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002677 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002678 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002679 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2680 if (!Stack->checkMappableExprComponentListsForDecl(
2681 VD, /*CurrentRegionOnly=*/true,
2682 [&CurComponents](
2683 OMPClauseMappableExprCommon::MappableExprComponentListRef
2684 StackComponents,
2685 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002686 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002687 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002688 for (const auto &SC : llvm::reverse(StackComponents)) {
2689 // Do both expressions have the same kind?
2690 if (CCI->getAssociatedExpression()->getStmtClass() !=
2691 SC.getAssociatedExpression()->getStmtClass())
2692 if (!(isa<OMPArraySectionExpr>(
2693 SC.getAssociatedExpression()) &&
2694 isa<ArraySubscriptExpr>(
2695 CCI->getAssociatedExpression())))
2696 return false;
2697
Alexey Bataeve3727102018-04-18 15:57:46 +00002698 const Decl *CCD = CCI->getAssociatedDeclaration();
2699 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002700 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2701 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2702 if (SCD != CCD)
2703 return false;
2704 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002705 if (CCI == CCE)
2706 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002707 }
2708 return true;
2709 })) {
2710 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002711 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002712 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002713 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00002714 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002715 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002716 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002717 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002718 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002719 // for task|target directives.
2720 // Skip analysis of arguments of implicitly defined map clause for target
2721 // directives.
2722 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2723 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002724 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002725 if (CC)
2726 Visit(CC);
2727 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002728 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002729 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00002730 // Check implicitly captured variables.
2731 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002732 }
2733 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002734 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002735 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00002736 // Check implicitly captured variables in the task-based directives to
2737 // check if they must be firstprivatized.
2738 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002739 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002740 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002741 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002742
Alexey Bataeve3727102018-04-18 15:57:46 +00002743 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002744 ArrayRef<Expr *> getImplicitFirstprivate() const {
2745 return ImplicitFirstprivate;
2746 }
2747 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00002748 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002749 return VarsWithInheritedDSA;
2750 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002751
Alexey Bataev7ff55242014-06-19 09:13:45 +00002752 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00002753 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
2754 // Process declare target link variables for the target directives.
2755 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
2756 for (DeclRefExpr *E : Stack->getLinkGlobals())
2757 Visit(E);
2758 }
2759 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002760};
Alexey Bataeved09d242014-05-28 05:53:51 +00002761} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002762
Alexey Bataevbae9a792014-06-27 10:37:06 +00002763void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002764 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002765 case OMPD_parallel:
2766 case OMPD_parallel_for:
2767 case OMPD_parallel_for_simd:
2768 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002769 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002770 case OMPD_teams_distribute:
2771 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002772 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002773 QualType KmpInt32PtrTy =
2774 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002775 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002776 std::make_pair(".global_tid.", KmpInt32PtrTy),
2777 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2778 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002779 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002780 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2781 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002782 break;
2783 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002784 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002785 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002786 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002787 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002788 case OMPD_target_teams_distribute:
2789 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002790 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2791 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2792 QualType KmpInt32PtrTy =
2793 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2794 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002795 FunctionProtoType::ExtProtoInfo EPI;
2796 EPI.Variadic = true;
2797 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2798 Sema::CapturedParamNameType Params[] = {
2799 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002800 std::make_pair(".part_id.", KmpInt32PtrTy),
2801 std::make_pair(".privates.", VoidPtrTy),
2802 std::make_pair(
2803 ".copy_fn.",
2804 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002805 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2806 std::make_pair(StringRef(), QualType()) // __context with shared vars
2807 };
2808 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2809 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002810 // Mark this captured region as inlined, because we don't use outlined
2811 // function directly.
2812 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2813 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002814 Context, AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002815 Sema::CapturedParamNameType ParamsTarget[] = {
2816 std::make_pair(StringRef(), QualType()) // __context with shared vars
2817 };
2818 // Start a captured region for 'target' with no implicit parameters.
2819 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2820 ParamsTarget);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002821 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002822 std::make_pair(".global_tid.", KmpInt32PtrTy),
2823 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2824 std::make_pair(StringRef(), QualType()) // __context with shared vars
2825 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002826 // Start a captured region for 'teams' or 'parallel'. Both regions have
2827 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002828 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002829 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002830 break;
2831 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002832 case OMPD_target:
2833 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002834 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2835 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2836 QualType KmpInt32PtrTy =
2837 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2838 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002839 FunctionProtoType::ExtProtoInfo EPI;
2840 EPI.Variadic = true;
2841 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2842 Sema::CapturedParamNameType Params[] = {
2843 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002844 std::make_pair(".part_id.", KmpInt32PtrTy),
2845 std::make_pair(".privates.", VoidPtrTy),
2846 std::make_pair(
2847 ".copy_fn.",
2848 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002849 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2850 std::make_pair(StringRef(), QualType()) // __context with shared vars
2851 };
2852 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2853 Params);
2854 // Mark this captured region as inlined, because we don't use outlined
2855 // function directly.
2856 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2857 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002858 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00002859 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2860 std::make_pair(StringRef(), QualType()));
2861 break;
2862 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002863 case OMPD_simd:
2864 case OMPD_for:
2865 case OMPD_for_simd:
2866 case OMPD_sections:
2867 case OMPD_section:
2868 case OMPD_single:
2869 case OMPD_master:
2870 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002871 case OMPD_taskgroup:
2872 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002873 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002874 case OMPD_ordered:
2875 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002876 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002877 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002878 std::make_pair(StringRef(), QualType()) // __context with shared vars
2879 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002880 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2881 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002882 break;
2883 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002884 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002885 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2886 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2887 QualType KmpInt32PtrTy =
2888 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2889 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002890 FunctionProtoType::ExtProtoInfo EPI;
2891 EPI.Variadic = true;
2892 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002893 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002894 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002895 std::make_pair(".part_id.", KmpInt32PtrTy),
2896 std::make_pair(".privates.", VoidPtrTy),
2897 std::make_pair(
2898 ".copy_fn.",
2899 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002900 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002901 std::make_pair(StringRef(), QualType()) // __context with shared vars
2902 };
2903 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2904 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002905 // Mark this captured region as inlined, because we don't use outlined
2906 // function directly.
2907 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2908 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002909 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002910 break;
2911 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002912 case OMPD_taskloop:
2913 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002914 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002915 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2916 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002917 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002918 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2919 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002920 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002921 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2922 .withConst();
2923 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2924 QualType KmpInt32PtrTy =
2925 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2926 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00002927 FunctionProtoType::ExtProtoInfo EPI;
2928 EPI.Variadic = true;
2929 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002930 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002931 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002932 std::make_pair(".part_id.", KmpInt32PtrTy),
2933 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00002934 std::make_pair(
2935 ".copy_fn.",
2936 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2937 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2938 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002939 std::make_pair(".ub.", KmpUInt64Ty),
2940 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00002941 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002942 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002943 std::make_pair(StringRef(), QualType()) // __context with shared vars
2944 };
2945 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2946 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002947 // Mark this captured region as inlined, because we don't use outlined
2948 // function directly.
2949 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2950 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002951 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002952 break;
2953 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002954 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002955 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002956 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00002957 QualType KmpInt32PtrTy =
2958 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2959 Sema::CapturedParamNameType Params[] = {
2960 std::make_pair(".global_tid.", KmpInt32PtrTy),
2961 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002962 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2963 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00002964 std::make_pair(StringRef(), QualType()) // __context with shared vars
2965 };
2966 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2967 Params);
2968 break;
2969 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002970 case OMPD_target_teams_distribute_parallel_for:
2971 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002972 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002973 QualType KmpInt32PtrTy =
2974 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002975 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002976
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002977 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002978 FunctionProtoType::ExtProtoInfo EPI;
2979 EPI.Variadic = true;
2980 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2981 Sema::CapturedParamNameType Params[] = {
2982 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002983 std::make_pair(".part_id.", KmpInt32PtrTy),
2984 std::make_pair(".privates.", VoidPtrTy),
2985 std::make_pair(
2986 ".copy_fn.",
2987 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002988 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2989 std::make_pair(StringRef(), QualType()) // __context with shared vars
2990 };
2991 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2992 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00002993 // Mark this captured region as inlined, because we don't use outlined
2994 // function directly.
2995 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2996 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002997 Context, AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00002998 Sema::CapturedParamNameType ParamsTarget[] = {
2999 std::make_pair(StringRef(), QualType()) // __context with shared vars
3000 };
3001 // Start a captured region for 'target' with no implicit parameters.
3002 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3003 ParamsTarget);
3004
3005 Sema::CapturedParamNameType ParamsTeams[] = {
3006 std::make_pair(".global_tid.", KmpInt32PtrTy),
3007 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3008 std::make_pair(StringRef(), QualType()) // __context with shared vars
3009 };
3010 // Start a captured region for 'target' with no implicit parameters.
3011 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3012 ParamsTeams);
3013
3014 Sema::CapturedParamNameType ParamsParallel[] = {
3015 std::make_pair(".global_tid.", KmpInt32PtrTy),
3016 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003017 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3018 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003019 std::make_pair(StringRef(), QualType()) // __context with shared vars
3020 };
3021 // Start a captured region for 'teams' or 'parallel'. Both regions have
3022 // the same implicit parameters.
3023 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3024 ParamsParallel);
3025 break;
3026 }
3027
Alexey Bataev46506272017-12-05 17:41:34 +00003028 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003029 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003030 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003031 QualType KmpInt32PtrTy =
3032 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3033
3034 Sema::CapturedParamNameType ParamsTeams[] = {
3035 std::make_pair(".global_tid.", KmpInt32PtrTy),
3036 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3037 std::make_pair(StringRef(), QualType()) // __context with shared vars
3038 };
3039 // Start a captured region for 'target' with no implicit parameters.
3040 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3041 ParamsTeams);
3042
3043 Sema::CapturedParamNameType ParamsParallel[] = {
3044 std::make_pair(".global_tid.", KmpInt32PtrTy),
3045 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003046 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3047 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003048 std::make_pair(StringRef(), QualType()) // __context with shared vars
3049 };
3050 // Start a captured region for 'teams' or 'parallel'. Both regions have
3051 // the same implicit parameters.
3052 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3053 ParamsParallel);
3054 break;
3055 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003056 case OMPD_target_update:
3057 case OMPD_target_enter_data:
3058 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003059 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3060 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3061 QualType KmpInt32PtrTy =
3062 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3063 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003064 FunctionProtoType::ExtProtoInfo EPI;
3065 EPI.Variadic = true;
3066 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3067 Sema::CapturedParamNameType Params[] = {
3068 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003069 std::make_pair(".part_id.", KmpInt32PtrTy),
3070 std::make_pair(".privates.", VoidPtrTy),
3071 std::make_pair(
3072 ".copy_fn.",
3073 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003074 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3075 std::make_pair(StringRef(), QualType()) // __context with shared vars
3076 };
3077 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3078 Params);
3079 // Mark this captured region as inlined, because we don't use outlined
3080 // function directly.
3081 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3082 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003083 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003084 break;
3085 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003086 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003087 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003088 case OMPD_taskyield:
3089 case OMPD_barrier:
3090 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003091 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003092 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003093 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003094 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003095 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003096 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003097 case OMPD_declare_target:
3098 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003099 case OMPD_requires:
Alexey Bataev9959db52014-05-06 10:08:46 +00003100 llvm_unreachable("OpenMP Directive is not allowed");
3101 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003102 llvm_unreachable("Unknown OpenMP directive");
3103 }
3104}
3105
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003106int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3107 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3108 getOpenMPCaptureRegions(CaptureRegions, DKind);
3109 return CaptureRegions.size();
3110}
3111
Alexey Bataev3392d762016-02-16 11:18:12 +00003112static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003113 Expr *CaptureExpr, bool WithInit,
3114 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003115 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003116 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003117 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003118 QualType Ty = Init->getType();
3119 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003120 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003121 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003122 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003123 Ty = C.getPointerType(Ty);
3124 ExprResult Res =
3125 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3126 if (!Res.isUsable())
3127 return nullptr;
3128 Init = Res.get();
3129 }
Alexey Bataev61205072016-03-02 04:57:40 +00003130 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003131 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003132 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003133 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003134 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003135 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003136 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003137 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003138 return CED;
3139}
3140
Alexey Bataev61205072016-03-02 04:57:40 +00003141static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3142 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003143 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003144 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003145 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003146 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003147 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3148 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003149 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003150 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003151}
3152
Alexey Bataev5a3af132016-03-29 08:58:54 +00003153static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003154 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003155 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003156 OMPCapturedExprDecl *CD = buildCaptureDecl(
3157 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3158 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003159 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3160 CaptureExpr->getExprLoc());
3161 }
3162 ExprResult Res = Ref;
3163 if (!S.getLangOpts().CPlusPlus &&
3164 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003165 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003166 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003167 if (!Res.isUsable())
3168 return ExprError();
3169 }
3170 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003171}
3172
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003173namespace {
3174// OpenMP directives parsed in this section are represented as a
3175// CapturedStatement with an associated statement. If a syntax error
3176// is detected during the parsing of the associated statement, the
3177// compiler must abort processing and close the CapturedStatement.
3178//
3179// Combined directives such as 'target parallel' have more than one
3180// nested CapturedStatements. This RAII ensures that we unwind out
3181// of all the nested CapturedStatements when an error is found.
3182class CaptureRegionUnwinderRAII {
3183private:
3184 Sema &S;
3185 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003186 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003187
3188public:
3189 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3190 OpenMPDirectiveKind DKind)
3191 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3192 ~CaptureRegionUnwinderRAII() {
3193 if (ErrorFound) {
3194 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3195 while (--ThisCaptureLevel >= 0)
3196 S.ActOnCapturedRegionError();
3197 }
3198 }
3199};
3200} // namespace
3201
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003202StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3203 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003204 bool ErrorFound = false;
3205 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3206 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003207 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003208 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003209 return StmtError();
3210 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003211
Alexey Bataev2ba67042017-11-28 21:11:44 +00003212 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3213 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003214 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003215 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003216 SmallVector<const OMPLinearClause *, 4> LCs;
3217 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003218 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003219 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003220 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3221 Clause->getClauseKind() == OMPC_in_reduction) {
3222 // Capture taskgroup task_reduction descriptors inside the tasking regions
3223 // with the corresponding in_reduction items.
3224 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003225 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003226 if (E)
3227 MarkDeclarationsReferencedInExpr(E);
3228 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003229 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003230 Clause->getClauseKind() == OMPC_copyprivate ||
3231 (getLangOpts().OpenMPUseTLS &&
3232 getASTContext().getTargetInfo().isTLSSupported() &&
3233 Clause->getClauseKind() == OMPC_copyin)) {
3234 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003235 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003236 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003237 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003238 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003239 }
3240 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003241 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003242 } else if (CaptureRegions.size() > 1 ||
3243 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003244 if (auto *C = OMPClauseWithPreInit::get(Clause))
3245 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003246 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003247 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003248 MarkDeclarationsReferencedInExpr(E);
3249 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003250 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003251 if (Clause->getClauseKind() == OMPC_schedule)
3252 SC = cast<OMPScheduleClause>(Clause);
3253 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003254 OC = cast<OMPOrderedClause>(Clause);
3255 else if (Clause->getClauseKind() == OMPC_linear)
3256 LCs.push_back(cast<OMPLinearClause>(Clause));
3257 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003258 // OpenMP, 2.7.1 Loop Construct, Restrictions
3259 // The nonmonotonic modifier cannot be specified if an ordered clause is
3260 // specified.
3261 if (SC &&
3262 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3263 SC->getSecondScheduleModifier() ==
3264 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3265 OC) {
3266 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3267 ? SC->getFirstScheduleModifierLoc()
3268 : SC->getSecondScheduleModifierLoc(),
3269 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003270 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003271 ErrorFound = true;
3272 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003273 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003274 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003275 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003276 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003277 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003278 ErrorFound = true;
3279 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003280 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3281 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3282 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003283 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003284 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3285 ErrorFound = true;
3286 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003287 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003288 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003289 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003290 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003291 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003292 // Mark all variables in private list clauses as used in inner region.
3293 // Required for proper codegen of combined directives.
3294 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003295 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003296 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003297 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3298 // Find the particular capture region for the clause if the
3299 // directive is a combined one with multiple capture regions.
3300 // If the directive is not a combined one, the capture region
3301 // associated with the clause is OMPD_unknown and is generated
3302 // only once.
3303 if (CaptureRegion == ThisCaptureRegion ||
3304 CaptureRegion == OMPD_unknown) {
3305 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003306 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003307 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3308 }
3309 }
3310 }
3311 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003312 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003313 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003314 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003315}
3316
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003317static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3318 OpenMPDirectiveKind CancelRegion,
3319 SourceLocation StartLoc) {
3320 // CancelRegion is only needed for cancel and cancellation_point.
3321 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3322 return false;
3323
3324 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3325 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3326 return false;
3327
3328 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3329 << getOpenMPDirectiveName(CancelRegion);
3330 return true;
3331}
3332
Alexey Bataeve3727102018-04-18 15:57:46 +00003333static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003334 OpenMPDirectiveKind CurrentRegion,
3335 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003336 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003337 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003338 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003339 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3340 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003341 bool NestingProhibited = false;
3342 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003343 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003344 enum {
3345 NoRecommend,
3346 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003347 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003348 ShouldBeInTargetRegion,
3349 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003350 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003351 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003352 // OpenMP [2.16, Nesting of Regions]
3353 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003354 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003355 // An ordered construct with the simd clause is the only OpenMP
3356 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003357 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003358 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3359 // message.
3360 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3361 ? diag::err_omp_prohibited_region_simd
3362 : diag::warn_omp_nesting_simd);
3363 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003364 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003365 if (ParentRegion == OMPD_atomic) {
3366 // OpenMP [2.16, Nesting of Regions]
3367 // OpenMP constructs may not be nested inside an atomic region.
3368 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3369 return true;
3370 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003371 if (CurrentRegion == OMPD_section) {
3372 // OpenMP [2.7.2, sections Construct, Restrictions]
3373 // Orphaned section directives are prohibited. That is, the section
3374 // directives must appear within the sections construct and must not be
3375 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003376 if (ParentRegion != OMPD_sections &&
3377 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003378 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3379 << (ParentRegion != OMPD_unknown)
3380 << getOpenMPDirectiveName(ParentRegion);
3381 return true;
3382 }
3383 return false;
3384 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003385 // Allow some constructs (except teams and cancellation constructs) to be
3386 // orphaned (they could be used in functions, called from OpenMP regions
3387 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003388 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003389 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3390 CurrentRegion != OMPD_cancellation_point &&
3391 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003392 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003393 if (CurrentRegion == OMPD_cancellation_point ||
3394 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003395 // OpenMP [2.16, Nesting of Regions]
3396 // A cancellation point construct for which construct-type-clause is
3397 // taskgroup must be nested inside a task construct. A cancellation
3398 // point construct for which construct-type-clause is not taskgroup must
3399 // be closely nested inside an OpenMP construct that matches the type
3400 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003401 // A cancel construct for which construct-type-clause is taskgroup must be
3402 // nested inside a task construct. A cancel construct for which
3403 // construct-type-clause is not taskgroup must be closely nested inside an
3404 // OpenMP construct that matches the type specified in
3405 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003406 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003407 !((CancelRegion == OMPD_parallel &&
3408 (ParentRegion == OMPD_parallel ||
3409 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003410 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003411 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003412 ParentRegion == OMPD_target_parallel_for ||
3413 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003414 ParentRegion == OMPD_teams_distribute_parallel_for ||
3415 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003416 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3417 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003418 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3419 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003420 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003421 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003422 // OpenMP [2.16, Nesting of Regions]
3423 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003424 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003425 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003426 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003427 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3428 // OpenMP [2.16, Nesting of Regions]
3429 // A critical region may not be nested (closely or otherwise) inside a
3430 // critical region with the same name. Note that this restriction is not
3431 // sufficient to prevent deadlock.
3432 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003433 bool DeadLock = Stack->hasDirective(
3434 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3435 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003436 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003437 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3438 PreviousCriticalLoc = Loc;
3439 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003440 }
3441 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003442 },
3443 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003444 if (DeadLock) {
3445 SemaRef.Diag(StartLoc,
3446 diag::err_omp_prohibited_region_critical_same_name)
3447 << CurrentName.getName();
3448 if (PreviousCriticalLoc.isValid())
3449 SemaRef.Diag(PreviousCriticalLoc,
3450 diag::note_omp_previous_critical_region);
3451 return true;
3452 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003453 } else if (CurrentRegion == OMPD_barrier) {
3454 // OpenMP [2.16, Nesting of Regions]
3455 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003456 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003457 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3458 isOpenMPTaskingDirective(ParentRegion) ||
3459 ParentRegion == OMPD_master ||
3460 ParentRegion == OMPD_critical ||
3461 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003462 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003463 !isOpenMPParallelDirective(CurrentRegion) &&
3464 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003465 // OpenMP [2.16, Nesting of Regions]
3466 // A worksharing region may not be closely nested inside a worksharing,
3467 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003468 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3469 isOpenMPTaskingDirective(ParentRegion) ||
3470 ParentRegion == OMPD_master ||
3471 ParentRegion == OMPD_critical ||
3472 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003473 Recommend = ShouldBeInParallelRegion;
3474 } else if (CurrentRegion == OMPD_ordered) {
3475 // OpenMP [2.16, Nesting of Regions]
3476 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003477 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003478 // An ordered region must be closely nested inside a loop region (or
3479 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003480 // OpenMP [2.8.1,simd Construct, Restrictions]
3481 // An ordered construct with the simd clause is the only OpenMP construct
3482 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003483 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003484 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003485 !(isOpenMPSimdDirective(ParentRegion) ||
3486 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003487 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003488 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003489 // OpenMP [2.16, Nesting of Regions]
3490 // If specified, a teams construct must be contained within a target
3491 // construct.
3492 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00003493 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003494 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003495 }
Kelvin Libf594a52016-12-17 05:48:59 +00003496 if (!NestingProhibited &&
3497 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3498 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3499 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003500 // OpenMP [2.16, Nesting of Regions]
3501 // distribute, parallel, parallel sections, parallel workshare, and the
3502 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3503 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003504 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3505 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003506 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003507 }
David Majnemer9d168222016-08-05 17:44:54 +00003508 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003509 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003510 // OpenMP 4.5 [2.17 Nesting of Regions]
3511 // The region associated with the distribute construct must be strictly
3512 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003513 NestingProhibited =
3514 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003515 Recommend = ShouldBeInTeamsRegion;
3516 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003517 if (!NestingProhibited &&
3518 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3519 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3520 // OpenMP 4.5 [2.17 Nesting of Regions]
3521 // If a target, target update, target data, target enter data, or
3522 // target exit data construct is encountered during execution of a
3523 // target region, the behavior is unspecified.
3524 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003525 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003526 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003527 if (isOpenMPTargetExecutionDirective(K)) {
3528 OffendingRegion = K;
3529 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003530 }
3531 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003532 },
3533 false /* don't skip top directive */);
3534 CloseNesting = false;
3535 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003536 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003537 if (OrphanSeen) {
3538 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3539 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3540 } else {
3541 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3542 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3543 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3544 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003545 return true;
3546 }
3547 }
3548 return false;
3549}
3550
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003551static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3552 ArrayRef<OMPClause *> Clauses,
3553 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3554 bool ErrorFound = false;
3555 unsigned NamedModifiersNumber = 0;
3556 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3557 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003558 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003559 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003560 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3561 // At most one if clause without a directive-name-modifier can appear on
3562 // the directive.
3563 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3564 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003565 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003566 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3567 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3568 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003569 } else if (CurNM != OMPD_unknown) {
3570 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003571 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003572 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003573 FoundNameModifiers[CurNM] = IC;
3574 if (CurNM == OMPD_unknown)
3575 continue;
3576 // Check if the specified name modifier is allowed for the current
3577 // directive.
3578 // At most one if clause with the particular directive-name-modifier can
3579 // appear on the directive.
3580 bool MatchFound = false;
3581 for (auto NM : AllowedNameModifiers) {
3582 if (CurNM == NM) {
3583 MatchFound = true;
3584 break;
3585 }
3586 }
3587 if (!MatchFound) {
3588 S.Diag(IC->getNameModifierLoc(),
3589 diag::err_omp_wrong_if_directive_name_modifier)
3590 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3591 ErrorFound = true;
3592 }
3593 }
3594 }
3595 // If any if clause on the directive includes a directive-name-modifier then
3596 // all if clauses on the directive must include a directive-name-modifier.
3597 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3598 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003599 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003600 diag::err_omp_no_more_if_clause);
3601 } else {
3602 std::string Values;
3603 std::string Sep(", ");
3604 unsigned AllowedCnt = 0;
3605 unsigned TotalAllowedNum =
3606 AllowedNameModifiers.size() - NamedModifiersNumber;
3607 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3608 ++Cnt) {
3609 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3610 if (!FoundNameModifiers[NM]) {
3611 Values += "'";
3612 Values += getOpenMPDirectiveName(NM);
3613 Values += "'";
3614 if (AllowedCnt + 2 == TotalAllowedNum)
3615 Values += " or ";
3616 else if (AllowedCnt + 1 != TotalAllowedNum)
3617 Values += Sep;
3618 ++AllowedCnt;
3619 }
3620 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003621 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003622 diag::err_omp_unnamed_if_clause)
3623 << (TotalAllowedNum > 1) << Values;
3624 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003625 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00003626 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3627 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003628 ErrorFound = true;
3629 }
3630 return ErrorFound;
3631}
3632
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003633StmtResult Sema::ActOnOpenMPExecutableDirective(
3634 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3635 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3636 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003637 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003638 // First check CancelRegion which is then used in checkNestingOfRegions.
3639 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3640 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003641 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00003642 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003643
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003644 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00003645 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003646 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003647 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003648 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003649 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3650
3651 // Check default data sharing attributes for referenced variables.
3652 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003653 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3654 Stmt *S = AStmt;
3655 while (--ThisCaptureLevel >= 0)
3656 S = cast<CapturedStmt>(S)->getCapturedStmt();
3657 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003658 if (DSAChecker.isErrorFound())
3659 return StmtError();
3660 // Generate list of implicitly defined firstprivate variables.
3661 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003662
Alexey Bataev88202be2017-07-27 13:20:36 +00003663 SmallVector<Expr *, 4> ImplicitFirstprivates(
3664 DSAChecker.getImplicitFirstprivate().begin(),
3665 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003666 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3667 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003668 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00003669 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003670 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003671 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003672 if (E)
3673 ImplicitFirstprivates.emplace_back(E);
3674 }
3675 }
3676 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003677 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00003678 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3679 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003680 ClausesWithImplicit.push_back(Implicit);
3681 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00003682 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003683 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00003684 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003685 }
Alexey Bataev68446b72014-07-18 07:47:19 +00003686 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003687 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00003688 CXXScopeSpec MapperIdScopeSpec;
3689 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003690 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00003691 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
3692 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
3693 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003694 ClausesWithImplicit.emplace_back(Implicit);
3695 ErrorFound |=
3696 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003697 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003698 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003699 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003700 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003701 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003702
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003703 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003704 switch (Kind) {
3705 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003706 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3707 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003708 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003709 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003710 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003711 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3712 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003713 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003714 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003715 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3716 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003717 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003718 case OMPD_for_simd:
3719 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3720 EndLoc, VarsWithInheritedDSA);
3721 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003722 case OMPD_sections:
3723 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3724 EndLoc);
3725 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003726 case OMPD_section:
3727 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003728 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003729 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3730 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003731 case OMPD_single:
3732 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3733 EndLoc);
3734 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003735 case OMPD_master:
3736 assert(ClausesWithImplicit.empty() &&
3737 "No clauses are allowed for 'omp master' directive");
3738 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3739 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003740 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003741 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3742 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003743 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003744 case OMPD_parallel_for:
3745 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3746 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003747 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003748 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003749 case OMPD_parallel_for_simd:
3750 Res = ActOnOpenMPParallelForSimdDirective(
3751 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003752 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003753 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003754 case OMPD_parallel_sections:
3755 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3756 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003757 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003758 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003759 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003760 Res =
3761 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003762 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003763 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003764 case OMPD_taskyield:
3765 assert(ClausesWithImplicit.empty() &&
3766 "No clauses are allowed for 'omp taskyield' directive");
3767 assert(AStmt == nullptr &&
3768 "No associated statement allowed for 'omp taskyield' directive");
3769 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3770 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003771 case OMPD_barrier:
3772 assert(ClausesWithImplicit.empty() &&
3773 "No clauses are allowed for 'omp barrier' directive");
3774 assert(AStmt == nullptr &&
3775 "No associated statement allowed for 'omp barrier' directive");
3776 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3777 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003778 case OMPD_taskwait:
3779 assert(ClausesWithImplicit.empty() &&
3780 "No clauses are allowed for 'omp taskwait' directive");
3781 assert(AStmt == nullptr &&
3782 "No associated statement allowed for 'omp taskwait' directive");
3783 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3784 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003785 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003786 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3787 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003788 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003789 case OMPD_flush:
3790 assert(AStmt == nullptr &&
3791 "No associated statement allowed for 'omp flush' directive");
3792 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3793 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003794 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003795 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3796 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003797 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003798 case OMPD_atomic:
3799 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3800 EndLoc);
3801 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003802 case OMPD_teams:
3803 Res =
3804 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3805 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003806 case OMPD_target:
3807 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3808 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003809 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003810 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003811 case OMPD_target_parallel:
3812 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3813 StartLoc, EndLoc);
3814 AllowedNameModifiers.push_back(OMPD_target);
3815 AllowedNameModifiers.push_back(OMPD_parallel);
3816 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003817 case OMPD_target_parallel_for:
3818 Res = ActOnOpenMPTargetParallelForDirective(
3819 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3820 AllowedNameModifiers.push_back(OMPD_target);
3821 AllowedNameModifiers.push_back(OMPD_parallel);
3822 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003823 case OMPD_cancellation_point:
3824 assert(ClausesWithImplicit.empty() &&
3825 "No clauses are allowed for 'omp cancellation point' directive");
3826 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3827 "cancellation point' directive");
3828 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3829 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003830 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003831 assert(AStmt == nullptr &&
3832 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003833 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3834 CancelRegion);
3835 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003836 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003837 case OMPD_target_data:
3838 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3839 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003840 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003841 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003842 case OMPD_target_enter_data:
3843 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003844 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003845 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3846 break;
Samuel Antao72590762016-01-19 20:04:50 +00003847 case OMPD_target_exit_data:
3848 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003849 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003850 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3851 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003852 case OMPD_taskloop:
3853 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3854 EndLoc, VarsWithInheritedDSA);
3855 AllowedNameModifiers.push_back(OMPD_taskloop);
3856 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003857 case OMPD_taskloop_simd:
3858 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3859 EndLoc, VarsWithInheritedDSA);
3860 AllowedNameModifiers.push_back(OMPD_taskloop);
3861 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003862 case OMPD_distribute:
3863 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3864 EndLoc, VarsWithInheritedDSA);
3865 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003866 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003867 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3868 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003869 AllowedNameModifiers.push_back(OMPD_target_update);
3870 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003871 case OMPD_distribute_parallel_for:
3872 Res = ActOnOpenMPDistributeParallelForDirective(
3873 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3874 AllowedNameModifiers.push_back(OMPD_parallel);
3875 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003876 case OMPD_distribute_parallel_for_simd:
3877 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3878 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3879 AllowedNameModifiers.push_back(OMPD_parallel);
3880 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003881 case OMPD_distribute_simd:
3882 Res = ActOnOpenMPDistributeSimdDirective(
3883 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3884 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003885 case OMPD_target_parallel_for_simd:
3886 Res = ActOnOpenMPTargetParallelForSimdDirective(
3887 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3888 AllowedNameModifiers.push_back(OMPD_target);
3889 AllowedNameModifiers.push_back(OMPD_parallel);
3890 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003891 case OMPD_target_simd:
3892 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3893 EndLoc, VarsWithInheritedDSA);
3894 AllowedNameModifiers.push_back(OMPD_target);
3895 break;
Kelvin Li02532872016-08-05 14:37:37 +00003896 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003897 Res = ActOnOpenMPTeamsDistributeDirective(
3898 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003899 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003900 case OMPD_teams_distribute_simd:
3901 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3902 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3903 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003904 case OMPD_teams_distribute_parallel_for_simd:
3905 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3906 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3907 AllowedNameModifiers.push_back(OMPD_parallel);
3908 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003909 case OMPD_teams_distribute_parallel_for:
3910 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3911 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3912 AllowedNameModifiers.push_back(OMPD_parallel);
3913 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003914 case OMPD_target_teams:
3915 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3916 EndLoc);
3917 AllowedNameModifiers.push_back(OMPD_target);
3918 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003919 case OMPD_target_teams_distribute:
3920 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3921 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3922 AllowedNameModifiers.push_back(OMPD_target);
3923 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003924 case OMPD_target_teams_distribute_parallel_for:
3925 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3926 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3927 AllowedNameModifiers.push_back(OMPD_target);
3928 AllowedNameModifiers.push_back(OMPD_parallel);
3929 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003930 case OMPD_target_teams_distribute_parallel_for_simd:
3931 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3932 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3933 AllowedNameModifiers.push_back(OMPD_target);
3934 AllowedNameModifiers.push_back(OMPD_parallel);
3935 break;
Kelvin Lida681182017-01-10 18:08:18 +00003936 case OMPD_target_teams_distribute_simd:
3937 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3938 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3939 AllowedNameModifiers.push_back(OMPD_target);
3940 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003941 case OMPD_declare_target:
3942 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003943 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003944 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003945 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003946 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003947 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00003948 case OMPD_requires:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003949 llvm_unreachable("OpenMP Directive is not allowed");
3950 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003951 llvm_unreachable("Unknown OpenMP directive");
3952 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003953
Roman Lebedevb5700602019-03-20 16:32:36 +00003954 ErrorFound = Res.isInvalid() || ErrorFound;
3955
Alexey Bataeve3727102018-04-18 15:57:46 +00003956 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003957 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3958 << P.first << P.second->getSourceRange();
3959 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003960 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3961
3962 if (!AllowedNameModifiers.empty())
3963 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3964 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003965
Alexey Bataeved09d242014-05-28 05:53:51 +00003966 if (ErrorFound)
3967 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00003968
3969 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
3970 Res.getAs<OMPExecutableDirective>()
3971 ->getStructuredBlock()
3972 ->setIsOMPStructuredBlock(true);
3973 }
3974
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003975 return Res;
3976}
3977
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003978Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3979 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003980 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003981 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3982 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003983 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003984 assert(Linears.size() == LinModifiers.size());
3985 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003986 if (!DG || DG.get().isNull())
3987 return DeclGroupPtrTy();
3988
3989 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003990 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003991 return DG;
3992 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003993 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00003994 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3995 ADecl = FTD->getTemplatedDecl();
3996
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003997 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3998 if (!FD) {
3999 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004000 return DeclGroupPtrTy();
4001 }
4002
Alexey Bataev2af33e32016-04-07 12:45:37 +00004003 // OpenMP [2.8.2, declare simd construct, Description]
4004 // The parameter of the simdlen clause must be a constant positive integer
4005 // expression.
4006 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004007 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00004008 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004009 // OpenMP [2.8.2, declare simd construct, Description]
4010 // The special this pointer can be used as if was one of the arguments to the
4011 // function in any of the linear, aligned, or uniform clauses.
4012 // The uniform clause declares one or more arguments to have an invariant
4013 // value for all concurrent invocations of the function in the execution of a
4014 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00004015 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4016 const Expr *UniformedLinearThis = nullptr;
4017 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004018 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004019 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4020 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004021 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4022 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004023 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004024 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004025 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004026 }
4027 if (isa<CXXThisExpr>(E)) {
4028 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004029 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004030 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004031 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4032 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004033 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004034 // OpenMP [2.8.2, declare simd construct, Description]
4035 // The aligned clause declares that the object to which each list item points
4036 // is aligned to the number of bytes expressed in the optional parameter of
4037 // the aligned clause.
4038 // The special this pointer can be used as if was one of the arguments to the
4039 // function in any of the linear, aligned, or uniform clauses.
4040 // The type of list items appearing in the aligned clause must be array,
4041 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004042 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4043 const Expr *AlignedThis = nullptr;
4044 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004045 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004046 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4047 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4048 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004049 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4050 FD->getParamDecl(PVD->getFunctionScopeIndex())
4051 ->getCanonicalDecl() == CanonPVD) {
4052 // OpenMP [2.8.1, simd construct, Restrictions]
4053 // A list-item cannot appear in more than one aligned clause.
4054 if (AlignedArgs.count(CanonPVD) > 0) {
4055 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4056 << 1 << E->getSourceRange();
4057 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4058 diag::note_omp_explicit_dsa)
4059 << getOpenMPClauseName(OMPC_aligned);
4060 continue;
4061 }
4062 AlignedArgs[CanonPVD] = E;
4063 QualType QTy = PVD->getType()
4064 .getNonReferenceType()
4065 .getUnqualifiedType()
4066 .getCanonicalType();
4067 const Type *Ty = QTy.getTypePtrOrNull();
4068 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4069 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4070 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4071 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4072 }
4073 continue;
4074 }
4075 }
4076 if (isa<CXXThisExpr>(E)) {
4077 if (AlignedThis) {
4078 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4079 << 2 << E->getSourceRange();
4080 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4081 << getOpenMPClauseName(OMPC_aligned);
4082 }
4083 AlignedThis = E;
4084 continue;
4085 }
4086 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4087 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4088 }
4089 // The optional parameter of the aligned clause, alignment, must be a constant
4090 // positive integer expression. If no optional parameter is specified,
4091 // implementation-defined default alignments for SIMD instructions on the
4092 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00004093 SmallVector<const Expr *, 4> NewAligns;
4094 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004095 ExprResult Align;
4096 if (E)
4097 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4098 NewAligns.push_back(Align.get());
4099 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00004100 // OpenMP [2.8.2, declare simd construct, Description]
4101 // The linear clause declares one or more list items to be private to a SIMD
4102 // lane and to have a linear relationship with respect to the iteration space
4103 // of a loop.
4104 // The special this pointer can be used as if was one of the arguments to the
4105 // function in any of the linear, aligned, or uniform clauses.
4106 // When a linear-step expression is specified in a linear clause it must be
4107 // either a constant integer expression or an integer-typed parameter that is
4108 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00004109 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004110 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4111 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00004112 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004113 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4114 ++MI;
4115 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004116 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4117 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4118 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004119 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4120 FD->getParamDecl(PVD->getFunctionScopeIndex())
4121 ->getCanonicalDecl() == CanonPVD) {
4122 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4123 // A list-item cannot appear in more than one linear clause.
4124 if (LinearArgs.count(CanonPVD) > 0) {
4125 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4126 << getOpenMPClauseName(OMPC_linear)
4127 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4128 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4129 diag::note_omp_explicit_dsa)
4130 << getOpenMPClauseName(OMPC_linear);
4131 continue;
4132 }
4133 // Each argument can appear in at most one uniform or linear clause.
4134 if (UniformedArgs.count(CanonPVD) > 0) {
4135 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4136 << getOpenMPClauseName(OMPC_linear)
4137 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4138 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4139 diag::note_omp_explicit_dsa)
4140 << getOpenMPClauseName(OMPC_uniform);
4141 continue;
4142 }
4143 LinearArgs[CanonPVD] = E;
4144 if (E->isValueDependent() || E->isTypeDependent() ||
4145 E->isInstantiationDependent() ||
4146 E->containsUnexpandedParameterPack())
4147 continue;
4148 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4149 PVD->getOriginalType());
4150 continue;
4151 }
4152 }
4153 if (isa<CXXThisExpr>(E)) {
4154 if (UniformedLinearThis) {
4155 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4156 << getOpenMPClauseName(OMPC_linear)
4157 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4158 << E->getSourceRange();
4159 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4160 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4161 : OMPC_linear);
4162 continue;
4163 }
4164 UniformedLinearThis = E;
4165 if (E->isValueDependent() || E->isTypeDependent() ||
4166 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4167 continue;
4168 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4169 E->getType());
4170 continue;
4171 }
4172 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4173 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4174 }
4175 Expr *Step = nullptr;
4176 Expr *NewStep = nullptr;
4177 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00004178 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004179 // Skip the same step expression, it was checked already.
4180 if (Step == E || !E) {
4181 NewSteps.push_back(E ? NewStep : nullptr);
4182 continue;
4183 }
4184 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00004185 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4186 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4187 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004188 if (UniformedArgs.count(CanonPVD) == 0) {
4189 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4190 << Step->getSourceRange();
4191 } else if (E->isValueDependent() || E->isTypeDependent() ||
4192 E->isInstantiationDependent() ||
4193 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00004194 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004195 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00004196 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004197 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4198 << Step->getSourceRange();
4199 }
4200 continue;
4201 }
4202 NewStep = Step;
4203 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4204 !Step->isInstantiationDependent() &&
4205 !Step->containsUnexpandedParameterPack()) {
4206 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4207 .get();
4208 if (NewStep)
4209 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4210 }
4211 NewSteps.push_back(NewStep);
4212 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004213 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4214 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00004215 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00004216 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4217 const_cast<Expr **>(Linears.data()), Linears.size(),
4218 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4219 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004220 ADecl->addAttr(NewAttr);
4221 return ConvertDeclToDeclGroup(ADecl);
4222}
4223
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004224StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
4225 Stmt *AStmt,
4226 SourceLocation StartLoc,
4227 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004228 if (!AStmt)
4229 return StmtError();
4230
Alexey Bataeve3727102018-04-18 15:57:46 +00004231 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00004232 // 1.2.2 OpenMP Language Terminology
4233 // Structured block - An executable statement with a single entry at the
4234 // top and a single exit at the bottom.
4235 // The point of exit cannot be a branch out of the structured block.
4236 // longjmp() and throw() must not violate the entry/exit criteria.
4237 CS->getCapturedDecl()->setNothrow();
4238
Reid Kleckner87a31802018-03-12 21:43:02 +00004239 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004240
Alexey Bataev25e5b442015-09-15 12:52:43 +00004241 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4242 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004243}
4244
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004245namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004246/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004247/// extracting iteration space of each loop in the loop nest, that will be used
4248/// for IR generation.
4249class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004250 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004251 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004252 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004253 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004254 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004255 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004256 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004257 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004258 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004259 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004260 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004261 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004262 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004263 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004264 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004265 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004266 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004267 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004268 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004269 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004270 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004271 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004272 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004273 /// Var < UB
4274 /// Var <= UB
4275 /// UB > Var
4276 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00004277 /// This will have no value when the condition is !=
4278 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004279 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004280 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004281 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004282 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004283
4284public:
4285 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004286 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004287 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004288 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00004289 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004290 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004291 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00004292 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004293 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004294 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00004295 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004296 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004297 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004298 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004299 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004300 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004301 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004302 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00004303 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004304 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004305 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004306 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00004307 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00004308 /// True, if the compare operator is strict (<, > or !=).
4309 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004310 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004311 Expr *buildNumIterations(
4312 Scope *S, const bool LimitedType,
4313 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004314 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00004315 Expr *
4316 buildPreCond(Scope *S, Expr *Cond,
4317 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004318 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004319 DeclRefExpr *
4320 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4321 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004322 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00004323 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004324 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004325 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004326 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004327 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004328 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004329 /// Build loop data with counter value for depend clauses in ordered
4330 /// directives.
4331 Expr *
4332 buildOrderedLoopData(Scope *S, Expr *Counter,
4333 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4334 SourceLocation Loc, Expr *Inc = nullptr,
4335 OverloadedOperatorKind OOK = OO_Amp);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004336 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00004337 bool dependent() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004338
4339private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004340 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004341 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00004342 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004343 /// Helper to set loop counter variable and its initializer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004344 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004345 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00004346 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4347 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004348 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004349 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004350};
4351
Alexey Bataeve3727102018-04-18 15:57:46 +00004352bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004353 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004354 assert(!LB && !UB && !Step);
4355 return false;
4356 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004357 return LCDecl->getType()->isDependentType() ||
4358 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4359 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004360}
4361
Alexey Bataeve3727102018-04-18 15:57:46 +00004362bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004363 Expr *NewLCRefExpr,
4364 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004365 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004366 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00004367 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004368 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004369 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004370 LCDecl = getCanonicalDecl(NewLCDecl);
4371 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004372 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4373 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004374 if ((Ctor->isCopyOrMoveConstructor() ||
4375 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4376 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004377 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004378 LB = NewLB;
4379 return false;
4380}
4381
Alexey Bataev316ccf62019-01-29 18:51:58 +00004382bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4383 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00004384 bool StrictOp, SourceRange SR,
4385 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004386 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004387 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4388 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004389 if (!NewUB)
4390 return true;
4391 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00004392 if (LessOp)
4393 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004394 TestIsStrictOp = StrictOp;
4395 ConditionSrcRange = SR;
4396 ConditionLoc = SL;
4397 return false;
4398}
4399
Alexey Bataeve3727102018-04-18 15:57:46 +00004400bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004401 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004402 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004403 if (!NewStep)
4404 return true;
4405 if (!NewStep->isValueDependent()) {
4406 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004407 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00004408 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4409 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004410 if (Val.isInvalid())
4411 return true;
4412 NewStep = Val.get();
4413
4414 // OpenMP [2.6, Canonical Loop Form, Restrictions]
4415 // If test-expr is of form var relational-op b and relational-op is < or
4416 // <= then incr-expr must cause var to increase on each iteration of the
4417 // loop. If test-expr is of form var relational-op b and relational-op is
4418 // > or >= then incr-expr must cause var to decrease on each iteration of
4419 // the loop.
4420 // If test-expr is of form b relational-op var and relational-op is < or
4421 // <= then incr-expr must cause var to decrease on each iteration of the
4422 // loop. If test-expr is of form b relational-op var and relational-op is
4423 // > or >= then incr-expr must cause var to increase on each iteration of
4424 // the loop.
4425 llvm::APSInt Result;
4426 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4427 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4428 bool IsConstNeg =
4429 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004430 bool IsConstPos =
4431 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004432 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00004433
4434 // != with increment is treated as <; != with decrement is treated as >
4435 if (!TestIsLessOp.hasValue())
4436 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004437 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004438 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004439 (IsConstNeg || (IsUnsigned && Subtract)) :
4440 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004441 SemaRef.Diag(NewStep->getExprLoc(),
4442 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004443 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004444 SemaRef.Diag(ConditionLoc,
4445 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004446 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004447 return true;
4448 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00004449 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00004450 NewStep =
4451 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4452 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004453 Subtract = !Subtract;
4454 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004455 }
4456
4457 Step = NewStep;
4458 SubtractStep = Subtract;
4459 return false;
4460}
4461
Alexey Bataeve3727102018-04-18 15:57:46 +00004462bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004463 // Check init-expr for canonical loop form and save loop counter
4464 // variable - #Var and its initialization value - #LB.
4465 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4466 // var = lb
4467 // integer-type var = lb
4468 // random-access-iterator-type var = lb
4469 // pointer-type var = lb
4470 //
4471 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00004472 if (EmitDiags) {
4473 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4474 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004475 return true;
4476 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004477 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4478 if (!ExprTemp->cleanupsHaveSideEffects())
4479 S = ExprTemp->getSubExpr();
4480
Alexander Musmana5f070a2014-10-01 06:03:56 +00004481 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004482 if (Expr *E = dyn_cast<Expr>(S))
4483 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004484 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004485 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004486 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004487 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4488 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4489 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004490 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4491 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004492 }
4493 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4494 if (ME->isArrow() &&
4495 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004496 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004497 }
4498 }
David Majnemer9d168222016-08-05 17:44:54 +00004499 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004500 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00004501 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00004502 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004503 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00004504 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004505 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004506 diag::ext_omp_loop_not_canonical_init)
4507 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00004508 return setLCDeclAndLB(
4509 Var,
4510 buildDeclRefExpr(SemaRef, Var,
4511 Var->getType().getNonReferenceType(),
4512 DS->getBeginLoc()),
4513 Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004514 }
4515 }
4516 }
David Majnemer9d168222016-08-05 17:44:54 +00004517 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004518 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004519 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00004520 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004521 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4522 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004523 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4524 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004525 }
4526 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4527 if (ME->isArrow() &&
4528 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004529 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004530 }
4531 }
4532 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004533
Alexey Bataeve3727102018-04-18 15:57:46 +00004534 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004535 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00004536 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004537 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00004538 << S->getSourceRange();
4539 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004540 return true;
4541}
4542
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004543/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004544/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00004545static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004546 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00004547 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004548 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00004549 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004550 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004551 if ((Ctor->isCopyOrMoveConstructor() ||
4552 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4553 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004554 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004555 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4556 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004557 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004558 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004559 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004560 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4561 return getCanonicalDecl(ME->getMemberDecl());
4562 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004563}
4564
Alexey Bataeve3727102018-04-18 15:57:46 +00004565bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004566 // Check test-expr for canonical form, save upper-bound UB, flags for
4567 // less/greater and for strict/non-strict comparison.
4568 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4569 // var relational-op b
4570 // b relational-op var
4571 //
4572 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004573 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004574 return true;
4575 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004576 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004577 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00004578 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004579 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004580 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4581 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004582 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4583 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4584 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004585 if (getInitLCDecl(BO->getRHS()) == LCDecl)
4586 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004587 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4588 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4589 BO->getSourceRange(), BO->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00004590 } else if (BO->getOpcode() == BO_NE)
4591 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
4592 BO->getRHS() : BO->getLHS(),
4593 /*LessOp=*/llvm::None,
4594 /*StrictOp=*/true,
4595 BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00004596 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004597 if (CE->getNumArgs() == 2) {
4598 auto Op = CE->getOperator();
4599 switch (Op) {
4600 case OO_Greater:
4601 case OO_GreaterEqual:
4602 case OO_Less:
4603 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004604 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4605 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004606 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4607 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004608 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4609 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004610 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4611 CE->getOperatorLoc());
4612 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004613 case OO_ExclaimEqual:
Kelvin Liefbe4af2018-11-21 19:10:48 +00004614 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
4615 CE->getArg(1) : CE->getArg(0),
4616 /*LessOp=*/llvm::None,
4617 /*StrictOp=*/true,
4618 CE->getSourceRange(),
4619 CE->getOperatorLoc());
4620 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004621 default:
4622 break;
4623 }
4624 }
4625 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004626 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004627 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004628 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004629 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004630 return true;
4631}
4632
Alexey Bataeve3727102018-04-18 15:57:46 +00004633bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004634 // RHS of canonical loop form increment can be:
4635 // var + incr
4636 // incr + var
4637 // var - incr
4638 //
4639 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00004640 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004641 if (BO->isAdditiveOp()) {
4642 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00004643 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4644 return setStep(BO->getRHS(), !IsAdd);
4645 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4646 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004647 }
David Majnemer9d168222016-08-05 17:44:54 +00004648 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004649 bool IsAdd = CE->getOperator() == OO_Plus;
4650 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004651 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4652 return setStep(CE->getArg(1), !IsAdd);
4653 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4654 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004655 }
4656 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004657 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004658 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004659 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004660 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004661 return true;
4662}
4663
Alexey Bataeve3727102018-04-18 15:57:46 +00004664bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004665 // Check incr-expr for canonical loop form and return true if it
4666 // does not conform.
4667 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4668 // ++var
4669 // var++
4670 // --var
4671 // var--
4672 // var += incr
4673 // var -= incr
4674 // var = var + incr
4675 // var = incr + var
4676 // var = var - incr
4677 //
4678 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004679 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004680 return true;
4681 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004682 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4683 if (!ExprTemp->cleanupsHaveSideEffects())
4684 S = ExprTemp->getSubExpr();
4685
Alexander Musmana5f070a2014-10-01 06:03:56 +00004686 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004687 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004688 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004689 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00004690 getInitLCDecl(UO->getSubExpr()) == LCDecl)
4691 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004692 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004693 (UO->isDecrementOp() ? -1 : 1))
4694 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004695 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00004696 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004697 switch (BO->getOpcode()) {
4698 case BO_AddAssign:
4699 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004700 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4701 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004702 break;
4703 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004704 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4705 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004706 break;
4707 default:
4708 break;
4709 }
David Majnemer9d168222016-08-05 17:44:54 +00004710 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004711 switch (CE->getOperator()) {
4712 case OO_PlusPlus:
4713 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00004714 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4715 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00004716 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004717 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004718 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4719 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004720 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004721 break;
4722 case OO_PlusEqual:
4723 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004724 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4725 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004726 break;
4727 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00004728 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4729 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004730 break;
4731 default:
4732 break;
4733 }
4734 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004735 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004736 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004737 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004738 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004739 return true;
4740}
Alexander Musmana5f070a2014-10-01 06:03:56 +00004741
Alexey Bataev5a3af132016-03-29 08:58:54 +00004742static ExprResult
4743tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00004744 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00004745 if (SemaRef.CurContext->isDependentContext())
4746 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004747 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4748 return SemaRef.PerformImplicitConversion(
4749 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4750 /*AllowExplicit=*/true);
4751 auto I = Captures.find(Capture);
4752 if (I != Captures.end())
4753 return buildCapture(SemaRef, Capture, I->second);
4754 DeclRefExpr *Ref = nullptr;
4755 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4756 Captures[Capture] = Ref;
4757 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004758}
4759
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004760/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004761Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004762 Scope *S, const bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00004763 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004764 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00004765 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004766 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004767 SemaRef.getLangOpts().CPlusPlus) {
4768 // Upper - Lower
Kelvin Liefbe4af2018-11-21 19:10:48 +00004769 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
4770 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004771 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4772 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004773 if (!Upper || !Lower)
4774 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004775
4776 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4777
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004778 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004779 // BuildBinOp already emitted error, this one is to point user to upper
4780 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004781 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004782 << Upper->getSourceRange() << Lower->getSourceRange();
4783 return nullptr;
4784 }
4785 }
4786
4787 if (!Diff.isUsable())
4788 return nullptr;
4789
4790 // Upper - Lower [- 1]
4791 if (TestIsStrictOp)
4792 Diff = SemaRef.BuildBinOp(
4793 S, DefaultLoc, BO_Sub, Diff.get(),
4794 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4795 if (!Diff.isUsable())
4796 return nullptr;
4797
4798 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00004799 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004800 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004801 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004802 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004803 if (!Diff.isUsable())
4804 return nullptr;
4805
4806 // Parentheses (for dumping/debugging purposes only).
4807 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4808 if (!Diff.isUsable())
4809 return nullptr;
4810
4811 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004812 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004813 if (!Diff.isUsable())
4814 return nullptr;
4815
Alexander Musman174b3ca2014-10-06 11:16:29 +00004816 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004817 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00004818 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004819 bool UseVarType = VarType->hasIntegerRepresentation() &&
4820 C.getTypeSize(Type) > C.getTypeSize(VarType);
4821 if (!Type->isIntegerType() || UseVarType) {
4822 unsigned NewSize =
4823 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4824 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4825 : Type->hasSignedIntegerRepresentation();
4826 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004827 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4828 Diff = SemaRef.PerformImplicitConversion(
4829 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4830 if (!Diff.isUsable())
4831 return nullptr;
4832 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004833 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004834 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004835 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4836 if (NewSize != C.getTypeSize(Type)) {
4837 if (NewSize < C.getTypeSize(Type)) {
4838 assert(NewSize == 64 && "incorrect loop var size");
4839 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4840 << InitSrcRange << ConditionSrcRange;
4841 }
4842 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004843 NewSize, Type->hasSignedIntegerRepresentation() ||
4844 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004845 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4846 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4847 Sema::AA_Converting, true);
4848 if (!Diff.isUsable())
4849 return nullptr;
4850 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004851 }
4852 }
4853
Alexander Musmana5f070a2014-10-01 06:03:56 +00004854 return Diff.get();
4855}
4856
Alexey Bataeve3727102018-04-18 15:57:46 +00004857Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004858 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00004859 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004860 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4861 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4862 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004863
Alexey Bataeve3727102018-04-18 15:57:46 +00004864 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4865 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004866 if (!NewLB.isUsable() || !NewUB.isUsable())
4867 return nullptr;
4868
Alexey Bataeve3727102018-04-18 15:57:46 +00004869 ExprResult CondExpr =
4870 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004871 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004872 (TestIsStrictOp ? BO_LT : BO_LE) :
4873 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00004874 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004875 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004876 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4877 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004878 CondExpr = SemaRef.PerformImplicitConversion(
4879 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4880 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004881 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004882 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00004883 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004884 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4885}
4886
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004887/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004888DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00004889 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4890 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004891 auto *VD = dyn_cast<VarDecl>(LCDecl);
4892 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004893 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4894 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004895 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004896 const DSAStackTy::DSAVarData Data =
4897 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004898 // If the loop control decl is explicitly marked as private, do not mark it
4899 // as captured again.
4900 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4901 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004902 return Ref;
4903 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00004904 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00004905}
4906
Alexey Bataeve3727102018-04-18 15:57:46 +00004907Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004908 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004909 QualType Type = LCDecl->getType().getNonReferenceType();
4910 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004911 SemaRef, DefaultLoc, Type, LCDecl->getName(),
4912 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4913 isa<VarDecl>(LCDecl)
4914 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4915 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004916 if (PrivateVar->isInvalidDecl())
4917 return nullptr;
4918 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4919 }
4920 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004921}
4922
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004923/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004924Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004925
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004926/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004927Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004928
Alexey Bataevf138fda2018-08-13 19:04:24 +00004929Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
4930 Scope *S, Expr *Counter,
4931 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
4932 Expr *Inc, OverloadedOperatorKind OOK) {
4933 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
4934 if (!Cnt)
4935 return nullptr;
4936 if (Inc) {
4937 assert((OOK == OO_Plus || OOK == OO_Minus) &&
4938 "Expected only + or - operations for depend clauses.");
4939 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
4940 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
4941 if (!Cnt)
4942 return nullptr;
4943 }
4944 ExprResult Diff;
4945 QualType VarType = LCDecl->getType().getNonReferenceType();
4946 if (VarType->isIntegerType() || VarType->isPointerType() ||
4947 SemaRef.getLangOpts().CPlusPlus) {
4948 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00004949 Expr *Upper = TestIsLessOp.getValue()
4950 ? Cnt
4951 : tryBuildCapture(SemaRef, UB, Captures).get();
4952 Expr *Lower = TestIsLessOp.getValue()
4953 ? tryBuildCapture(SemaRef, LB, Captures).get()
4954 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004955 if (!Upper || !Lower)
4956 return nullptr;
4957
4958 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4959
4960 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4961 // BuildBinOp already emitted error, this one is to point user to upper
4962 // and lower bound, and to tell what is passed to 'operator-'.
4963 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4964 << Upper->getSourceRange() << Lower->getSourceRange();
4965 return nullptr;
4966 }
4967 }
4968
4969 if (!Diff.isUsable())
4970 return nullptr;
4971
4972 // Parentheses (for dumping/debugging purposes only).
4973 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4974 if (!Diff.isUsable())
4975 return nullptr;
4976
4977 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4978 if (!NewStep.isUsable())
4979 return nullptr;
4980 // (Upper - Lower) / Step
4981 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4982 if (!Diff.isUsable())
4983 return nullptr;
4984
4985 return Diff.get();
4986}
4987
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004988/// Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004989struct LoopIterationSpace final {
Alexey Bataev316ccf62019-01-29 18:51:58 +00004990 /// True if the condition operator is the strict compare operator (<, > or
4991 /// !=).
4992 bool IsStrictCompare = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004993 /// Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004994 Expr *PreCond = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004995 /// This expression calculates the number of iterations in the loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004996 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004997 Expr *NumIterations = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004998 /// The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004999 Expr *CounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005000 /// Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00005001 Expr *PrivateCounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005002 /// This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00005003 Expr *CounterInit = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005004 /// This is step for the #CounterVar used to generate its update:
Alexander Musmana5f070a2014-10-01 06:03:56 +00005005 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00005006 Expr *CounterStep = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005007 /// Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00005008 bool Subtract = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005009 /// Source range of the loop init.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005010 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005011 /// Source range of the loop condition.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005012 SourceRange CondSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005013 /// Source range of the loop increment.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005014 SourceRange IncSrcRange;
5015};
5016
Alexey Bataev23b69422014-06-18 07:08:49 +00005017} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005018
Alexey Bataev9c821032015-04-30 04:23:23 +00005019void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
5020 assert(getLangOpts().OpenMP && "OpenMP is not active.");
5021 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005022 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
5023 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00005024 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00005025 DSAStack->loopStart();
Alexey Bataev9c821032015-04-30 04:23:23 +00005026 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00005027 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
5028 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005029 auto *VD = dyn_cast<VarDecl>(D);
5030 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005031 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005032 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00005033 } else {
5034 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
5035 /*WithInit=*/false);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005036 VD = cast<VarDecl>(Ref->getDecl());
5037 }
5038 }
5039 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005040 const Decl *LD = DSAStack->getPossiblyLoopCunter();
5041 if (LD != D->getCanonicalDecl()) {
5042 DSAStack->resetPossibleLoopCounter();
5043 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
5044 MarkDeclarationsReferencedInExpr(
5045 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
5046 Var->getType().getNonLValueExprType(Context),
5047 ForLoc, /*RefersToCapture=*/true));
5048 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005049 }
5050 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005051 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00005052 }
5053}
5054
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005055/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005056/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00005057static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00005058 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
5059 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00005060 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
5061 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00005062 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005063 LoopIterationSpace &ResultIterSpace,
Alexey Bataeve3727102018-04-18 15:57:46 +00005064 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005065 // OpenMP [2.6, Canonical Loop Form]
5066 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00005067 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005068 if (!For) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005069 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005070 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00005071 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00005072 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005073 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005074 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
5075 SemaRef.Diag(DSA.getConstructLoc(),
5076 diag::note_omp_collapse_ordered_expr)
5077 << 2 << CollapseLoopCountExpr->getSourceRange()
5078 << OrderedLoopCountExpr->getSourceRange();
5079 else if (CollapseLoopCountExpr)
5080 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5081 diag::note_omp_collapse_ordered_expr)
5082 << 0 << CollapseLoopCountExpr->getSourceRange();
5083 else
5084 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5085 diag::note_omp_collapse_ordered_expr)
5086 << 1 << OrderedLoopCountExpr->getSourceRange();
5087 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005088 return true;
5089 }
5090 assert(For->getBody());
5091
5092 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
5093
5094 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005095 Stmt *Init = For->getInit();
5096 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005097 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005098
5099 bool HasErrors = false;
5100
5101 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005102 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
5103 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005104
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005105 // OpenMP [2.6, Canonical Loop Form]
5106 // Var is one of the following:
5107 // A variable of signed or unsigned integer type.
5108 // For C++, a variable of a random access iterator type.
5109 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005110 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005111 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
5112 !VarType->isPointerType() &&
5113 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005114 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005115 << SemaRef.getLangOpts().CPlusPlus;
5116 HasErrors = true;
5117 }
5118
5119 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
5120 // a Construct
5121 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5122 // parallel for construct is (are) private.
5123 // The loop iteration variable in the associated for-loop of a simd
5124 // construct with just one associated for-loop is linear with a
5125 // constant-linear-step that is the increment of the associated for-loop.
5126 // Exclude loop var from the list of variables with implicitly defined data
5127 // sharing attributes.
5128 VarsWithImplicitDSA.erase(LCDecl);
5129
5130 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5131 // in a Construct, C/C++].
5132 // The loop iteration variable in the associated for-loop of a simd
5133 // construct with just one associated for-loop may be listed in a linear
5134 // clause with a constant-linear-step that is the increment of the
5135 // associated for-loop.
5136 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5137 // parallel for construct may be listed in a private or lastprivate clause.
5138 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
5139 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
5140 // declared in the loop and it is predetermined as a private.
Alexey Bataeve3727102018-04-18 15:57:46 +00005141 OpenMPClauseKind PredeterminedCKind =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005142 isOpenMPSimdDirective(DKind)
5143 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
5144 : OMPC_private;
5145 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5146 DVar.CKind != PredeterminedCKind) ||
5147 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
5148 isOpenMPDistributeDirective(DKind)) &&
5149 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5150 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
5151 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005152 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005153 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
5154 << getOpenMPClauseName(PredeterminedCKind);
5155 if (DVar.RefExpr == nullptr)
5156 DVar.CKind = PredeterminedCKind;
Alexey Bataeve3727102018-04-18 15:57:46 +00005157 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005158 HasErrors = true;
5159 } else if (LoopDeclRefExpr != nullptr) {
5160 // Make the loop iteration variable private (for worksharing constructs),
5161 // linear (for simd directives with the only one associated loop) or
5162 // lastprivate (for simd directives with several collapsed or ordered
5163 // loops).
5164 if (DVar.CKind == OMPC_unknown)
Alexey Bataevc2cdff62019-01-29 21:12:28 +00005165 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005166 }
5167
5168 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
5169
5170 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005171 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005172
5173 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005174 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005175 }
5176
Alexey Bataeve3727102018-04-18 15:57:46 +00005177 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005178 return HasErrors;
5179
Alexander Musmana5f070a2014-10-01 06:03:56 +00005180 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005181 ResultIterSpace.PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00005182 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
5183 ResultIterSpace.NumIterations = ISC.buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005184 DSA.getCurScope(),
5185 (isOpenMPWorksharingDirective(DKind) ||
5186 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
5187 Captures);
Alexey Bataeve3727102018-04-18 15:57:46 +00005188 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
5189 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
5190 ResultIterSpace.CounterInit = ISC.buildCounterInit();
5191 ResultIterSpace.CounterStep = ISC.buildCounterStep();
5192 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
5193 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
5194 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
5195 ResultIterSpace.Subtract = ISC.shouldSubtractStep();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005196 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005197
Alexey Bataev62dbb972015-04-22 11:59:37 +00005198 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
5199 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005200 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00005201 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005202 ResultIterSpace.CounterInit == nullptr ||
5203 ResultIterSpace.CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00005204 if (!HasErrors && DSA.isOrderedRegion()) {
5205 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
5206 if (CurrentNestedLoopCount <
5207 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
5208 DSA.getOrderedRegionParam().second->setLoopNumIterations(
5209 CurrentNestedLoopCount, ResultIterSpace.NumIterations);
5210 DSA.getOrderedRegionParam().second->setLoopCounter(
5211 CurrentNestedLoopCount, ResultIterSpace.CounterVar);
5212 }
5213 }
5214 for (auto &Pair : DSA.getDoacrossDependClauses()) {
5215 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
5216 // Erroneous case - clause has some problems.
5217 continue;
5218 }
5219 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
5220 Pair.second.size() <= CurrentNestedLoopCount) {
5221 // Erroneous case - clause has some problems.
5222 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
5223 continue;
5224 }
5225 Expr *CntValue;
5226 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5227 CntValue = ISC.buildOrderedLoopData(
5228 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5229 Pair.first->getDependencyLoc());
5230 else
5231 CntValue = ISC.buildOrderedLoopData(
5232 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5233 Pair.first->getDependencyLoc(),
5234 Pair.second[CurrentNestedLoopCount].first,
5235 Pair.second[CurrentNestedLoopCount].second);
5236 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
5237 }
5238 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005239
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005240 return HasErrors;
5241}
5242
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005243/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005244static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00005245buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005246 ExprResult Start,
Alexey Bataeve3727102018-04-18 15:57:46 +00005247 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005248 // Build 'VarRef = Start.
Alexey Bataeve3727102018-04-18 15:57:46 +00005249 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005250 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005251 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00005252 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00005253 VarRef.get()->getType())) {
5254 NewStart = SemaRef.PerformImplicitConversion(
5255 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
5256 /*AllowExplicit=*/true);
5257 if (!NewStart.isUsable())
5258 return ExprError();
5259 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005260
Alexey Bataeve3727102018-04-18 15:57:46 +00005261 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005262 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5263 return Init;
5264}
5265
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005266/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00005267static ExprResult buildCounterUpdate(
5268 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5269 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
5270 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005271 // Add parentheses (for debugging purposes only).
5272 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
5273 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
5274 !Step.isUsable())
5275 return ExprError();
5276
Alexey Bataev5a3af132016-03-29 08:58:54 +00005277 ExprResult NewStep = Step;
5278 if (Captures)
5279 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005280 if (NewStep.isInvalid())
5281 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005282 ExprResult Update =
5283 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005284 if (!Update.isUsable())
5285 return ExprError();
5286
Alexey Bataevc0214e02016-02-16 12:13:49 +00005287 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
5288 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005289 ExprResult NewStart = Start;
5290 if (Captures)
5291 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005292 if (NewStart.isInvalid())
5293 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005294
Alexey Bataevc0214e02016-02-16 12:13:49 +00005295 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5296 ExprResult SavedUpdate = Update;
5297 ExprResult UpdateVal;
5298 if (VarRef.get()->getType()->isOverloadableType() ||
5299 NewStart.get()->getType()->isOverloadableType() ||
5300 Update.get()->getType()->isOverloadableType()) {
5301 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5302 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5303 Update =
5304 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5305 if (Update.isUsable()) {
5306 UpdateVal =
5307 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5308 VarRef.get(), SavedUpdate.get());
5309 if (UpdateVal.isUsable()) {
5310 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5311 UpdateVal.get());
5312 }
5313 }
5314 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5315 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005316
Alexey Bataevc0214e02016-02-16 12:13:49 +00005317 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5318 if (!Update.isUsable() || !UpdateVal.isUsable()) {
5319 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5320 NewStart.get(), SavedUpdate.get());
5321 if (!Update.isUsable())
5322 return ExprError();
5323
Alexey Bataev11481f52016-02-17 10:29:05 +00005324 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5325 VarRef.get()->getType())) {
5326 Update = SemaRef.PerformImplicitConversion(
5327 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5328 if (!Update.isUsable())
5329 return ExprError();
5330 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00005331
5332 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5333 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005334 return Update;
5335}
5336
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005337/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005338/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005339static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005340 if (E == nullptr)
5341 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00005342 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005343 QualType OldType = E->getType();
5344 unsigned HasBits = C.getTypeSize(OldType);
5345 if (HasBits >= Bits)
5346 return ExprResult(E);
5347 // OK to convert to signed, because new type has more bits than old.
5348 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5349 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5350 true);
5351}
5352
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005353/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005354/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005355static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005356 if (E == nullptr)
5357 return false;
5358 llvm::APSInt Result;
5359 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5360 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5361 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005362}
5363
Alexey Bataev5a3af132016-03-29 08:58:54 +00005364/// Build preinits statement for the given declarations.
5365static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00005366 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005367 if (!PreInits.empty()) {
5368 return new (Context) DeclStmt(
5369 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5370 SourceLocation(), SourceLocation());
5371 }
5372 return nullptr;
5373}
5374
5375/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00005376static Stmt *
5377buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00005378 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005379 if (!Captures.empty()) {
5380 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00005381 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00005382 PreInits.push_back(Pair.second->getDecl());
5383 return buildPreInits(Context, PreInits);
5384 }
5385 return nullptr;
5386}
5387
5388/// Build postupdate expression for the given list of postupdates expressions.
5389static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5390 Expr *PostUpdate = nullptr;
5391 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005392 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005393 Expr *ConvE = S.BuildCStyleCastExpr(
5394 E->getExprLoc(),
5395 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5396 E->getExprLoc(), E)
5397 .get();
5398 PostUpdate = PostUpdate
5399 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5400 PostUpdate, ConvE)
5401 .get()
5402 : ConvE;
5403 }
5404 }
5405 return PostUpdate;
5406}
5407
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005408/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00005409/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5410/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005411static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00005412checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00005413 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5414 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00005415 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00005416 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005417 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005418 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005419 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005420 Expr::EvalResult Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005421 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Fangrui Song407659a2018-11-30 23:41:18 +00005422 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005423 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005424 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005425 if (OrderedLoopCountExpr) {
5426 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005427 Expr::EvalResult EVResult;
5428 if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5429 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005430 if (Result.getLimitedValue() < NestedLoopCount) {
5431 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5432 diag::err_omp_wrong_ordered_loop_count)
5433 << OrderedLoopCountExpr->getSourceRange();
5434 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5435 diag::note_collapse_loop_count)
5436 << CollapseLoopCountExpr->getSourceRange();
5437 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005438 OrderedLoopCount = Result.getLimitedValue();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005439 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005440 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005441 // This is helper routine for loop directives (e.g., 'for', 'simd',
5442 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00005443 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00005444 SmallVector<LoopIterationSpace, 4> IterSpaces(
5445 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00005446 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005447 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005448 if (checkOpenMPIterationSpace(
5449 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5450 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5451 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5452 Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00005453 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005454 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005455 // OpenMP [2.8.1, simd construct, Restrictions]
5456 // All loops associated with the construct must be perfectly nested; that
5457 // is, there must be no intervening code nor any OpenMP directive between
5458 // any two loops.
5459 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005460 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005461 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5462 if (checkOpenMPIterationSpace(
5463 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5464 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5465 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5466 Captures))
5467 return 0;
5468 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5469 // Handle initialization of captured loop iterator variables.
5470 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5471 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5472 Captures[DRE] = DRE;
5473 }
5474 }
5475 // Move on to the next nested for loop, or to the loop body.
5476 // OpenMP [2.8.1, simd construct, Restrictions]
5477 // All loops associated with the construct must be perfectly nested; that
5478 // is, there must be no intervening code nor any OpenMP directive between
5479 // any two loops.
5480 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5481 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005482
Alexander Musmana5f070a2014-10-01 06:03:56 +00005483 Built.clear(/* size */ NestedLoopCount);
5484
5485 if (SemaRef.CurContext->isDependentContext())
5486 return NestedLoopCount;
5487
5488 // An example of what is generated for the following code:
5489 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00005490 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00005491 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005492 // for (k = 0; k < NK; ++k)
5493 // for (j = J0; j < NJ; j+=2) {
5494 // <loop body>
5495 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005496 //
5497 // We generate the code below.
5498 // Note: the loop body may be outlined in CodeGen.
5499 // Note: some counters may be C++ classes, operator- is used to find number of
5500 // iterations and operator+= to calculate counter value.
5501 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5502 // or i64 is currently supported).
5503 //
5504 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5505 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5506 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5507 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5508 // // similar updates for vars in clauses (e.g. 'linear')
5509 // <loop body (using local i and j)>
5510 // }
5511 // i = NI; // assign final values of counters
5512 // j = NJ;
5513 //
5514
5515 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5516 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00005517 // Precondition tests if there is at least one iteration (all conditions are
5518 // true).
5519 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00005520 Expr *N0 = IterSpaces[0].NumIterations;
5521 ExprResult LastIteration32 =
5522 widenIterationCount(/*Bits=*/32,
5523 SemaRef
5524 .PerformImplicitConversion(
5525 N0->IgnoreImpCasts(), N0->getType(),
5526 Sema::AA_Converting, /*AllowExplicit=*/true)
5527 .get(),
5528 SemaRef);
5529 ExprResult LastIteration64 = widenIterationCount(
5530 /*Bits=*/64,
5531 SemaRef
5532 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5533 Sema::AA_Converting,
5534 /*AllowExplicit=*/true)
5535 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005536 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005537
5538 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5539 return NestedLoopCount;
5540
Alexey Bataeve3727102018-04-18 15:57:46 +00005541 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005542 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5543
5544 Scope *CurScope = DSA.getCurScope();
5545 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00005546 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00005547 PreCond =
5548 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5549 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00005550 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005551 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00005552 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005553 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5554 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005555 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005556 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005557 SemaRef
5558 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5559 Sema::AA_Converting,
5560 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005561 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005562 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005563 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005564 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005565 SemaRef
5566 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5567 Sema::AA_Converting,
5568 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005569 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005570 }
5571
5572 // Choose either the 32-bit or 64-bit version.
5573 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005574 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
5575 (LastIteration32.isUsable() &&
5576 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5577 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5578 fitsInto(
5579 /*Bits=*/32,
5580 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5581 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00005582 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00005583 QualType VType = LastIteration.get()->getType();
5584 QualType RealVType = VType;
5585 QualType StrideVType = VType;
5586 if (isOpenMPTaskLoopDirective(DKind)) {
5587 VType =
5588 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5589 StrideVType =
5590 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5591 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005592
5593 if (!LastIteration.isUsable())
5594 return 0;
5595
5596 // Save the number of iterations.
5597 ExprResult NumIterations = LastIteration;
5598 {
5599 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005600 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5601 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005602 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5603 if (!LastIteration.isUsable())
5604 return 0;
5605 }
5606
5607 // Calculate the last iteration number beforehand instead of doing this on
5608 // each iteration. Do not do this if the number of iterations may be kfold-ed.
5609 llvm::APSInt Result;
5610 bool IsConstant =
5611 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5612 ExprResult CalcLastIteration;
5613 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005614 ExprResult SaveRef =
5615 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005616 LastIteration = SaveRef;
5617
5618 // Prepare SaveRef + 1.
5619 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005620 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005621 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5622 if (!NumIterations.isUsable())
5623 return 0;
5624 }
5625
5626 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5627
David Majnemer9d168222016-08-05 17:44:54 +00005628 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005629 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005630 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5631 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005632 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005633 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5634 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005635 SemaRef.AddInitializerToDecl(LBDecl,
5636 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5637 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005638
5639 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005640 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
5641 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00005642 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00005643 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005644
5645 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
5646 // This will be used to implement clause 'lastprivate'.
5647 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005648 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
5649 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005650 SemaRef.AddInitializerToDecl(ILDecl,
5651 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5652 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005653
5654 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00005655 VarDecl *STDecl =
5656 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
5657 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005658 SemaRef.AddInitializerToDecl(STDecl,
5659 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
5660 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005661
5662 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00005663 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00005664 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
5665 UB.get(), LastIteration.get());
5666 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00005667 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
5668 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00005669 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
5670 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005671 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005672
5673 // If we have a combined directive that combines 'distribute', 'for' or
5674 // 'simd' we need to be able to access the bounds of the schedule of the
5675 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
5676 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
5677 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00005678 // Lower bound variable, initialized with zero.
5679 VarDecl *CombLBDecl =
5680 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
5681 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
5682 SemaRef.AddInitializerToDecl(
5683 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5684 /*DirectInit*/ false);
5685
5686 // Upper bound variable, initialized with last iteration number.
5687 VarDecl *CombUBDecl =
5688 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
5689 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
5690 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
5691 /*DirectInit*/ false);
5692
5693 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
5694 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
5695 ExprResult CombCondOp =
5696 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
5697 LastIteration.get(), CombUB.get());
5698 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
5699 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005700 CombEUB =
5701 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005702
Alexey Bataeve3727102018-04-18 15:57:46 +00005703 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005704 // We expect to have at least 2 more parameters than the 'parallel'
5705 // directive does - the lower and upper bounds of the previous schedule.
5706 assert(CD->getNumParams() >= 4 &&
5707 "Unexpected number of parameters in loop combined directive");
5708
5709 // Set the proper type for the bounds given what we learned from the
5710 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005711 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
5712 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005713
5714 // Previous lower and upper bounds are obtained from the region
5715 // parameters.
5716 PrevLB =
5717 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
5718 PrevUB =
5719 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
5720 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005721 }
5722
5723 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005724 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005725 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005726 {
Alexey Bataev7292c292016-04-25 12:22:29 +00005727 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
5728 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00005729 Expr *RHS =
5730 (isOpenMPWorksharingDirective(DKind) ||
5731 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5732 ? LB.get()
5733 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005734 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005735 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005736
5737 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5738 Expr *CombRHS =
5739 (isOpenMPWorksharingDirective(DKind) ||
5740 isOpenMPTaskLoopDirective(DKind) ||
5741 isOpenMPDistributeDirective(DKind))
5742 ? CombLB.get()
5743 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5744 CombInit =
5745 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005746 CombInit =
5747 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005748 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005749 }
5750
Alexey Bataev316ccf62019-01-29 18:51:58 +00005751 bool UseStrictCompare =
5752 RealVType->hasUnsignedIntegerRepresentation() &&
5753 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
5754 return LIS.IsStrictCompare;
5755 });
5756 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
5757 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005758 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005759 Expr *BoundUB = UB.get();
5760 if (UseStrictCompare) {
5761 BoundUB =
5762 SemaRef
5763 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
5764 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5765 .get();
5766 BoundUB =
5767 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
5768 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005769 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005770 (isOpenMPWorksharingDirective(DKind) ||
5771 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00005772 ? SemaRef.BuildBinOp(CurScope, CondLoc,
5773 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
5774 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00005775 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5776 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005777 ExprResult CombDistCond;
5778 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005779 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5780 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005781 }
5782
Carlo Bertolliffafe102017-04-20 00:39:39 +00005783 ExprResult CombCond;
5784 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005785 Expr *BoundCombUB = CombUB.get();
5786 if (UseStrictCompare) {
5787 BoundCombUB =
5788 SemaRef
5789 .BuildBinOp(
5790 CurScope, CondLoc, BO_Add, BoundCombUB,
5791 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5792 .get();
5793 BoundCombUB =
5794 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
5795 .get();
5796 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00005797 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005798 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5799 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005800 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005801 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005802 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005803 ExprResult Inc =
5804 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5805 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5806 if (!Inc.isUsable())
5807 return 0;
5808 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005809 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005810 if (!Inc.isUsable())
5811 return 0;
5812
5813 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5814 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005815 // In combined construct, add combined version that use CombLB and CombUB
5816 // base variables for the update
5817 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005818 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5819 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005820 // LB + ST
5821 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5822 if (!NextLB.isUsable())
5823 return 0;
5824 // LB = LB + ST
5825 NextLB =
5826 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005827 NextLB =
5828 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005829 if (!NextLB.isUsable())
5830 return 0;
5831 // UB + ST
5832 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5833 if (!NextUB.isUsable())
5834 return 0;
5835 // UB = UB + ST
5836 NextUB =
5837 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005838 NextUB =
5839 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005840 if (!NextUB.isUsable())
5841 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005842 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5843 CombNextLB =
5844 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5845 if (!NextLB.isUsable())
5846 return 0;
5847 // LB = LB + ST
5848 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5849 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005850 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
5851 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005852 if (!CombNextLB.isUsable())
5853 return 0;
5854 // UB + ST
5855 CombNextUB =
5856 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5857 if (!CombNextUB.isUsable())
5858 return 0;
5859 // UB = UB + ST
5860 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5861 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005862 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
5863 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005864 if (!CombNextUB.isUsable())
5865 return 0;
5866 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005867 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005868
Carlo Bertolliffafe102017-04-20 00:39:39 +00005869 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00005870 // directive with for as IV = IV + ST; ensure upper bound expression based
5871 // on PrevUB instead of NumIterations - used to implement 'for' when found
5872 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005873 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005874 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00005875 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005876 DistCond = SemaRef.BuildBinOp(
5877 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005878 assert(DistCond.isUsable() && "distribute cond expr was not built");
5879
5880 DistInc =
5881 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5882 assert(DistInc.isUsable() && "distribute inc expr was not built");
5883 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5884 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005885 DistInc =
5886 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005887 assert(DistInc.isUsable() && "distribute inc expr was not built");
5888
5889 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5890 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005891 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005892 ExprResult IsUBGreater =
5893 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5894 ExprResult CondOp = SemaRef.ActOnConditionalOp(
5895 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5896 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5897 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005898 PrevEUB =
5899 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005900
Alexey Bataev316ccf62019-01-29 18:51:58 +00005901 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
5902 // parallel for is in combination with a distribute directive with
5903 // schedule(static, 1)
5904 Expr *BoundPrevUB = PrevUB.get();
5905 if (UseStrictCompare) {
5906 BoundPrevUB =
5907 SemaRef
5908 .BuildBinOp(
5909 CurScope, CondLoc, BO_Add, BoundPrevUB,
5910 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
5911 .get();
5912 BoundPrevUB =
5913 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
5914 .get();
5915 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005916 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00005917 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
5918 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005919 }
5920
Alexander Musmana5f070a2014-10-01 06:03:56 +00005921 // Build updates and final values of the loop counters.
5922 bool HasErrors = false;
5923 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005924 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005925 Built.Updates.resize(NestedLoopCount);
5926 Built.Finals.resize(NestedLoopCount);
5927 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005928 // We implement the following algorithm for obtaining the
5929 // original loop iteration variable values based on the
5930 // value of the collapsed loop iteration variable IV.
5931 //
5932 // Let n+1 be the number of collapsed loops in the nest.
5933 // Iteration variables (I0, I1, .... In)
5934 // Iteration counts (N0, N1, ... Nn)
5935 //
5936 // Acc = IV;
5937 //
5938 // To compute Ik for loop k, 0 <= k <= n, generate:
5939 // Prod = N(k+1) * N(k+2) * ... * Nn;
5940 // Ik = Acc / Prod;
5941 // Acc -= Ik * Prod;
5942 //
5943 ExprResult Acc = IV;
5944 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005945 LoopIterationSpace &IS = IterSpaces[Cnt];
5946 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005947 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005948
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005949 // Compute prod
5950 ExprResult Prod =
5951 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5952 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
5953 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
5954 IterSpaces[K].NumIterations);
5955
5956 // Iter = Acc / Prod
5957 // If there is at least one more inner loop to avoid
5958 // multiplication by 1.
5959 if (Cnt + 1 < NestedLoopCount)
5960 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
5961 Acc.get(), Prod.get());
5962 else
5963 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005964 if (!Iter.isUsable()) {
5965 HasErrors = true;
5966 break;
5967 }
5968
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005969 // Update Acc:
5970 // Acc -= Iter * Prod
5971 // Check if there is at least one more inner loop to avoid
5972 // multiplication by 1.
5973 if (Cnt + 1 < NestedLoopCount)
5974 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
5975 Iter.get(), Prod.get());
5976 else
5977 Prod = Iter;
5978 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
5979 Acc.get(), Prod.get());
5980
Alexey Bataev39f915b82015-05-08 10:41:21 +00005981 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005982 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00005983 DeclRefExpr *CounterVar = buildDeclRefExpr(
5984 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5985 /*RefersToCapture=*/true);
5986 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005987 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005988 if (!Init.isUsable()) {
5989 HasErrors = true;
5990 break;
5991 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005992 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005993 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5994 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005995 if (!Update.isUsable()) {
5996 HasErrors = true;
5997 break;
5998 }
5999
6000 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006001 ExprResult Final = buildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00006002 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00006003 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006004 if (!Final.isUsable()) {
6005 HasErrors = true;
6006 break;
6007 }
6008
Alexander Musmana5f070a2014-10-01 06:03:56 +00006009 if (!Update.isUsable() || !Final.isUsable()) {
6010 HasErrors = true;
6011 break;
6012 }
6013 // Save results
6014 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00006015 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006016 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006017 Built.Updates[Cnt] = Update.get();
6018 Built.Finals[Cnt] = Final.get();
6019 }
6020 }
6021
6022 if (HasErrors)
6023 return 0;
6024
6025 // Save results
6026 Built.IterationVarRef = IV.get();
6027 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00006028 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006029 Built.CalcLastIteration = SemaRef
6030 .ActOnFinishFullExpr(CalcLastIteration.get(),
6031 /*DiscardedValue*/ false)
6032 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006033 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00006034 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006035 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006036 Built.Init = Init.get();
6037 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00006038 Built.LB = LB.get();
6039 Built.UB = UB.get();
6040 Built.IL = IL.get();
6041 Built.ST = ST.get();
6042 Built.EUB = EUB.get();
6043 Built.NLB = NextLB.get();
6044 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00006045 Built.PrevLB = PrevLB.get();
6046 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00006047 Built.DistInc = DistInc.get();
6048 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00006049 Built.DistCombinedFields.LB = CombLB.get();
6050 Built.DistCombinedFields.UB = CombUB.get();
6051 Built.DistCombinedFields.EUB = CombEUB.get();
6052 Built.DistCombinedFields.Init = CombInit.get();
6053 Built.DistCombinedFields.Cond = CombCond.get();
6054 Built.DistCombinedFields.NLB = CombNextLB.get();
6055 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006056 Built.DistCombinedFields.DistCond = CombDistCond.get();
6057 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006058
Alexey Bataevabfc0692014-06-25 06:52:00 +00006059 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006060}
6061
Alexey Bataev10e775f2015-07-30 11:36:16 +00006062static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006063 auto CollapseClauses =
6064 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
6065 if (CollapseClauses.begin() != CollapseClauses.end())
6066 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006067 return nullptr;
6068}
6069
Alexey Bataev10e775f2015-07-30 11:36:16 +00006070static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006071 auto OrderedClauses =
6072 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
6073 if (OrderedClauses.begin() != OrderedClauses.end())
6074 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00006075 return nullptr;
6076}
6077
Kelvin Lic5609492016-07-15 04:39:07 +00006078static bool checkSimdlenSafelenSpecified(Sema &S,
6079 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006080 const OMPSafelenClause *Safelen = nullptr;
6081 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00006082
Alexey Bataeve3727102018-04-18 15:57:46 +00006083 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00006084 if (Clause->getClauseKind() == OMPC_safelen)
6085 Safelen = cast<OMPSafelenClause>(Clause);
6086 else if (Clause->getClauseKind() == OMPC_simdlen)
6087 Simdlen = cast<OMPSimdlenClause>(Clause);
6088 if (Safelen && Simdlen)
6089 break;
6090 }
6091
6092 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006093 const Expr *SimdlenLength = Simdlen->getSimdlen();
6094 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00006095 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
6096 SimdlenLength->isInstantiationDependent() ||
6097 SimdlenLength->containsUnexpandedParameterPack())
6098 return false;
6099 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
6100 SafelenLength->isInstantiationDependent() ||
6101 SafelenLength->containsUnexpandedParameterPack())
6102 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00006103 Expr::EvalResult SimdlenResult, SafelenResult;
6104 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
6105 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
6106 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
6107 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00006108 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
6109 // If both simdlen and safelen clauses are specified, the value of the
6110 // simdlen parameter must be less than or equal to the value of the safelen
6111 // parameter.
6112 if (SimdlenRes > SafelenRes) {
6113 S.Diag(SimdlenLength->getExprLoc(),
6114 diag::err_omp_wrong_simdlen_safelen_values)
6115 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
6116 return true;
6117 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00006118 }
6119 return false;
6120}
6121
Alexey Bataeve3727102018-04-18 15:57:46 +00006122StmtResult
6123Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6124 SourceLocation StartLoc, SourceLocation EndLoc,
6125 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006126 if (!AStmt)
6127 return StmtError();
6128
6129 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006130 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006131 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6132 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006133 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006134 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6135 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006136 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006137 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006138
Alexander Musmana5f070a2014-10-01 06:03:56 +00006139 assert((CurContext->isDependentContext() || B.builtAll()) &&
6140 "omp simd loop exprs were not built");
6141
Alexander Musman3276a272015-03-21 10:12:56 +00006142 if (!CurContext->isDependentContext()) {
6143 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006144 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006145 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00006146 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006147 B.NumIterations, *this, CurScope,
6148 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00006149 return StmtError();
6150 }
6151 }
6152
Kelvin Lic5609492016-07-15 04:39:07 +00006153 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006154 return StmtError();
6155
Reid Kleckner87a31802018-03-12 21:43:02 +00006156 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006157 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6158 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006159}
6160
Alexey Bataeve3727102018-04-18 15:57:46 +00006161StmtResult
6162Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6163 SourceLocation StartLoc, SourceLocation EndLoc,
6164 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006165 if (!AStmt)
6166 return StmtError();
6167
6168 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006169 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006170 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6171 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006172 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006173 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6174 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006175 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00006176 return StmtError();
6177
Alexander Musmana5f070a2014-10-01 06:03:56 +00006178 assert((CurContext->isDependentContext() || B.builtAll()) &&
6179 "omp for loop exprs were not built");
6180
Alexey Bataev54acd402015-08-04 11:18:19 +00006181 if (!CurContext->isDependentContext()) {
6182 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006183 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006184 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006185 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006186 B.NumIterations, *this, CurScope,
6187 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006188 return StmtError();
6189 }
6190 }
6191
Reid Kleckner87a31802018-03-12 21:43:02 +00006192 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006193 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006194 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00006195}
6196
Alexander Musmanf82886e2014-09-18 05:12:34 +00006197StmtResult Sema::ActOnOpenMPForSimdDirective(
6198 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006199 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006200 if (!AStmt)
6201 return StmtError();
6202
6203 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006204 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006205 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6206 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00006207 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006208 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006209 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6210 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006211 if (NestedLoopCount == 0)
6212 return StmtError();
6213
Alexander Musmanc6388682014-12-15 07:07:06 +00006214 assert((CurContext->isDependentContext() || B.builtAll()) &&
6215 "omp for simd loop exprs were not built");
6216
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006217 if (!CurContext->isDependentContext()) {
6218 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006219 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006220 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006221 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006222 B.NumIterations, *this, CurScope,
6223 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006224 return StmtError();
6225 }
6226 }
6227
Kelvin Lic5609492016-07-15 04:39:07 +00006228 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006229 return StmtError();
6230
Reid Kleckner87a31802018-03-12 21:43:02 +00006231 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006232 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6233 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006234}
6235
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006236StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
6237 Stmt *AStmt,
6238 SourceLocation StartLoc,
6239 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006240 if (!AStmt)
6241 return StmtError();
6242
6243 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006244 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006245 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006246 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006247 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006248 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006249 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006250 return StmtError();
6251 // All associated statements must be '#pragma omp section' except for
6252 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006253 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006254 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6255 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006256 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006257 diag::err_omp_sections_substmt_not_section);
6258 return StmtError();
6259 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006260 cast<OMPSectionDirective>(SectionStmt)
6261 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006262 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006263 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006264 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006265 return StmtError();
6266 }
6267
Reid Kleckner87a31802018-03-12 21:43:02 +00006268 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006269
Alexey Bataev25e5b442015-09-15 12:52:43 +00006270 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6271 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006272}
6273
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006274StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
6275 SourceLocation StartLoc,
6276 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006277 if (!AStmt)
6278 return StmtError();
6279
6280 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006281
Reid Kleckner87a31802018-03-12 21:43:02 +00006282 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00006283 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006284
Alexey Bataev25e5b442015-09-15 12:52:43 +00006285 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
6286 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006287}
6288
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006289StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
6290 Stmt *AStmt,
6291 SourceLocation StartLoc,
6292 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006293 if (!AStmt)
6294 return StmtError();
6295
6296 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00006297
Reid Kleckner87a31802018-03-12 21:43:02 +00006298 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00006299
Alexey Bataev3255bf32015-01-19 05:20:46 +00006300 // OpenMP [2.7.3, single Construct, Restrictions]
6301 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00006302 const OMPClause *Nowait = nullptr;
6303 const OMPClause *Copyprivate = nullptr;
6304 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00006305 if (Clause->getClauseKind() == OMPC_nowait)
6306 Nowait = Clause;
6307 else if (Clause->getClauseKind() == OMPC_copyprivate)
6308 Copyprivate = Clause;
6309 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006310 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00006311 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006312 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00006313 return StmtError();
6314 }
6315 }
6316
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006317 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6318}
6319
Alexander Musman80c22892014-07-17 08:54:58 +00006320StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6321 SourceLocation StartLoc,
6322 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006323 if (!AStmt)
6324 return StmtError();
6325
6326 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00006327
Reid Kleckner87a31802018-03-12 21:43:02 +00006328 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00006329
6330 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6331}
6332
Alexey Bataev28c75412015-12-15 08:19:24 +00006333StmtResult Sema::ActOnOpenMPCriticalDirective(
6334 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6335 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006336 if (!AStmt)
6337 return StmtError();
6338
6339 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006340
Alexey Bataev28c75412015-12-15 08:19:24 +00006341 bool ErrorFound = false;
6342 llvm::APSInt Hint;
6343 SourceLocation HintLoc;
6344 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006345 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006346 if (C->getClauseKind() == OMPC_hint) {
6347 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006348 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00006349 ErrorFound = true;
6350 }
6351 Expr *E = cast<OMPHintClause>(C)->getHint();
6352 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00006353 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006354 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006355 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00006356 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006357 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00006358 }
6359 }
6360 }
6361 if (ErrorFound)
6362 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006363 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00006364 if (Pair.first && DirName.getName() && !DependentHint) {
6365 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6366 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00006367 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00006368 Diag(HintLoc, diag::note_omp_critical_hint_here)
6369 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006370 else
Alexey Bataev28c75412015-12-15 08:19:24 +00006371 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00006372 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006373 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00006374 << 1
6375 << C->getHint()->EvaluateKnownConstInt(Context).toString(
6376 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006377 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006378 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00006379 }
Alexey Bataev28c75412015-12-15 08:19:24 +00006380 }
6381 }
6382
Reid Kleckner87a31802018-03-12 21:43:02 +00006383 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006384
Alexey Bataev28c75412015-12-15 08:19:24 +00006385 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6386 Clauses, AStmt);
6387 if (!Pair.first && DirName.getName() && !DependentHint)
6388 DSAStack->addCriticalWithHint(Dir, Hint);
6389 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006390}
6391
Alexey Bataev4acb8592014-07-07 13:01:15 +00006392StmtResult Sema::ActOnOpenMPParallelForDirective(
6393 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006394 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006395 if (!AStmt)
6396 return StmtError();
6397
Alexey Bataeve3727102018-04-18 15:57:46 +00006398 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006399 // 1.2.2 OpenMP Language Terminology
6400 // Structured block - An executable statement with a single entry at the
6401 // top and a single exit at the bottom.
6402 // The point of exit cannot be a branch out of the structured block.
6403 // longjmp() and throw() must not violate the entry/exit criteria.
6404 CS->getCapturedDecl()->setNothrow();
6405
Alexander Musmanc6388682014-12-15 07:07:06 +00006406 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006407 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6408 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006409 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006410 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006411 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6412 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006413 if (NestedLoopCount == 0)
6414 return StmtError();
6415
Alexander Musmana5f070a2014-10-01 06:03:56 +00006416 assert((CurContext->isDependentContext() || B.builtAll()) &&
6417 "omp parallel for loop exprs were not built");
6418
Alexey Bataev54acd402015-08-04 11:18:19 +00006419 if (!CurContext->isDependentContext()) {
6420 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006421 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006422 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006423 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006424 B.NumIterations, *this, CurScope,
6425 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006426 return StmtError();
6427 }
6428 }
6429
Reid Kleckner87a31802018-03-12 21:43:02 +00006430 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006431 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006432 NestedLoopCount, Clauses, AStmt, B,
6433 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00006434}
6435
Alexander Musmane4e893b2014-09-23 09:33:00 +00006436StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6437 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006438 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006439 if (!AStmt)
6440 return StmtError();
6441
Alexey Bataeve3727102018-04-18 15:57:46 +00006442 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006443 // 1.2.2 OpenMP Language Terminology
6444 // Structured block - An executable statement with a single entry at the
6445 // top and a single exit at the bottom.
6446 // The point of exit cannot be a branch out of the structured block.
6447 // longjmp() and throw() must not violate the entry/exit criteria.
6448 CS->getCapturedDecl()->setNothrow();
6449
Alexander Musmanc6388682014-12-15 07:07:06 +00006450 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006451 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6452 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00006453 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006454 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006455 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6456 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006457 if (NestedLoopCount == 0)
6458 return StmtError();
6459
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006460 if (!CurContext->isDependentContext()) {
6461 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006462 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006463 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006464 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006465 B.NumIterations, *this, CurScope,
6466 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006467 return StmtError();
6468 }
6469 }
6470
Kelvin Lic5609492016-07-15 04:39:07 +00006471 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006472 return StmtError();
6473
Reid Kleckner87a31802018-03-12 21:43:02 +00006474 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006475 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00006476 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006477}
6478
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006479StmtResult
6480Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6481 Stmt *AStmt, SourceLocation StartLoc,
6482 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006483 if (!AStmt)
6484 return StmtError();
6485
6486 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006487 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006488 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006489 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006490 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006491 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006492 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006493 return StmtError();
6494 // All associated statements must be '#pragma omp section' except for
6495 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006496 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006497 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6498 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006499 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006500 diag::err_omp_parallel_sections_substmt_not_section);
6501 return StmtError();
6502 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006503 cast<OMPSectionDirective>(SectionStmt)
6504 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006505 }
6506 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006507 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006508 diag::err_omp_parallel_sections_not_compound_stmt);
6509 return StmtError();
6510 }
6511
Reid Kleckner87a31802018-03-12 21:43:02 +00006512 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006513
Alexey Bataev25e5b442015-09-15 12:52:43 +00006514 return OMPParallelSectionsDirective::Create(
6515 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006516}
6517
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006518StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6519 Stmt *AStmt, SourceLocation StartLoc,
6520 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006521 if (!AStmt)
6522 return StmtError();
6523
David Majnemer9d168222016-08-05 17:44:54 +00006524 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006525 // 1.2.2 OpenMP Language Terminology
6526 // Structured block - An executable statement with a single entry at the
6527 // top and a single exit at the bottom.
6528 // The point of exit cannot be a branch out of the structured block.
6529 // longjmp() and throw() must not violate the entry/exit criteria.
6530 CS->getCapturedDecl()->setNothrow();
6531
Reid Kleckner87a31802018-03-12 21:43:02 +00006532 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006533
Alexey Bataev25e5b442015-09-15 12:52:43 +00006534 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6535 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006536}
6537
Alexey Bataev68446b72014-07-18 07:47:19 +00006538StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6539 SourceLocation EndLoc) {
6540 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6541}
6542
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00006543StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6544 SourceLocation EndLoc) {
6545 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6546}
6547
Alexey Bataev2df347a2014-07-18 10:17:07 +00006548StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6549 SourceLocation EndLoc) {
6550 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6551}
6552
Alexey Bataev169d96a2017-07-18 20:17:46 +00006553StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6554 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006555 SourceLocation StartLoc,
6556 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006557 if (!AStmt)
6558 return StmtError();
6559
6560 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006561
Reid Kleckner87a31802018-03-12 21:43:02 +00006562 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006563
Alexey Bataev169d96a2017-07-18 20:17:46 +00006564 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00006565 AStmt,
6566 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006567}
6568
Alexey Bataev6125da92014-07-21 11:26:11 +00006569StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6570 SourceLocation StartLoc,
6571 SourceLocation EndLoc) {
6572 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6573 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6574}
6575
Alexey Bataev346265e2015-09-25 10:37:12 +00006576StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6577 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006578 SourceLocation StartLoc,
6579 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006580 const OMPClause *DependFound = nullptr;
6581 const OMPClause *DependSourceClause = nullptr;
6582 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00006583 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006584 const OMPThreadsClause *TC = nullptr;
6585 const OMPSIMDClause *SC = nullptr;
6586 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00006587 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6588 DependFound = C;
6589 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6590 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006591 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00006592 << getOpenMPDirectiveName(OMPD_ordered)
6593 << getOpenMPClauseName(OMPC_depend) << 2;
6594 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006595 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00006596 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00006597 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006598 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006599 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006600 << 0;
6601 ErrorFound = true;
6602 }
6603 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6604 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006605 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006606 << 1;
6607 ErrorFound = true;
6608 }
6609 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00006610 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006611 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00006612 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006613 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006614 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006615 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006616 }
Alexey Bataeveb482352015-12-18 05:05:56 +00006617 if (!ErrorFound && !SC &&
6618 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006619 // OpenMP [2.8.1,simd Construct, Restrictions]
6620 // An ordered construct with the simd clause is the only OpenMP construct
6621 // that can appear in the simd region.
6622 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00006623 ErrorFound = true;
6624 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006625 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00006626 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6627 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006628 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006629 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00006630 diag::err_omp_ordered_directive_without_param);
6631 ErrorFound = true;
6632 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006633 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006634 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00006635 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6636 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006637 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00006638 ErrorFound = true;
6639 }
6640 }
6641 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006642 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00006643
6644 if (AStmt) {
6645 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6646
Reid Kleckner87a31802018-03-12 21:43:02 +00006647 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006648 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006649
6650 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006651}
6652
Alexey Bataev1d160b12015-03-13 12:27:31 +00006653namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006654/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006655/// construct.
6656class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006657 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006658 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006659 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006660 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006661 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006662 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006663 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006664 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006665 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006666 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006667 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006668 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006669 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006670 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006671 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00006672 /// expression.
6673 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006674 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00006675 /// part.
6676 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006677 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006678 NoError
6679 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006680 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006681 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006682 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00006683 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006684 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006685 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006686 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006687 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006688 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00006689 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6690 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6691 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006692 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00006693 /// important for non-associative operations.
6694 bool IsXLHSInRHSPart;
6695 BinaryOperatorKind Op;
6696 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006697 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006698 /// if it is a prefix unary operation.
6699 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006700
6701public:
6702 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00006703 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00006704 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006705 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006706 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00006707 /// expression. If DiagId and NoteId == 0, then only check is performed
6708 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006709 /// \param DiagId Diagnostic which should be emitted if error is found.
6710 /// \param NoteId Diagnostic note for the main error message.
6711 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00006712 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006713 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006714 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006715 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006716 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006717 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00006718 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6719 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6720 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006721 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00006722 /// false otherwise.
6723 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
6724
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006725 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006726 /// if it is a prefix unary operation.
6727 bool isPostfixUpdate() const { return IsPostfixUpdate; }
6728
Alexey Bataev1d160b12015-03-13 12:27:31 +00006729private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00006730 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
6731 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00006732};
6733} // namespace
6734
6735bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
6736 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
6737 ExprAnalysisErrorCode ErrorFound = NoError;
6738 SourceLocation ErrorLoc, NoteLoc;
6739 SourceRange ErrorRange, NoteRange;
6740 // Allowed constructs are:
6741 // x = x binop expr;
6742 // x = expr binop x;
6743 if (AtomicBinOp->getOpcode() == BO_Assign) {
6744 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00006745 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006746 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
6747 if (AtomicInnerBinOp->isMultiplicativeOp() ||
6748 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
6749 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006750 Op = AtomicInnerBinOp->getOpcode();
6751 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00006752 Expr *LHS = AtomicInnerBinOp->getLHS();
6753 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006754 llvm::FoldingSetNodeID XId, LHSId, RHSId;
6755 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
6756 /*Canonical=*/true);
6757 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
6758 /*Canonical=*/true);
6759 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
6760 /*Canonical=*/true);
6761 if (XId == LHSId) {
6762 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006763 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006764 } else if (XId == RHSId) {
6765 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006766 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006767 } else {
6768 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6769 ErrorRange = AtomicInnerBinOp->getSourceRange();
6770 NoteLoc = X->getExprLoc();
6771 NoteRange = X->getSourceRange();
6772 ErrorFound = NotAnUpdateExpression;
6773 }
6774 } else {
6775 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6776 ErrorRange = AtomicInnerBinOp->getSourceRange();
6777 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
6778 NoteRange = SourceRange(NoteLoc, NoteLoc);
6779 ErrorFound = NotABinaryOperator;
6780 }
6781 } else {
6782 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
6783 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
6784 ErrorFound = NotABinaryExpression;
6785 }
6786 } else {
6787 ErrorLoc = AtomicBinOp->getExprLoc();
6788 ErrorRange = AtomicBinOp->getSourceRange();
6789 NoteLoc = AtomicBinOp->getOperatorLoc();
6790 NoteRange = SourceRange(NoteLoc, NoteLoc);
6791 ErrorFound = NotAnAssignmentOp;
6792 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006793 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006794 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6795 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6796 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006797 }
6798 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006799 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006800 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006801}
6802
6803bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6804 unsigned NoteId) {
6805 ExprAnalysisErrorCode ErrorFound = NoError;
6806 SourceLocation ErrorLoc, NoteLoc;
6807 SourceRange ErrorRange, NoteRange;
6808 // Allowed constructs are:
6809 // x++;
6810 // x--;
6811 // ++x;
6812 // --x;
6813 // x binop= expr;
6814 // x = x binop expr;
6815 // x = expr binop x;
6816 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6817 AtomicBody = AtomicBody->IgnoreParenImpCasts();
6818 if (AtomicBody->getType()->isScalarType() ||
6819 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006820 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006821 AtomicBody->IgnoreParenImpCasts())) {
6822 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00006823 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006824 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00006825 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006826 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006827 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006828 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006829 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6830 AtomicBody->IgnoreParenImpCasts())) {
6831 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00006832 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00006833 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006834 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00006835 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006836 // Check for Unary Operation
6837 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006838 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006839 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6840 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006841 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006842 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6843 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006844 } else {
6845 ErrorFound = NotAnUnaryIncDecExpression;
6846 ErrorLoc = AtomicUnaryOp->getExprLoc();
6847 ErrorRange = AtomicUnaryOp->getSourceRange();
6848 NoteLoc = AtomicUnaryOp->getOperatorLoc();
6849 NoteRange = SourceRange(NoteLoc, NoteLoc);
6850 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006851 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006852 ErrorFound = NotABinaryOrUnaryExpression;
6853 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6854 NoteRange = ErrorRange = AtomicBody->getSourceRange();
6855 }
6856 } else {
6857 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006858 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006859 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6860 }
6861 } else {
6862 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006863 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006864 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6865 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006866 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006867 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6868 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6869 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006870 }
6871 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006872 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006873 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006874 // Build an update expression of form 'OpaqueValueExpr(x) binop
6875 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6876 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6877 auto *OVEX = new (SemaRef.getASTContext())
6878 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6879 auto *OVEExpr = new (SemaRef.getASTContext())
6880 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00006881 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00006882 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6883 IsXLHSInRHSPart ? OVEExpr : OVEX);
6884 if (Update.isInvalid())
6885 return true;
6886 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6887 Sema::AA_Casting);
6888 if (Update.isInvalid())
6889 return true;
6890 UpdateExpr = Update.get();
6891 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00006892 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006893}
6894
Alexey Bataev0162e452014-07-22 10:10:35 +00006895StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6896 Stmt *AStmt,
6897 SourceLocation StartLoc,
6898 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006899 if (!AStmt)
6900 return StmtError();
6901
David Majnemer9d168222016-08-05 17:44:54 +00006902 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00006903 // 1.2.2 OpenMP Language Terminology
6904 // Structured block - An executable statement with a single entry at the
6905 // top and a single exit at the bottom.
6906 // The point of exit cannot be a branch out of the structured block.
6907 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00006908 OpenMPClauseKind AtomicKind = OMPC_unknown;
6909 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00006910 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00006911 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00006912 C->getClauseKind() == OMPC_update ||
6913 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00006914 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006915 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006916 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00006917 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6918 << getOpenMPClauseName(AtomicKind);
6919 } else {
6920 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006921 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006922 }
6923 }
6924 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006925
Alexey Bataeve3727102018-04-18 15:57:46 +00006926 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00006927 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6928 Body = EWC->getSubExpr();
6929
Alexey Bataev62cec442014-11-18 10:14:22 +00006930 Expr *X = nullptr;
6931 Expr *V = nullptr;
6932 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006933 Expr *UE = nullptr;
6934 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006935 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006936 // OpenMP [2.12.6, atomic Construct]
6937 // In the next expressions:
6938 // * x and v (as applicable) are both l-value expressions with scalar type.
6939 // * During the execution of an atomic region, multiple syntactic
6940 // occurrences of x must designate the same storage location.
6941 // * Neither of v and expr (as applicable) may access the storage location
6942 // designated by x.
6943 // * Neither of x and expr (as applicable) may access the storage location
6944 // designated by v.
6945 // * expr is an expression with scalar type.
6946 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6947 // * binop, binop=, ++, and -- are not overloaded operators.
6948 // * The expression x binop expr must be numerically equivalent to x binop
6949 // (expr). This requirement is satisfied if the operators in expr have
6950 // precedence greater than binop, or by using parentheses around expr or
6951 // subexpressions of expr.
6952 // * The expression expr binop x must be numerically equivalent to (expr)
6953 // binop x. This requirement is satisfied if the operators in expr have
6954 // precedence equal to or greater than binop, or by using parentheses around
6955 // expr or subexpressions of expr.
6956 // * For forms that allow multiple occurrences of x, the number of times
6957 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006958 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006959 enum {
6960 NotAnExpression,
6961 NotAnAssignmentOp,
6962 NotAScalarType,
6963 NotAnLValue,
6964 NoError
6965 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006966 SourceLocation ErrorLoc, NoteLoc;
6967 SourceRange ErrorRange, NoteRange;
6968 // If clause is read:
6969 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006970 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6971 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006972 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6973 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6974 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6975 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6976 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6977 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6978 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006979 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00006980 ErrorFound = NotAnLValue;
6981 ErrorLoc = AtomicBinOp->getExprLoc();
6982 ErrorRange = AtomicBinOp->getSourceRange();
6983 NoteLoc = NotLValueExpr->getExprLoc();
6984 NoteRange = NotLValueExpr->getSourceRange();
6985 }
6986 } else if (!X->isInstantiationDependent() ||
6987 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006988 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00006989 (X->isInstantiationDependent() || X->getType()->isScalarType())
6990 ? V
6991 : X;
6992 ErrorFound = NotAScalarType;
6993 ErrorLoc = AtomicBinOp->getExprLoc();
6994 ErrorRange = AtomicBinOp->getSourceRange();
6995 NoteLoc = NotScalarExpr->getExprLoc();
6996 NoteRange = NotScalarExpr->getSourceRange();
6997 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006998 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00006999 ErrorFound = NotAnAssignmentOp;
7000 ErrorLoc = AtomicBody->getExprLoc();
7001 ErrorRange = AtomicBody->getSourceRange();
7002 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7003 : AtomicBody->getExprLoc();
7004 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7005 : AtomicBody->getSourceRange();
7006 }
7007 } else {
7008 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007009 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00007010 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00007011 }
Alexey Bataev62cec442014-11-18 10:14:22 +00007012 if (ErrorFound != NoError) {
7013 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
7014 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00007015 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7016 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00007017 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007018 }
7019 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00007020 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00007021 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007022 enum {
7023 NotAnExpression,
7024 NotAnAssignmentOp,
7025 NotAScalarType,
7026 NotAnLValue,
7027 NoError
7028 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00007029 SourceLocation ErrorLoc, NoteLoc;
7030 SourceRange ErrorRange, NoteRange;
7031 // If clause is write:
7032 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00007033 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7034 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007035 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7036 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00007037 X = AtomicBinOp->getLHS();
7038 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007039 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7040 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
7041 if (!X->isLValue()) {
7042 ErrorFound = NotAnLValue;
7043 ErrorLoc = AtomicBinOp->getExprLoc();
7044 ErrorRange = AtomicBinOp->getSourceRange();
7045 NoteLoc = X->getExprLoc();
7046 NoteRange = X->getSourceRange();
7047 }
7048 } else if (!X->isInstantiationDependent() ||
7049 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007050 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007051 (X->isInstantiationDependent() || X->getType()->isScalarType())
7052 ? E
7053 : X;
7054 ErrorFound = NotAScalarType;
7055 ErrorLoc = AtomicBinOp->getExprLoc();
7056 ErrorRange = AtomicBinOp->getSourceRange();
7057 NoteLoc = NotScalarExpr->getExprLoc();
7058 NoteRange = NotScalarExpr->getSourceRange();
7059 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007060 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00007061 ErrorFound = NotAnAssignmentOp;
7062 ErrorLoc = AtomicBody->getExprLoc();
7063 ErrorRange = AtomicBody->getSourceRange();
7064 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7065 : AtomicBody->getExprLoc();
7066 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7067 : AtomicBody->getSourceRange();
7068 }
7069 } else {
7070 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007071 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007072 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00007073 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00007074 if (ErrorFound != NoError) {
7075 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
7076 << ErrorRange;
7077 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7078 << NoteRange;
7079 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007080 }
7081 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00007082 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007083 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007084 // If clause is update:
7085 // x++;
7086 // x--;
7087 // ++x;
7088 // --x;
7089 // x binop= expr;
7090 // x = x binop expr;
7091 // x = expr binop x;
7092 OpenMPAtomicUpdateChecker Checker(*this);
7093 if (Checker.checkStatement(
7094 Body, (AtomicKind == OMPC_update)
7095 ? diag::err_omp_atomic_update_not_expression_statement
7096 : diag::err_omp_atomic_not_expression_statement,
7097 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00007098 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007099 if (!CurContext->isDependentContext()) {
7100 E = Checker.getExpr();
7101 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007102 UE = Checker.getUpdateExpr();
7103 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00007104 }
Alexey Bataev459dec02014-07-24 06:46:57 +00007105 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007106 enum {
7107 NotAnAssignmentOp,
7108 NotACompoundStatement,
7109 NotTwoSubstatements,
7110 NotASpecificExpression,
7111 NoError
7112 } ErrorFound = NoError;
7113 SourceLocation ErrorLoc, NoteLoc;
7114 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00007115 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007116 // If clause is a capture:
7117 // v = x++;
7118 // v = x--;
7119 // v = ++x;
7120 // v = --x;
7121 // v = x binop= expr;
7122 // v = x = x binop expr;
7123 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00007124 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00007125 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7126 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7127 V = AtomicBinOp->getLHS();
7128 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7129 OpenMPAtomicUpdateChecker Checker(*this);
7130 if (Checker.checkStatement(
7131 Body, diag::err_omp_atomic_capture_not_expression_statement,
7132 diag::note_omp_atomic_update))
7133 return StmtError();
7134 E = Checker.getExpr();
7135 X = Checker.getX();
7136 UE = Checker.getUpdateExpr();
7137 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7138 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00007139 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007140 ErrorLoc = AtomicBody->getExprLoc();
7141 ErrorRange = AtomicBody->getSourceRange();
7142 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7143 : AtomicBody->getExprLoc();
7144 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7145 : AtomicBody->getSourceRange();
7146 ErrorFound = NotAnAssignmentOp;
7147 }
7148 if (ErrorFound != NoError) {
7149 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
7150 << ErrorRange;
7151 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7152 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007153 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007154 if (CurContext->isDependentContext())
7155 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007156 } else {
7157 // If clause is a capture:
7158 // { v = x; x = expr; }
7159 // { v = x; x++; }
7160 // { v = x; x--; }
7161 // { v = x; ++x; }
7162 // { v = x; --x; }
7163 // { v = x; x binop= expr; }
7164 // { v = x; x = x binop expr; }
7165 // { v = x; x = expr binop x; }
7166 // { x++; v = x; }
7167 // { x--; v = x; }
7168 // { ++x; v = x; }
7169 // { --x; v = x; }
7170 // { x binop= expr; v = x; }
7171 // { x = x binop expr; v = x; }
7172 // { x = expr binop x; v = x; }
7173 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
7174 // Check that this is { expr1; expr2; }
7175 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007176 Stmt *First = CS->body_front();
7177 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007178 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
7179 First = EWC->getSubExpr()->IgnoreParenImpCasts();
7180 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
7181 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
7182 // Need to find what subexpression is 'v' and what is 'x'.
7183 OpenMPAtomicUpdateChecker Checker(*this);
7184 bool IsUpdateExprFound = !Checker.checkStatement(Second);
7185 BinaryOperator *BinOp = nullptr;
7186 if (IsUpdateExprFound) {
7187 BinOp = dyn_cast<BinaryOperator>(First);
7188 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7189 }
7190 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7191 // { v = x; x++; }
7192 // { v = x; x--; }
7193 // { v = x; ++x; }
7194 // { v = x; --x; }
7195 // { v = x; x binop= expr; }
7196 // { v = x; x = x binop expr; }
7197 // { v = x; x = expr binop x; }
7198 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007199 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007200 llvm::FoldingSetNodeID XId, PossibleXId;
7201 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7202 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7203 IsUpdateExprFound = XId == PossibleXId;
7204 if (IsUpdateExprFound) {
7205 V = BinOp->getLHS();
7206 X = Checker.getX();
7207 E = Checker.getExpr();
7208 UE = Checker.getUpdateExpr();
7209 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007210 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007211 }
7212 }
7213 if (!IsUpdateExprFound) {
7214 IsUpdateExprFound = !Checker.checkStatement(First);
7215 BinOp = nullptr;
7216 if (IsUpdateExprFound) {
7217 BinOp = dyn_cast<BinaryOperator>(Second);
7218 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7219 }
7220 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7221 // { x++; v = x; }
7222 // { x--; v = x; }
7223 // { ++x; v = x; }
7224 // { --x; v = x; }
7225 // { x binop= expr; v = x; }
7226 // { x = x binop expr; v = x; }
7227 // { x = expr binop x; v = x; }
7228 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007229 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007230 llvm::FoldingSetNodeID XId, PossibleXId;
7231 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7232 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7233 IsUpdateExprFound = XId == PossibleXId;
7234 if (IsUpdateExprFound) {
7235 V = BinOp->getLHS();
7236 X = Checker.getX();
7237 E = Checker.getExpr();
7238 UE = Checker.getUpdateExpr();
7239 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007240 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007241 }
7242 }
7243 }
7244 if (!IsUpdateExprFound) {
7245 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00007246 auto *FirstExpr = dyn_cast<Expr>(First);
7247 auto *SecondExpr = dyn_cast<Expr>(Second);
7248 if (!FirstExpr || !SecondExpr ||
7249 !(FirstExpr->isInstantiationDependent() ||
7250 SecondExpr->isInstantiationDependent())) {
7251 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
7252 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007253 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00007254 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007255 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007256 NoteRange = ErrorRange = FirstBinOp
7257 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00007258 : SourceRange(ErrorLoc, ErrorLoc);
7259 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00007260 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
7261 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
7262 ErrorFound = NotAnAssignmentOp;
7263 NoteLoc = ErrorLoc = SecondBinOp
7264 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007265 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007266 NoteRange = ErrorRange =
7267 SecondBinOp ? SecondBinOp->getSourceRange()
7268 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00007269 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007270 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00007271 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00007272 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00007273 SecondBinOp->getLHS()->IgnoreParenImpCasts();
7274 llvm::FoldingSetNodeID X1Id, X2Id;
7275 PossibleXRHSInFirst->Profile(X1Id, Context,
7276 /*Canonical=*/true);
7277 PossibleXLHSInSecond->Profile(X2Id, Context,
7278 /*Canonical=*/true);
7279 IsUpdateExprFound = X1Id == X2Id;
7280 if (IsUpdateExprFound) {
7281 V = FirstBinOp->getLHS();
7282 X = SecondBinOp->getLHS();
7283 E = SecondBinOp->getRHS();
7284 UE = nullptr;
7285 IsXLHSInRHSPart = false;
7286 IsPostfixUpdate = true;
7287 } else {
7288 ErrorFound = NotASpecificExpression;
7289 ErrorLoc = FirstBinOp->getExprLoc();
7290 ErrorRange = FirstBinOp->getSourceRange();
7291 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
7292 NoteRange = SecondBinOp->getRHS()->getSourceRange();
7293 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007294 }
7295 }
7296 }
7297 }
7298 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007299 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007300 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007301 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007302 ErrorFound = NotTwoSubstatements;
7303 }
7304 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007305 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007306 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007307 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007308 ErrorFound = NotACompoundStatement;
7309 }
7310 if (ErrorFound != NoError) {
7311 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7312 << ErrorRange;
7313 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7314 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007315 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007316 if (CurContext->isDependentContext())
7317 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00007318 }
Alexey Bataevdea47612014-07-23 07:46:59 +00007319 }
Alexey Bataev0162e452014-07-22 10:10:35 +00007320
Reid Kleckner87a31802018-03-12 21:43:02 +00007321 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00007322
Alexey Bataev62cec442014-11-18 10:14:22 +00007323 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00007324 X, V, E, UE, IsXLHSInRHSPart,
7325 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00007326}
7327
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007328StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7329 Stmt *AStmt,
7330 SourceLocation StartLoc,
7331 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007332 if (!AStmt)
7333 return StmtError();
7334
Alexey Bataeve3727102018-04-18 15:57:46 +00007335 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00007336 // 1.2.2 OpenMP Language Terminology
7337 // Structured block - An executable statement with a single entry at the
7338 // top and a single exit at the bottom.
7339 // The point of exit cannot be a branch out of the structured block.
7340 // longjmp() and throw() must not violate the entry/exit criteria.
7341 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007342 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7343 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7344 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7345 // 1.2.2 OpenMP Language Terminology
7346 // Structured block - An executable statement with a single entry at the
7347 // top and a single exit at the bottom.
7348 // The point of exit cannot be a branch out of the structured block.
7349 // longjmp() and throw() must not violate the entry/exit criteria.
7350 CS->getCapturedDecl()->setNothrow();
7351 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007352
Alexey Bataev13314bf2014-10-09 04:18:56 +00007353 // OpenMP [2.16, Nesting of Regions]
7354 // If specified, a teams construct must be contained within a target
7355 // construct. That target construct must contain no statements or directives
7356 // outside of the teams construct.
7357 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007358 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007359 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007360 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00007361 auto I = CS->body_begin();
7362 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007363 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00007364 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7365 OMPTeamsFound) {
7366
Alexey Bataev13314bf2014-10-09 04:18:56 +00007367 OMPTeamsFound = false;
7368 break;
7369 }
7370 ++I;
7371 }
7372 assert(I != CS->body_end() && "Not found statement");
7373 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00007374 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007375 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00007376 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00007377 }
7378 if (!OMPTeamsFound) {
7379 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7380 Diag(DSAStack->getInnerTeamsRegionLoc(),
7381 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007382 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00007383 << isa<OMPExecutableDirective>(S);
7384 return StmtError();
7385 }
7386 }
7387
Reid Kleckner87a31802018-03-12 21:43:02 +00007388 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007389
7390 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7391}
7392
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007393StmtResult
7394Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7395 Stmt *AStmt, SourceLocation StartLoc,
7396 SourceLocation EndLoc) {
7397 if (!AStmt)
7398 return StmtError();
7399
Alexey Bataeve3727102018-04-18 15:57:46 +00007400 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007401 // 1.2.2 OpenMP Language Terminology
7402 // Structured block - An executable statement with a single entry at the
7403 // top and a single exit at the bottom.
7404 // The point of exit cannot be a branch out of the structured block.
7405 // longjmp() and throw() must not violate the entry/exit criteria.
7406 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007407 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7408 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7409 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7410 // 1.2.2 OpenMP Language Terminology
7411 // Structured block - An executable statement with a single entry at the
7412 // top and a single exit at the bottom.
7413 // The point of exit cannot be a branch out of the structured block.
7414 // longjmp() and throw() must not violate the entry/exit criteria.
7415 CS->getCapturedDecl()->setNothrow();
7416 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007417
Reid Kleckner87a31802018-03-12 21:43:02 +00007418 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007419
7420 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7421 AStmt);
7422}
7423
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007424StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7425 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007426 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007427 if (!AStmt)
7428 return StmtError();
7429
Alexey Bataeve3727102018-04-18 15:57:46 +00007430 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007431 // 1.2.2 OpenMP Language Terminology
7432 // Structured block - An executable statement with a single entry at the
7433 // top and a single exit at the bottom.
7434 // The point of exit cannot be a branch out of the structured block.
7435 // longjmp() and throw() must not violate the entry/exit criteria.
7436 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007437 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7438 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7439 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7440 // 1.2.2 OpenMP Language Terminology
7441 // Structured block - An executable statement with a single entry at the
7442 // top and a single exit at the bottom.
7443 // The point of exit cannot be a branch out of the structured block.
7444 // longjmp() and throw() must not violate the entry/exit criteria.
7445 CS->getCapturedDecl()->setNothrow();
7446 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007447
7448 OMPLoopDirective::HelperExprs B;
7449 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7450 // define the nested loops number.
7451 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007452 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007453 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007454 VarsWithImplicitDSA, B);
7455 if (NestedLoopCount == 0)
7456 return StmtError();
7457
7458 assert((CurContext->isDependentContext() || B.builtAll()) &&
7459 "omp target parallel for loop exprs were not built");
7460
7461 if (!CurContext->isDependentContext()) {
7462 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007463 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007464 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007465 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007466 B.NumIterations, *this, CurScope,
7467 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007468 return StmtError();
7469 }
7470 }
7471
Reid Kleckner87a31802018-03-12 21:43:02 +00007472 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007473 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7474 NestedLoopCount, Clauses, AStmt,
7475 B, DSAStack->isCancelRegion());
7476}
7477
Alexey Bataev95b64a92017-05-30 16:00:04 +00007478/// Check for existence of a map clause in the list of clauses.
7479static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7480 const OpenMPClauseKind K) {
7481 return llvm::any_of(
7482 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7483}
Samuel Antaodf67fc42016-01-19 19:15:56 +00007484
Alexey Bataev95b64a92017-05-30 16:00:04 +00007485template <typename... Params>
7486static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7487 const Params... ClauseTypes) {
7488 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007489}
7490
Michael Wong65f367f2015-07-21 13:44:28 +00007491StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7492 Stmt *AStmt,
7493 SourceLocation StartLoc,
7494 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007495 if (!AStmt)
7496 return StmtError();
7497
7498 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7499
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007500 // OpenMP [2.10.1, Restrictions, p. 97]
7501 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007502 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7503 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7504 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00007505 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007506 return StmtError();
7507 }
7508
Reid Kleckner87a31802018-03-12 21:43:02 +00007509 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00007510
7511 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7512 AStmt);
7513}
7514
Samuel Antaodf67fc42016-01-19 19:15:56 +00007515StmtResult
7516Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7517 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007518 SourceLocation EndLoc, Stmt *AStmt) {
7519 if (!AStmt)
7520 return StmtError();
7521
Alexey Bataeve3727102018-04-18 15:57:46 +00007522 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007523 // 1.2.2 OpenMP Language Terminology
7524 // Structured block - An executable statement with a single entry at the
7525 // top and a single exit at the bottom.
7526 // The point of exit cannot be a branch out of the structured block.
7527 // longjmp() and throw() must not violate the entry/exit criteria.
7528 CS->getCapturedDecl()->setNothrow();
7529 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7530 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7531 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7532 // 1.2.2 OpenMP Language Terminology
7533 // Structured block - An executable statement with a single entry at the
7534 // top and a single exit at the bottom.
7535 // The point of exit cannot be a branch out of the structured block.
7536 // longjmp() and throw() must not violate the entry/exit criteria.
7537 CS->getCapturedDecl()->setNothrow();
7538 }
7539
Samuel Antaodf67fc42016-01-19 19:15:56 +00007540 // OpenMP [2.10.2, Restrictions, p. 99]
7541 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007542 if (!hasClauses(Clauses, OMPC_map)) {
7543 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7544 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007545 return StmtError();
7546 }
7547
Alexey Bataev7828b252017-11-21 17:08:48 +00007548 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7549 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007550}
7551
Samuel Antao72590762016-01-19 20:04:50 +00007552StmtResult
7553Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7554 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007555 SourceLocation EndLoc, Stmt *AStmt) {
7556 if (!AStmt)
7557 return StmtError();
7558
Alexey Bataeve3727102018-04-18 15:57:46 +00007559 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007560 // 1.2.2 OpenMP Language Terminology
7561 // Structured block - An executable statement with a single entry at the
7562 // top and a single exit at the bottom.
7563 // The point of exit cannot be a branch out of the structured block.
7564 // longjmp() and throw() must not violate the entry/exit criteria.
7565 CS->getCapturedDecl()->setNothrow();
7566 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7567 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7568 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7569 // 1.2.2 OpenMP Language Terminology
7570 // Structured block - An executable statement with a single entry at the
7571 // top and a single exit at the bottom.
7572 // The point of exit cannot be a branch out of the structured block.
7573 // longjmp() and throw() must not violate the entry/exit criteria.
7574 CS->getCapturedDecl()->setNothrow();
7575 }
7576
Samuel Antao72590762016-01-19 20:04:50 +00007577 // OpenMP [2.10.3, Restrictions, p. 102]
7578 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007579 if (!hasClauses(Clauses, OMPC_map)) {
7580 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7581 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00007582 return StmtError();
7583 }
7584
Alexey Bataev7828b252017-11-21 17:08:48 +00007585 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7586 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00007587}
7588
Samuel Antao686c70c2016-05-26 17:30:50 +00007589StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7590 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007591 SourceLocation EndLoc,
7592 Stmt *AStmt) {
7593 if (!AStmt)
7594 return StmtError();
7595
Alexey Bataeve3727102018-04-18 15:57:46 +00007596 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007597 // 1.2.2 OpenMP Language Terminology
7598 // Structured block - An executable statement with a single entry at the
7599 // top and a single exit at the bottom.
7600 // The point of exit cannot be a branch out of the structured block.
7601 // longjmp() and throw() must not violate the entry/exit criteria.
7602 CS->getCapturedDecl()->setNothrow();
7603 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7604 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7605 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7606 // 1.2.2 OpenMP Language Terminology
7607 // Structured block - An executable statement with a single entry at the
7608 // top and a single exit at the bottom.
7609 // The point of exit cannot be a branch out of the structured block.
7610 // longjmp() and throw() must not violate the entry/exit criteria.
7611 CS->getCapturedDecl()->setNothrow();
7612 }
7613
Alexey Bataev95b64a92017-05-30 16:00:04 +00007614 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00007615 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7616 return StmtError();
7617 }
Alexey Bataev7828b252017-11-21 17:08:48 +00007618 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7619 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00007620}
7621
Alexey Bataev13314bf2014-10-09 04:18:56 +00007622StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7623 Stmt *AStmt, SourceLocation StartLoc,
7624 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007625 if (!AStmt)
7626 return StmtError();
7627
Alexey Bataeve3727102018-04-18 15:57:46 +00007628 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007629 // 1.2.2 OpenMP Language Terminology
7630 // Structured block - An executable statement with a single entry at the
7631 // top and a single exit at the bottom.
7632 // The point of exit cannot be a branch out of the structured block.
7633 // longjmp() and throw() must not violate the entry/exit criteria.
7634 CS->getCapturedDecl()->setNothrow();
7635
Reid Kleckner87a31802018-03-12 21:43:02 +00007636 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00007637
Alexey Bataevceabd412017-11-30 18:01:54 +00007638 DSAStack->setParentTeamsRegionLoc(StartLoc);
7639
Alexey Bataev13314bf2014-10-09 04:18:56 +00007640 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7641}
7642
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007643StmtResult
7644Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7645 SourceLocation EndLoc,
7646 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007647 if (DSAStack->isParentNowaitRegion()) {
7648 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
7649 return StmtError();
7650 }
7651 if (DSAStack->isParentOrderedRegion()) {
7652 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
7653 return StmtError();
7654 }
7655 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
7656 CancelRegion);
7657}
7658
Alexey Bataev87933c72015-09-18 08:07:34 +00007659StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7660 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00007661 SourceLocation EndLoc,
7662 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00007663 if (DSAStack->isParentNowaitRegion()) {
7664 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
7665 return StmtError();
7666 }
7667 if (DSAStack->isParentOrderedRegion()) {
7668 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
7669 return StmtError();
7670 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007671 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00007672 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7673 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00007674}
7675
Alexey Bataev382967a2015-12-08 12:06:20 +00007676static bool checkGrainsizeNumTasksClauses(Sema &S,
7677 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007678 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00007679 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007680 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00007681 if (C->getClauseKind() == OMPC_grainsize ||
7682 C->getClauseKind() == OMPC_num_tasks) {
7683 if (!PrevClause)
7684 PrevClause = C;
7685 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007686 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007687 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
7688 << getOpenMPClauseName(C->getClauseKind())
7689 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007690 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007691 diag::note_omp_previous_grainsize_num_tasks)
7692 << getOpenMPClauseName(PrevClause->getClauseKind());
7693 ErrorFound = true;
7694 }
7695 }
7696 }
7697 return ErrorFound;
7698}
7699
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007700static bool checkReductionClauseWithNogroup(Sema &S,
7701 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007702 const OMPClause *ReductionClause = nullptr;
7703 const OMPClause *NogroupClause = nullptr;
7704 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007705 if (C->getClauseKind() == OMPC_reduction) {
7706 ReductionClause = C;
7707 if (NogroupClause)
7708 break;
7709 continue;
7710 }
7711 if (C->getClauseKind() == OMPC_nogroup) {
7712 NogroupClause = C;
7713 if (ReductionClause)
7714 break;
7715 continue;
7716 }
7717 }
7718 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007719 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
7720 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007721 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007722 return true;
7723 }
7724 return false;
7725}
7726
Alexey Bataev49f6e782015-12-01 04:18:41 +00007727StmtResult Sema::ActOnOpenMPTaskLoopDirective(
7728 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007729 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00007730 if (!AStmt)
7731 return StmtError();
7732
7733 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7734 OMPLoopDirective::HelperExprs B;
7735 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7736 // define the nested loops number.
7737 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007738 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007739 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00007740 VarsWithImplicitDSA, B);
7741 if (NestedLoopCount == 0)
7742 return StmtError();
7743
7744 assert((CurContext->isDependentContext() || B.builtAll()) &&
7745 "omp for loop exprs were not built");
7746
Alexey Bataev382967a2015-12-08 12:06:20 +00007747 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7748 // The grainsize clause and num_tasks clause are mutually exclusive and may
7749 // not appear on the same taskloop directive.
7750 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7751 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007752 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7753 // If a reduction clause is present on the taskloop directive, the nogroup
7754 // clause must not be specified.
7755 if (checkReductionClauseWithNogroup(*this, Clauses))
7756 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007757
Reid Kleckner87a31802018-03-12 21:43:02 +00007758 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00007759 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
7760 NestedLoopCount, Clauses, AStmt, B);
7761}
7762
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007763StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
7764 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007765 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007766 if (!AStmt)
7767 return StmtError();
7768
7769 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7770 OMPLoopDirective::HelperExprs B;
7771 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7772 // define the nested loops number.
7773 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007774 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007775 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7776 VarsWithImplicitDSA, B);
7777 if (NestedLoopCount == 0)
7778 return StmtError();
7779
7780 assert((CurContext->isDependentContext() || B.builtAll()) &&
7781 "omp for loop exprs were not built");
7782
Alexey Bataev5a3af132016-03-29 08:58:54 +00007783 if (!CurContext->isDependentContext()) {
7784 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007785 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007786 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007787 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007788 B.NumIterations, *this, CurScope,
7789 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007790 return StmtError();
7791 }
7792 }
7793
Alexey Bataev382967a2015-12-08 12:06:20 +00007794 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7795 // The grainsize clause and num_tasks clause are mutually exclusive and may
7796 // not appear on the same taskloop directive.
7797 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7798 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007799 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7800 // If a reduction clause is present on the taskloop directive, the nogroup
7801 // clause must not be specified.
7802 if (checkReductionClauseWithNogroup(*this, Clauses))
7803 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00007804 if (checkSimdlenSafelenSpecified(*this, Clauses))
7805 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007806
Reid Kleckner87a31802018-03-12 21:43:02 +00007807 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007808 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7809 NestedLoopCount, Clauses, AStmt, B);
7810}
7811
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007812StmtResult Sema::ActOnOpenMPDistributeDirective(
7813 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007814 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007815 if (!AStmt)
7816 return StmtError();
7817
7818 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7819 OMPLoopDirective::HelperExprs B;
7820 // In presence of clause 'collapse' with number of loops, it will
7821 // define the nested loops number.
7822 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007823 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007824 nullptr /*ordered not a clause on distribute*/, AStmt,
7825 *this, *DSAStack, VarsWithImplicitDSA, B);
7826 if (NestedLoopCount == 0)
7827 return StmtError();
7828
7829 assert((CurContext->isDependentContext() || B.builtAll()) &&
7830 "omp for loop exprs were not built");
7831
Reid Kleckner87a31802018-03-12 21:43:02 +00007832 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007833 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7834 NestedLoopCount, Clauses, AStmt, B);
7835}
7836
Carlo Bertolli9925f152016-06-27 14:55:37 +00007837StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7838 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007839 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00007840 if (!AStmt)
7841 return StmtError();
7842
Alexey Bataeve3727102018-04-18 15:57:46 +00007843 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007844 // 1.2.2 OpenMP Language Terminology
7845 // Structured block - An executable statement with a single entry at the
7846 // top and a single exit at the bottom.
7847 // The point of exit cannot be a branch out of the structured block.
7848 // longjmp() and throw() must not violate the entry/exit criteria.
7849 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00007850 for (int ThisCaptureLevel =
7851 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7852 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7853 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7854 // 1.2.2 OpenMP Language Terminology
7855 // Structured block - An executable statement with a single entry at the
7856 // top and a single exit at the bottom.
7857 // The point of exit cannot be a branch out of the structured block.
7858 // longjmp() and throw() must not violate the entry/exit criteria.
7859 CS->getCapturedDecl()->setNothrow();
7860 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00007861
7862 OMPLoopDirective::HelperExprs B;
7863 // In presence of clause 'collapse' with number of loops, it will
7864 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007865 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00007866 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00007867 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00007868 VarsWithImplicitDSA, B);
7869 if (NestedLoopCount == 0)
7870 return StmtError();
7871
7872 assert((CurContext->isDependentContext() || B.builtAll()) &&
7873 "omp for loop exprs were not built");
7874
Reid Kleckner87a31802018-03-12 21:43:02 +00007875 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007876 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007877 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7878 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00007879}
7880
Kelvin Li4a39add2016-07-05 05:00:15 +00007881StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7882 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007883 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00007884 if (!AStmt)
7885 return StmtError();
7886
Alexey Bataeve3727102018-04-18 15:57:46 +00007887 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00007888 // 1.2.2 OpenMP Language Terminology
7889 // Structured block - An executable statement with a single entry at the
7890 // top and a single exit at the bottom.
7891 // The point of exit cannot be a branch out of the structured block.
7892 // longjmp() and throw() must not violate the entry/exit criteria.
7893 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00007894 for (int ThisCaptureLevel =
7895 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7896 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7897 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7898 // 1.2.2 OpenMP Language Terminology
7899 // Structured block - An executable statement with a single entry at the
7900 // top and a single exit at the bottom.
7901 // The point of exit cannot be a branch out of the structured block.
7902 // longjmp() and throw() must not violate the entry/exit criteria.
7903 CS->getCapturedDecl()->setNothrow();
7904 }
Kelvin Li4a39add2016-07-05 05:00:15 +00007905
7906 OMPLoopDirective::HelperExprs B;
7907 // In presence of clause 'collapse' with number of loops, it will
7908 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007909 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00007910 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00007911 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00007912 VarsWithImplicitDSA, B);
7913 if (NestedLoopCount == 0)
7914 return StmtError();
7915
7916 assert((CurContext->isDependentContext() || B.builtAll()) &&
7917 "omp for loop exprs were not built");
7918
Alexey Bataev438388c2017-11-22 18:34:02 +00007919 if (!CurContext->isDependentContext()) {
7920 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007921 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007922 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7923 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7924 B.NumIterations, *this, CurScope,
7925 DSAStack))
7926 return StmtError();
7927 }
7928 }
7929
Kelvin Lic5609492016-07-15 04:39:07 +00007930 if (checkSimdlenSafelenSpecified(*this, Clauses))
7931 return StmtError();
7932
Reid Kleckner87a31802018-03-12 21:43:02 +00007933 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00007934 return OMPDistributeParallelForSimdDirective::Create(
7935 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7936}
7937
Kelvin Li787f3fc2016-07-06 04:45:38 +00007938StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7939 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007940 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00007941 if (!AStmt)
7942 return StmtError();
7943
Alexey Bataeve3727102018-04-18 15:57:46 +00007944 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007945 // 1.2.2 OpenMP Language Terminology
7946 // Structured block - An executable statement with a single entry at the
7947 // top and a single exit at the bottom.
7948 // The point of exit cannot be a branch out of the structured block.
7949 // longjmp() and throw() must not violate the entry/exit criteria.
7950 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00007951 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7952 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7953 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7954 // 1.2.2 OpenMP Language Terminology
7955 // Structured block - An executable statement with a single entry at the
7956 // top and a single exit at the bottom.
7957 // The point of exit cannot be a branch out of the structured block.
7958 // longjmp() and throw() must not violate the entry/exit criteria.
7959 CS->getCapturedDecl()->setNothrow();
7960 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007961
7962 OMPLoopDirective::HelperExprs B;
7963 // In presence of clause 'collapse' with number of loops, it will
7964 // define the nested loops number.
7965 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007966 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007967 nullptr /*ordered not a clause on distribute*/, CS, *this,
7968 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007969 if (NestedLoopCount == 0)
7970 return StmtError();
7971
7972 assert((CurContext->isDependentContext() || B.builtAll()) &&
7973 "omp for loop exprs were not built");
7974
Alexey Bataev438388c2017-11-22 18:34:02 +00007975 if (!CurContext->isDependentContext()) {
7976 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007977 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007978 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7979 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7980 B.NumIterations, *this, CurScope,
7981 DSAStack))
7982 return StmtError();
7983 }
7984 }
7985
Kelvin Lic5609492016-07-15 04:39:07 +00007986 if (checkSimdlenSafelenSpecified(*this, Clauses))
7987 return StmtError();
7988
Reid Kleckner87a31802018-03-12 21:43:02 +00007989 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00007990 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7991 NestedLoopCount, Clauses, AStmt, B);
7992}
7993
Kelvin Lia579b912016-07-14 02:54:56 +00007994StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7995 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007996 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00007997 if (!AStmt)
7998 return StmtError();
7999
Alexey Bataeve3727102018-04-18 15:57:46 +00008000 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00008001 // 1.2.2 OpenMP Language Terminology
8002 // Structured block - An executable statement with a single entry at the
8003 // top and a single exit at the bottom.
8004 // The point of exit cannot be a branch out of the structured block.
8005 // longjmp() and throw() must not violate the entry/exit criteria.
8006 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008007 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
8008 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8009 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8010 // 1.2.2 OpenMP Language Terminology
8011 // Structured block - An executable statement with a single entry at the
8012 // top and a single exit at the bottom.
8013 // The point of exit cannot be a branch out of the structured block.
8014 // longjmp() and throw() must not violate the entry/exit criteria.
8015 CS->getCapturedDecl()->setNothrow();
8016 }
Kelvin Lia579b912016-07-14 02:54:56 +00008017
8018 OMPLoopDirective::HelperExprs B;
8019 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8020 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008021 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00008022 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008023 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00008024 VarsWithImplicitDSA, B);
8025 if (NestedLoopCount == 0)
8026 return StmtError();
8027
8028 assert((CurContext->isDependentContext() || B.builtAll()) &&
8029 "omp target parallel for simd loop exprs were not built");
8030
8031 if (!CurContext->isDependentContext()) {
8032 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008033 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008034 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00008035 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8036 B.NumIterations, *this, CurScope,
8037 DSAStack))
8038 return StmtError();
8039 }
8040 }
Kelvin Lic5609492016-07-15 04:39:07 +00008041 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00008042 return StmtError();
8043
Reid Kleckner87a31802018-03-12 21:43:02 +00008044 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00008045 return OMPTargetParallelForSimdDirective::Create(
8046 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8047}
8048
Kelvin Li986330c2016-07-20 22:57:10 +00008049StmtResult Sema::ActOnOpenMPTargetSimdDirective(
8050 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008051 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00008052 if (!AStmt)
8053 return StmtError();
8054
Alexey Bataeve3727102018-04-18 15:57:46 +00008055 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00008056 // 1.2.2 OpenMP Language Terminology
8057 // Structured block - An executable statement with a single entry at the
8058 // top and a single exit at the bottom.
8059 // The point of exit cannot be a branch out of the structured block.
8060 // longjmp() and throw() must not violate the entry/exit criteria.
8061 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00008062 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
8063 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8064 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8065 // 1.2.2 OpenMP Language Terminology
8066 // Structured block - An executable statement with a single entry at the
8067 // top and a single exit at the bottom.
8068 // The point of exit cannot be a branch out of the structured block.
8069 // longjmp() and throw() must not violate the entry/exit criteria.
8070 CS->getCapturedDecl()->setNothrow();
8071 }
8072
Kelvin Li986330c2016-07-20 22:57:10 +00008073 OMPLoopDirective::HelperExprs B;
8074 // In presence of clause 'collapse' with number of loops, it will define the
8075 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00008076 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008077 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00008078 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00008079 VarsWithImplicitDSA, B);
8080 if (NestedLoopCount == 0)
8081 return StmtError();
8082
8083 assert((CurContext->isDependentContext() || B.builtAll()) &&
8084 "omp target simd loop exprs were not built");
8085
8086 if (!CurContext->isDependentContext()) {
8087 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008088 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008089 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00008090 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8091 B.NumIterations, *this, CurScope,
8092 DSAStack))
8093 return StmtError();
8094 }
8095 }
8096
8097 if (checkSimdlenSafelenSpecified(*this, Clauses))
8098 return StmtError();
8099
Reid Kleckner87a31802018-03-12 21:43:02 +00008100 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00008101 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
8102 NestedLoopCount, Clauses, AStmt, B);
8103}
8104
Kelvin Li02532872016-08-05 14:37:37 +00008105StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
8106 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008107 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00008108 if (!AStmt)
8109 return StmtError();
8110
Alexey Bataeve3727102018-04-18 15:57:46 +00008111 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00008112 // 1.2.2 OpenMP Language Terminology
8113 // Structured block - An executable statement with a single entry at the
8114 // top and a single exit at the bottom.
8115 // The point of exit cannot be a branch out of the structured block.
8116 // longjmp() and throw() must not violate the entry/exit criteria.
8117 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008118 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
8119 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8120 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8121 // 1.2.2 OpenMP Language Terminology
8122 // Structured block - An executable statement with a single entry at the
8123 // top and a single exit at the bottom.
8124 // The point of exit cannot be a branch out of the structured block.
8125 // longjmp() and throw() must not violate the entry/exit criteria.
8126 CS->getCapturedDecl()->setNothrow();
8127 }
Kelvin Li02532872016-08-05 14:37:37 +00008128
8129 OMPLoopDirective::HelperExprs B;
8130 // In presence of clause 'collapse' with number of loops, it will
8131 // define the nested loops number.
8132 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008133 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008134 nullptr /*ordered not a clause on distribute*/, CS, *this,
8135 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00008136 if (NestedLoopCount == 0)
8137 return StmtError();
8138
8139 assert((CurContext->isDependentContext() || B.builtAll()) &&
8140 "omp teams distribute loop exprs were not built");
8141
Reid Kleckner87a31802018-03-12 21:43:02 +00008142 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008143
8144 DSAStack->setParentTeamsRegionLoc(StartLoc);
8145
David Majnemer9d168222016-08-05 17:44:54 +00008146 return OMPTeamsDistributeDirective::Create(
8147 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00008148}
8149
Kelvin Li4e325f72016-10-25 12:50:55 +00008150StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
8151 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008152 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008153 if (!AStmt)
8154 return StmtError();
8155
Alexey Bataeve3727102018-04-18 15:57:46 +00008156 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00008157 // 1.2.2 OpenMP Language Terminology
8158 // Structured block - An executable statement with a single entry at the
8159 // top and a single exit at the bottom.
8160 // The point of exit cannot be a branch out of the structured block.
8161 // longjmp() and throw() must not violate the entry/exit criteria.
8162 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00008163 for (int ThisCaptureLevel =
8164 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
8165 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8166 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8167 // 1.2.2 OpenMP Language Terminology
8168 // Structured block - An executable statement with a single entry at the
8169 // top and a single exit at the bottom.
8170 // The point of exit cannot be a branch out of the structured block.
8171 // longjmp() and throw() must not violate the entry/exit criteria.
8172 CS->getCapturedDecl()->setNothrow();
8173 }
8174
Kelvin Li4e325f72016-10-25 12:50:55 +00008175
8176 OMPLoopDirective::HelperExprs B;
8177 // In presence of clause 'collapse' with number of loops, it will
8178 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008179 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00008180 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00008181 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00008182 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00008183
8184 if (NestedLoopCount == 0)
8185 return StmtError();
8186
8187 assert((CurContext->isDependentContext() || B.builtAll()) &&
8188 "omp teams distribute simd loop exprs were not built");
8189
8190 if (!CurContext->isDependentContext()) {
8191 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008192 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008193 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8194 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8195 B.NumIterations, *this, CurScope,
8196 DSAStack))
8197 return StmtError();
8198 }
8199 }
8200
8201 if (checkSimdlenSafelenSpecified(*this, Clauses))
8202 return StmtError();
8203
Reid Kleckner87a31802018-03-12 21:43:02 +00008204 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008205
8206 DSAStack->setParentTeamsRegionLoc(StartLoc);
8207
Kelvin Li4e325f72016-10-25 12:50:55 +00008208 return OMPTeamsDistributeSimdDirective::Create(
8209 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8210}
8211
Kelvin Li579e41c2016-11-30 23:51:03 +00008212StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8213 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008214 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008215 if (!AStmt)
8216 return StmtError();
8217
Alexey Bataeve3727102018-04-18 15:57:46 +00008218 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00008219 // 1.2.2 OpenMP Language Terminology
8220 // Structured block - An executable statement with a single entry at the
8221 // top and a single exit at the bottom.
8222 // The point of exit cannot be a branch out of the structured block.
8223 // longjmp() and throw() must not violate the entry/exit criteria.
8224 CS->getCapturedDecl()->setNothrow();
8225
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008226 for (int ThisCaptureLevel =
8227 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
8228 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8229 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8230 // 1.2.2 OpenMP Language Terminology
8231 // Structured block - An executable statement with a single entry at the
8232 // top and a single exit at the bottom.
8233 // The point of exit cannot be a branch out of the structured block.
8234 // longjmp() and throw() must not violate the entry/exit criteria.
8235 CS->getCapturedDecl()->setNothrow();
8236 }
8237
Kelvin Li579e41c2016-11-30 23:51:03 +00008238 OMPLoopDirective::HelperExprs B;
8239 // In presence of clause 'collapse' with number of loops, it will
8240 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008241 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00008242 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008243 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00008244 VarsWithImplicitDSA, B);
8245
8246 if (NestedLoopCount == 0)
8247 return StmtError();
8248
8249 assert((CurContext->isDependentContext() || B.builtAll()) &&
8250 "omp for loop exprs were not built");
8251
8252 if (!CurContext->isDependentContext()) {
8253 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008254 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008255 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8256 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8257 B.NumIterations, *this, CurScope,
8258 DSAStack))
8259 return StmtError();
8260 }
8261 }
8262
8263 if (checkSimdlenSafelenSpecified(*this, Clauses))
8264 return StmtError();
8265
Reid Kleckner87a31802018-03-12 21:43:02 +00008266 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008267
8268 DSAStack->setParentTeamsRegionLoc(StartLoc);
8269
Kelvin Li579e41c2016-11-30 23:51:03 +00008270 return OMPTeamsDistributeParallelForSimdDirective::Create(
8271 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8272}
8273
Kelvin Li7ade93f2016-12-09 03:24:30 +00008274StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
8275 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008276 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00008277 if (!AStmt)
8278 return StmtError();
8279
Alexey Bataeve3727102018-04-18 15:57:46 +00008280 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00008281 // 1.2.2 OpenMP Language Terminology
8282 // Structured block - An executable statement with a single entry at the
8283 // top and a single exit at the bottom.
8284 // The point of exit cannot be a branch out of the structured block.
8285 // longjmp() and throw() must not violate the entry/exit criteria.
8286 CS->getCapturedDecl()->setNothrow();
8287
Carlo Bertolli62fae152017-11-20 20:46:39 +00008288 for (int ThisCaptureLevel =
8289 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
8290 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8291 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8292 // 1.2.2 OpenMP Language Terminology
8293 // Structured block - An executable statement with a single entry at the
8294 // top and a single exit at the bottom.
8295 // The point of exit cannot be a branch out of the structured block.
8296 // longjmp() and throw() must not violate the entry/exit criteria.
8297 CS->getCapturedDecl()->setNothrow();
8298 }
8299
Kelvin Li7ade93f2016-12-09 03:24:30 +00008300 OMPLoopDirective::HelperExprs B;
8301 // In presence of clause 'collapse' with number of loops, it will
8302 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008303 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00008304 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00008305 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00008306 VarsWithImplicitDSA, B);
8307
8308 if (NestedLoopCount == 0)
8309 return StmtError();
8310
8311 assert((CurContext->isDependentContext() || B.builtAll()) &&
8312 "omp for loop exprs were not built");
8313
Reid Kleckner87a31802018-03-12 21:43:02 +00008314 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008315
8316 DSAStack->setParentTeamsRegionLoc(StartLoc);
8317
Kelvin Li7ade93f2016-12-09 03:24:30 +00008318 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008319 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8320 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00008321}
8322
Kelvin Libf594a52016-12-17 05:48:59 +00008323StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8324 Stmt *AStmt,
8325 SourceLocation StartLoc,
8326 SourceLocation EndLoc) {
8327 if (!AStmt)
8328 return StmtError();
8329
Alexey Bataeve3727102018-04-18 15:57:46 +00008330 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00008331 // 1.2.2 OpenMP Language Terminology
8332 // Structured block - An executable statement with a single entry at the
8333 // top and a single exit at the bottom.
8334 // The point of exit cannot be a branch out of the structured block.
8335 // longjmp() and throw() must not violate the entry/exit criteria.
8336 CS->getCapturedDecl()->setNothrow();
8337
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00008338 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
8339 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8340 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8341 // 1.2.2 OpenMP Language Terminology
8342 // Structured block - An executable statement with a single entry at the
8343 // top and a single exit at the bottom.
8344 // The point of exit cannot be a branch out of the structured block.
8345 // longjmp() and throw() must not violate the entry/exit criteria.
8346 CS->getCapturedDecl()->setNothrow();
8347 }
Reid Kleckner87a31802018-03-12 21:43:02 +00008348 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00008349
8350 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8351 AStmt);
8352}
8353
Kelvin Li83c451e2016-12-25 04:52:54 +00008354StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8355 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008356 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00008357 if (!AStmt)
8358 return StmtError();
8359
Alexey Bataeve3727102018-04-18 15:57:46 +00008360 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00008361 // 1.2.2 OpenMP Language Terminology
8362 // Structured block - An executable statement with a single entry at the
8363 // top and a single exit at the bottom.
8364 // The point of exit cannot be a branch out of the structured block.
8365 // longjmp() and throw() must not violate the entry/exit criteria.
8366 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008367 for (int ThisCaptureLevel =
8368 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8369 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8370 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8371 // 1.2.2 OpenMP Language Terminology
8372 // Structured block - An executable statement with a single entry at the
8373 // top and a single exit at the bottom.
8374 // The point of exit cannot be a branch out of the structured block.
8375 // longjmp() and throw() must not violate the entry/exit criteria.
8376 CS->getCapturedDecl()->setNothrow();
8377 }
Kelvin Li83c451e2016-12-25 04:52:54 +00008378
8379 OMPLoopDirective::HelperExprs B;
8380 // In presence of clause 'collapse' with number of loops, it will
8381 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008382 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008383 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8384 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00008385 VarsWithImplicitDSA, B);
8386 if (NestedLoopCount == 0)
8387 return StmtError();
8388
8389 assert((CurContext->isDependentContext() || B.builtAll()) &&
8390 "omp target teams distribute loop exprs were not built");
8391
Reid Kleckner87a31802018-03-12 21:43:02 +00008392 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00008393 return OMPTargetTeamsDistributeDirective::Create(
8394 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8395}
8396
Kelvin Li80e8f562016-12-29 22:16:30 +00008397StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8398 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008399 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00008400 if (!AStmt)
8401 return StmtError();
8402
Alexey Bataeve3727102018-04-18 15:57:46 +00008403 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00008404 // 1.2.2 OpenMP Language Terminology
8405 // Structured block - An executable statement with a single entry at the
8406 // top and a single exit at the bottom.
8407 // The point of exit cannot be a branch out of the structured block.
8408 // longjmp() and throw() must not violate the entry/exit criteria.
8409 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00008410 for (int ThisCaptureLevel =
8411 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8412 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8413 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8414 // 1.2.2 OpenMP Language Terminology
8415 // Structured block - An executable statement with a single entry at the
8416 // top and a single exit at the bottom.
8417 // The point of exit cannot be a branch out of the structured block.
8418 // longjmp() and throw() must not violate the entry/exit criteria.
8419 CS->getCapturedDecl()->setNothrow();
8420 }
8421
Kelvin Li80e8f562016-12-29 22:16:30 +00008422 OMPLoopDirective::HelperExprs B;
8423 // In presence of clause 'collapse' with number of loops, it will
8424 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008425 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00008426 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8427 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00008428 VarsWithImplicitDSA, B);
8429 if (NestedLoopCount == 0)
8430 return StmtError();
8431
8432 assert((CurContext->isDependentContext() || B.builtAll()) &&
8433 "omp target teams distribute parallel for loop exprs were not built");
8434
Alexey Bataev647dd842018-01-15 20:59:40 +00008435 if (!CurContext->isDependentContext()) {
8436 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008437 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00008438 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8439 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8440 B.NumIterations, *this, CurScope,
8441 DSAStack))
8442 return StmtError();
8443 }
8444 }
8445
Reid Kleckner87a31802018-03-12 21:43:02 +00008446 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00008447 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00008448 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8449 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00008450}
8451
Kelvin Li1851df52017-01-03 05:23:48 +00008452StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8453 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008454 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00008455 if (!AStmt)
8456 return StmtError();
8457
Alexey Bataeve3727102018-04-18 15:57:46 +00008458 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00008459 // 1.2.2 OpenMP Language Terminology
8460 // Structured block - An executable statement with a single entry at the
8461 // top and a single exit at the bottom.
8462 // The point of exit cannot be a branch out of the structured block.
8463 // longjmp() and throw() must not violate the entry/exit criteria.
8464 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00008465 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8466 OMPD_target_teams_distribute_parallel_for_simd);
8467 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8468 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8469 // 1.2.2 OpenMP Language Terminology
8470 // Structured block - An executable statement with a single entry at the
8471 // top and a single exit at the bottom.
8472 // The point of exit cannot be a branch out of the structured block.
8473 // longjmp() and throw() must not violate the entry/exit criteria.
8474 CS->getCapturedDecl()->setNothrow();
8475 }
Kelvin Li1851df52017-01-03 05:23:48 +00008476
8477 OMPLoopDirective::HelperExprs B;
8478 // In presence of clause 'collapse' with number of loops, it will
8479 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008480 unsigned NestedLoopCount =
8481 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00008482 getCollapseNumberExpr(Clauses),
8483 nullptr /*ordered not a clause on distribute*/, CS, *this,
8484 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00008485 if (NestedLoopCount == 0)
8486 return StmtError();
8487
8488 assert((CurContext->isDependentContext() || B.builtAll()) &&
8489 "omp target teams distribute parallel for simd loop exprs were not "
8490 "built");
8491
8492 if (!CurContext->isDependentContext()) {
8493 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008494 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00008495 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8496 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8497 B.NumIterations, *this, CurScope,
8498 DSAStack))
8499 return StmtError();
8500 }
8501 }
8502
Alexey Bataev438388c2017-11-22 18:34:02 +00008503 if (checkSimdlenSafelenSpecified(*this, Clauses))
8504 return StmtError();
8505
Reid Kleckner87a31802018-03-12 21:43:02 +00008506 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00008507 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8508 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8509}
8510
Kelvin Lida681182017-01-10 18:08:18 +00008511StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8512 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008513 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00008514 if (!AStmt)
8515 return StmtError();
8516
8517 auto *CS = cast<CapturedStmt>(AStmt);
8518 // 1.2.2 OpenMP Language Terminology
8519 // Structured block - An executable statement with a single entry at the
8520 // top and a single exit at the bottom.
8521 // The point of exit cannot be a branch out of the structured block.
8522 // longjmp() and throw() must not violate the entry/exit criteria.
8523 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008524 for (int ThisCaptureLevel =
8525 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
8526 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8527 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8528 // 1.2.2 OpenMP Language Terminology
8529 // Structured block - An executable statement with a single entry at the
8530 // top and a single exit at the bottom.
8531 // The point of exit cannot be a branch out of the structured block.
8532 // longjmp() and throw() must not violate the entry/exit criteria.
8533 CS->getCapturedDecl()->setNothrow();
8534 }
Kelvin Lida681182017-01-10 18:08:18 +00008535
8536 OMPLoopDirective::HelperExprs B;
8537 // In presence of clause 'collapse' with number of loops, it will
8538 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008539 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00008540 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008541 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00008542 VarsWithImplicitDSA, B);
8543 if (NestedLoopCount == 0)
8544 return StmtError();
8545
8546 assert((CurContext->isDependentContext() || B.builtAll()) &&
8547 "omp target teams distribute simd loop exprs were not built");
8548
Alexey Bataev438388c2017-11-22 18:34:02 +00008549 if (!CurContext->isDependentContext()) {
8550 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008551 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008552 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8553 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8554 B.NumIterations, *this, CurScope,
8555 DSAStack))
8556 return StmtError();
8557 }
8558 }
8559
8560 if (checkSimdlenSafelenSpecified(*this, Clauses))
8561 return StmtError();
8562
Reid Kleckner87a31802018-03-12 21:43:02 +00008563 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00008564 return OMPTargetTeamsDistributeSimdDirective::Create(
8565 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8566}
8567
Alexey Bataeved09d242014-05-28 05:53:51 +00008568OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008569 SourceLocation StartLoc,
8570 SourceLocation LParenLoc,
8571 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008572 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008573 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00008574 case OMPC_final:
8575 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8576 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00008577 case OMPC_num_threads:
8578 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8579 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008580 case OMPC_safelen:
8581 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8582 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00008583 case OMPC_simdlen:
8584 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8585 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00008586 case OMPC_allocator:
8587 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
8588 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00008589 case OMPC_collapse:
8590 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8591 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008592 case OMPC_ordered:
8593 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8594 break;
Michael Wonge710d542015-08-07 16:16:36 +00008595 case OMPC_device:
8596 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8597 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00008598 case OMPC_num_teams:
8599 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8600 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008601 case OMPC_thread_limit:
8602 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8603 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00008604 case OMPC_priority:
8605 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8606 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008607 case OMPC_grainsize:
8608 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8609 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00008610 case OMPC_num_tasks:
8611 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8612 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00008613 case OMPC_hint:
8614 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8615 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008616 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008617 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008618 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008619 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008620 case OMPC_private:
8621 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008622 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008623 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008624 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008625 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008626 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008627 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008628 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008629 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008630 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00008631 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008632 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008633 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008634 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008635 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008636 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008637 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008638 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008639 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008640 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008641 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008642 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00008643 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008644 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008645 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00008646 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008647 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008648 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008649 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008650 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008651 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008652 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008653 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008654 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00008655 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00008656 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00008657 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00008658 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00008659 case OMPC_atomic_default_mem_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008660 llvm_unreachable("Clause is not allowed.");
8661 }
8662 return Res;
8663}
8664
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008665// An OpenMP directive such as 'target parallel' has two captured regions:
8666// for the 'target' and 'parallel' respectively. This function returns
8667// the region in which to capture expressions associated with a clause.
8668// A return value of OMPD_unknown signifies that the expression should not
8669// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008670static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
8671 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
8672 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008673 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008674 switch (CKind) {
8675 case OMPC_if:
8676 switch (DKind) {
8677 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008678 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008679 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008680 // If this clause applies to the nested 'parallel' region, capture within
8681 // the 'target' region, otherwise do not capture.
8682 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8683 CaptureRegion = OMPD_target;
8684 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00008685 case OMPD_target_teams_distribute_parallel_for:
8686 case OMPD_target_teams_distribute_parallel_for_simd:
8687 // If this clause applies to the nested 'parallel' region, capture within
8688 // the 'teams' region, otherwise do not capture.
8689 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8690 CaptureRegion = OMPD_teams;
8691 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008692 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008693 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008694 CaptureRegion = OMPD_teams;
8695 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008696 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008697 case OMPD_target_enter_data:
8698 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008699 CaptureRegion = OMPD_task;
8700 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008701 case OMPD_cancel:
8702 case OMPD_parallel:
8703 case OMPD_parallel_sections:
8704 case OMPD_parallel_for:
8705 case OMPD_parallel_for_simd:
8706 case OMPD_target:
8707 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008708 case OMPD_target_teams:
8709 case OMPD_target_teams_distribute:
8710 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008711 case OMPD_distribute_parallel_for:
8712 case OMPD_distribute_parallel_for_simd:
8713 case OMPD_task:
8714 case OMPD_taskloop:
8715 case OMPD_taskloop_simd:
8716 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008717 // Do not capture if-clause expressions.
8718 break;
8719 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008720 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008721 case OMPD_taskyield:
8722 case OMPD_barrier:
8723 case OMPD_taskwait:
8724 case OMPD_cancellation_point:
8725 case OMPD_flush:
8726 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008727 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008728 case OMPD_declare_simd:
8729 case OMPD_declare_target:
8730 case OMPD_end_declare_target:
8731 case OMPD_teams:
8732 case OMPD_simd:
8733 case OMPD_for:
8734 case OMPD_for_simd:
8735 case OMPD_sections:
8736 case OMPD_section:
8737 case OMPD_single:
8738 case OMPD_master:
8739 case OMPD_critical:
8740 case OMPD_taskgroup:
8741 case OMPD_distribute:
8742 case OMPD_ordered:
8743 case OMPD_atomic:
8744 case OMPD_distribute_simd:
8745 case OMPD_teams_distribute:
8746 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008747 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008748 llvm_unreachable("Unexpected OpenMP directive with if-clause");
8749 case OMPD_unknown:
8750 llvm_unreachable("Unknown OpenMP directive");
8751 }
8752 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008753 case OMPC_num_threads:
8754 switch (DKind) {
8755 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008756 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008757 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008758 CaptureRegion = OMPD_target;
8759 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008760 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008761 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008762 case OMPD_target_teams_distribute_parallel_for:
8763 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008764 CaptureRegion = OMPD_teams;
8765 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008766 case OMPD_parallel:
8767 case OMPD_parallel_sections:
8768 case OMPD_parallel_for:
8769 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008770 case OMPD_distribute_parallel_for:
8771 case OMPD_distribute_parallel_for_simd:
8772 // Do not capture num_threads-clause expressions.
8773 break;
8774 case OMPD_target_data:
8775 case OMPD_target_enter_data:
8776 case OMPD_target_exit_data:
8777 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008778 case OMPD_target:
8779 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008780 case OMPD_target_teams:
8781 case OMPD_target_teams_distribute:
8782 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008783 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008784 case OMPD_task:
8785 case OMPD_taskloop:
8786 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008787 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008788 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008789 case OMPD_taskyield:
8790 case OMPD_barrier:
8791 case OMPD_taskwait:
8792 case OMPD_cancellation_point:
8793 case OMPD_flush:
8794 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008795 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008796 case OMPD_declare_simd:
8797 case OMPD_declare_target:
8798 case OMPD_end_declare_target:
8799 case OMPD_teams:
8800 case OMPD_simd:
8801 case OMPD_for:
8802 case OMPD_for_simd:
8803 case OMPD_sections:
8804 case OMPD_section:
8805 case OMPD_single:
8806 case OMPD_master:
8807 case OMPD_critical:
8808 case OMPD_taskgroup:
8809 case OMPD_distribute:
8810 case OMPD_ordered:
8811 case OMPD_atomic:
8812 case OMPD_distribute_simd:
8813 case OMPD_teams_distribute:
8814 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008815 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008816 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8817 case OMPD_unknown:
8818 llvm_unreachable("Unknown OpenMP directive");
8819 }
8820 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008821 case OMPC_num_teams:
8822 switch (DKind) {
8823 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008824 case OMPD_target_teams_distribute:
8825 case OMPD_target_teams_distribute_simd:
8826 case OMPD_target_teams_distribute_parallel_for:
8827 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008828 CaptureRegion = OMPD_target;
8829 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008830 case OMPD_teams_distribute_parallel_for:
8831 case OMPD_teams_distribute_parallel_for_simd:
8832 case OMPD_teams:
8833 case OMPD_teams_distribute:
8834 case OMPD_teams_distribute_simd:
8835 // Do not capture num_teams-clause expressions.
8836 break;
8837 case OMPD_distribute_parallel_for:
8838 case OMPD_distribute_parallel_for_simd:
8839 case OMPD_task:
8840 case OMPD_taskloop:
8841 case OMPD_taskloop_simd:
8842 case OMPD_target_data:
8843 case OMPD_target_enter_data:
8844 case OMPD_target_exit_data:
8845 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008846 case OMPD_cancel:
8847 case OMPD_parallel:
8848 case OMPD_parallel_sections:
8849 case OMPD_parallel_for:
8850 case OMPD_parallel_for_simd:
8851 case OMPD_target:
8852 case OMPD_target_simd:
8853 case OMPD_target_parallel:
8854 case OMPD_target_parallel_for:
8855 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008856 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008857 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008858 case OMPD_taskyield:
8859 case OMPD_barrier:
8860 case OMPD_taskwait:
8861 case OMPD_cancellation_point:
8862 case OMPD_flush:
8863 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008864 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008865 case OMPD_declare_simd:
8866 case OMPD_declare_target:
8867 case OMPD_end_declare_target:
8868 case OMPD_simd:
8869 case OMPD_for:
8870 case OMPD_for_simd:
8871 case OMPD_sections:
8872 case OMPD_section:
8873 case OMPD_single:
8874 case OMPD_master:
8875 case OMPD_critical:
8876 case OMPD_taskgroup:
8877 case OMPD_distribute:
8878 case OMPD_ordered:
8879 case OMPD_atomic:
8880 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008881 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008882 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8883 case OMPD_unknown:
8884 llvm_unreachable("Unknown OpenMP directive");
8885 }
8886 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008887 case OMPC_thread_limit:
8888 switch (DKind) {
8889 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008890 case OMPD_target_teams_distribute:
8891 case OMPD_target_teams_distribute_simd:
8892 case OMPD_target_teams_distribute_parallel_for:
8893 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008894 CaptureRegion = OMPD_target;
8895 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008896 case OMPD_teams_distribute_parallel_for:
8897 case OMPD_teams_distribute_parallel_for_simd:
8898 case OMPD_teams:
8899 case OMPD_teams_distribute:
8900 case OMPD_teams_distribute_simd:
8901 // Do not capture thread_limit-clause expressions.
8902 break;
8903 case OMPD_distribute_parallel_for:
8904 case OMPD_distribute_parallel_for_simd:
8905 case OMPD_task:
8906 case OMPD_taskloop:
8907 case OMPD_taskloop_simd:
8908 case OMPD_target_data:
8909 case OMPD_target_enter_data:
8910 case OMPD_target_exit_data:
8911 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008912 case OMPD_cancel:
8913 case OMPD_parallel:
8914 case OMPD_parallel_sections:
8915 case OMPD_parallel_for:
8916 case OMPD_parallel_for_simd:
8917 case OMPD_target:
8918 case OMPD_target_simd:
8919 case OMPD_target_parallel:
8920 case OMPD_target_parallel_for:
8921 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008922 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008923 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008924 case OMPD_taskyield:
8925 case OMPD_barrier:
8926 case OMPD_taskwait:
8927 case OMPD_cancellation_point:
8928 case OMPD_flush:
8929 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008930 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008931 case OMPD_declare_simd:
8932 case OMPD_declare_target:
8933 case OMPD_end_declare_target:
8934 case OMPD_simd:
8935 case OMPD_for:
8936 case OMPD_for_simd:
8937 case OMPD_sections:
8938 case OMPD_section:
8939 case OMPD_single:
8940 case OMPD_master:
8941 case OMPD_critical:
8942 case OMPD_taskgroup:
8943 case OMPD_distribute:
8944 case OMPD_ordered:
8945 case OMPD_atomic:
8946 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008947 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008948 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8949 case OMPD_unknown:
8950 llvm_unreachable("Unknown OpenMP directive");
8951 }
8952 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008953 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008954 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008955 case OMPD_parallel_for:
8956 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008957 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008958 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008959 case OMPD_teams_distribute_parallel_for:
8960 case OMPD_teams_distribute_parallel_for_simd:
8961 case OMPD_target_parallel_for:
8962 case OMPD_target_parallel_for_simd:
8963 case OMPD_target_teams_distribute_parallel_for:
8964 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008965 CaptureRegion = OMPD_parallel;
8966 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008967 case OMPD_for:
8968 case OMPD_for_simd:
8969 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008970 break;
8971 case OMPD_task:
8972 case OMPD_taskloop:
8973 case OMPD_taskloop_simd:
8974 case OMPD_target_data:
8975 case OMPD_target_enter_data:
8976 case OMPD_target_exit_data:
8977 case OMPD_target_update:
8978 case OMPD_teams:
8979 case OMPD_teams_distribute:
8980 case OMPD_teams_distribute_simd:
8981 case OMPD_target_teams_distribute:
8982 case OMPD_target_teams_distribute_simd:
8983 case OMPD_target:
8984 case OMPD_target_simd:
8985 case OMPD_target_parallel:
8986 case OMPD_cancel:
8987 case OMPD_parallel:
8988 case OMPD_parallel_sections:
8989 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008990 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008991 case OMPD_taskyield:
8992 case OMPD_barrier:
8993 case OMPD_taskwait:
8994 case OMPD_cancellation_point:
8995 case OMPD_flush:
8996 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00008997 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008998 case OMPD_declare_simd:
8999 case OMPD_declare_target:
9000 case OMPD_end_declare_target:
9001 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009002 case OMPD_sections:
9003 case OMPD_section:
9004 case OMPD_single:
9005 case OMPD_master:
9006 case OMPD_critical:
9007 case OMPD_taskgroup:
9008 case OMPD_distribute:
9009 case OMPD_ordered:
9010 case OMPD_atomic:
9011 case OMPD_distribute_simd:
9012 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00009013 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009014 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9015 case OMPD_unknown:
9016 llvm_unreachable("Unknown OpenMP directive");
9017 }
9018 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009019 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009020 switch (DKind) {
9021 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009022 case OMPD_teams_distribute_parallel_for_simd:
9023 case OMPD_teams_distribute:
9024 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009025 case OMPD_target_teams_distribute_parallel_for:
9026 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009027 case OMPD_target_teams_distribute:
9028 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00009029 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009030 break;
9031 case OMPD_distribute_parallel_for:
9032 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009033 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009034 case OMPD_distribute_simd:
9035 // Do not capture thread_limit-clause expressions.
9036 break;
9037 case OMPD_parallel_for:
9038 case OMPD_parallel_for_simd:
9039 case OMPD_target_parallel_for_simd:
9040 case OMPD_target_parallel_for:
9041 case OMPD_task:
9042 case OMPD_taskloop:
9043 case OMPD_taskloop_simd:
9044 case OMPD_target_data:
9045 case OMPD_target_enter_data:
9046 case OMPD_target_exit_data:
9047 case OMPD_target_update:
9048 case OMPD_teams:
9049 case OMPD_target:
9050 case OMPD_target_simd:
9051 case OMPD_target_parallel:
9052 case OMPD_cancel:
9053 case OMPD_parallel:
9054 case OMPD_parallel_sections:
9055 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009056 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009057 case OMPD_taskyield:
9058 case OMPD_barrier:
9059 case OMPD_taskwait:
9060 case OMPD_cancellation_point:
9061 case OMPD_flush:
9062 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009063 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009064 case OMPD_declare_simd:
9065 case OMPD_declare_target:
9066 case OMPD_end_declare_target:
9067 case OMPD_simd:
9068 case OMPD_for:
9069 case OMPD_for_simd:
9070 case OMPD_sections:
9071 case OMPD_section:
9072 case OMPD_single:
9073 case OMPD_master:
9074 case OMPD_critical:
9075 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009076 case OMPD_ordered:
9077 case OMPD_atomic:
9078 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00009079 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009080 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9081 case OMPD_unknown:
9082 llvm_unreachable("Unknown OpenMP directive");
9083 }
9084 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009085 case OMPC_device:
9086 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009087 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00009088 case OMPD_target_enter_data:
9089 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00009090 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00009091 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00009092 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00009093 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00009094 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00009095 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00009096 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00009097 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00009098 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00009099 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009100 CaptureRegion = OMPD_task;
9101 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009102 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009103 // Do not capture device-clause expressions.
9104 break;
9105 case OMPD_teams_distribute_parallel_for:
9106 case OMPD_teams_distribute_parallel_for_simd:
9107 case OMPD_teams:
9108 case OMPD_teams_distribute:
9109 case OMPD_teams_distribute_simd:
9110 case OMPD_distribute_parallel_for:
9111 case OMPD_distribute_parallel_for_simd:
9112 case OMPD_task:
9113 case OMPD_taskloop:
9114 case OMPD_taskloop_simd:
9115 case OMPD_cancel:
9116 case OMPD_parallel:
9117 case OMPD_parallel_sections:
9118 case OMPD_parallel_for:
9119 case OMPD_parallel_for_simd:
9120 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009121 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009122 case OMPD_taskyield:
9123 case OMPD_barrier:
9124 case OMPD_taskwait:
9125 case OMPD_cancellation_point:
9126 case OMPD_flush:
9127 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009128 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009129 case OMPD_declare_simd:
9130 case OMPD_declare_target:
9131 case OMPD_end_declare_target:
9132 case OMPD_simd:
9133 case OMPD_for:
9134 case OMPD_for_simd:
9135 case OMPD_sections:
9136 case OMPD_section:
9137 case OMPD_single:
9138 case OMPD_master:
9139 case OMPD_critical:
9140 case OMPD_taskgroup:
9141 case OMPD_distribute:
9142 case OMPD_ordered:
9143 case OMPD_atomic:
9144 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009145 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009146 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
9147 case OMPD_unknown:
9148 llvm_unreachable("Unknown OpenMP directive");
9149 }
9150 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009151 case OMPC_firstprivate:
9152 case OMPC_lastprivate:
9153 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009154 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009155 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009156 case OMPC_linear:
9157 case OMPC_default:
9158 case OMPC_proc_bind:
9159 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009160 case OMPC_safelen:
9161 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009162 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009163 case OMPC_collapse:
9164 case OMPC_private:
9165 case OMPC_shared:
9166 case OMPC_aligned:
9167 case OMPC_copyin:
9168 case OMPC_copyprivate:
9169 case OMPC_ordered:
9170 case OMPC_nowait:
9171 case OMPC_untied:
9172 case OMPC_mergeable:
9173 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009174 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009175 case OMPC_flush:
9176 case OMPC_read:
9177 case OMPC_write:
9178 case OMPC_update:
9179 case OMPC_capture:
9180 case OMPC_seq_cst:
9181 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009182 case OMPC_threads:
9183 case OMPC_simd:
9184 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009185 case OMPC_priority:
9186 case OMPC_grainsize:
9187 case OMPC_nogroup:
9188 case OMPC_num_tasks:
9189 case OMPC_hint:
9190 case OMPC_defaultmap:
9191 case OMPC_unknown:
9192 case OMPC_uniform:
9193 case OMPC_to:
9194 case OMPC_from:
9195 case OMPC_use_device_ptr:
9196 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009197 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009198 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009199 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009200 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009201 case OMPC_atomic_default_mem_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009202 llvm_unreachable("Unexpected OpenMP clause.");
9203 }
9204 return CaptureRegion;
9205}
9206
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009207OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9208 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009209 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009210 SourceLocation NameModifierLoc,
9211 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009212 SourceLocation EndLoc) {
9213 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009214 Stmt *HelperValStmt = nullptr;
9215 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009216 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9217 !Condition->isInstantiationDependent() &&
9218 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009219 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009220 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009221 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009222
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009223 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009224
9225 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
9226 CaptureRegion =
9227 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00009228 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009229 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009230 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009231 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9232 HelperValStmt = buildPreInits(Context, Captures);
9233 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009234 }
9235
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009236 return new (Context)
9237 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
9238 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009239}
9240
Alexey Bataev3778b602014-07-17 07:32:53 +00009241OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
9242 SourceLocation StartLoc,
9243 SourceLocation LParenLoc,
9244 SourceLocation EndLoc) {
9245 Expr *ValExpr = Condition;
9246 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9247 !Condition->isInstantiationDependent() &&
9248 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009249 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00009250 if (Val.isInvalid())
9251 return nullptr;
9252
Richard Smith03a4aa32016-06-23 19:02:52 +00009253 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00009254 }
9255
9256 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9257}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009258ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
9259 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00009260 if (!Op)
9261 return ExprError();
9262
9263 class IntConvertDiagnoser : public ICEConvertDiagnoser {
9264 public:
9265 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00009266 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00009267 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9268 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009269 return S.Diag(Loc, diag::err_omp_not_integral) << T;
9270 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009271 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
9272 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009273 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
9274 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009275 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
9276 QualType T,
9277 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009278 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
9279 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009280 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
9281 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009282 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009283 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009284 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009285 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9286 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009287 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
9288 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009289 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
9290 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009291 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009292 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009293 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009294 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
9295 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009296 llvm_unreachable("conversion functions are permitted");
9297 }
9298 } ConvertDiagnoser;
9299 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
9300}
9301
Alexey Bataeve3727102018-04-18 15:57:46 +00009302static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00009303 OpenMPClauseKind CKind,
9304 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009305 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
9306 !ValExpr->isInstantiationDependent()) {
9307 SourceLocation Loc = ValExpr->getExprLoc();
9308 ExprResult Value =
9309 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9310 if (Value.isInvalid())
9311 return false;
9312
9313 ValExpr = Value.get();
9314 // The expression must evaluate to a non-negative integer value.
9315 llvm::APSInt Result;
9316 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00009317 Result.isSigned() &&
9318 !((!StrictlyPositive && Result.isNonNegative()) ||
9319 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009320 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009321 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9322 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009323 return false;
9324 }
9325 }
9326 return true;
9327}
9328
Alexey Bataev568a8332014-03-06 06:15:19 +00009329OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9330 SourceLocation StartLoc,
9331 SourceLocation LParenLoc,
9332 SourceLocation EndLoc) {
9333 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009334 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009335
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009336 // OpenMP [2.5, Restrictions]
9337 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +00009338 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +00009339 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009340 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009341
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009342 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00009343 OpenMPDirectiveKind CaptureRegion =
9344 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9345 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009346 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009347 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009348 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9349 HelperValStmt = buildPreInits(Context, Captures);
9350 }
9351
9352 return new (Context) OMPNumThreadsClause(
9353 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00009354}
9355
Alexey Bataev62c87d22014-03-21 04:51:18 +00009356ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009357 OpenMPClauseKind CKind,
9358 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009359 if (!E)
9360 return ExprError();
9361 if (E->isValueDependent() || E->isTypeDependent() ||
9362 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009363 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009364 llvm::APSInt Result;
9365 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9366 if (ICE.isInvalid())
9367 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009368 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9369 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009370 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009371 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9372 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00009373 return ExprError();
9374 }
Alexander Musman09184fe2014-09-30 05:29:28 +00009375 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9376 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9377 << E->getSourceRange();
9378 return ExprError();
9379 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009380 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9381 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00009382 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009383 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00009384 return ICE;
9385}
9386
9387OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9388 SourceLocation LParenLoc,
9389 SourceLocation EndLoc) {
9390 // OpenMP [2.8.1, simd construct, Description]
9391 // The parameter of the safelen clause must be a constant
9392 // positive integer expression.
9393 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9394 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009395 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009396 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009397 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00009398}
9399
Alexey Bataev66b15b52015-08-21 11:14:16 +00009400OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9401 SourceLocation LParenLoc,
9402 SourceLocation EndLoc) {
9403 // OpenMP [2.8.1, simd construct, Description]
9404 // The parameter of the simdlen clause must be a constant
9405 // positive integer expression.
9406 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9407 if (Simdlen.isInvalid())
9408 return nullptr;
9409 return new (Context)
9410 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9411}
9412
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009413/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +00009414static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
9415 DSAStackTy *Stack) {
9416 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009417 if (!OMPAllocatorHandleT.isNull())
9418 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +00009419 // Build the predefined allocator expressions.
9420 bool ErrorFound = false;
9421 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
9422 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
9423 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
9424 StringRef Allocator =
9425 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
9426 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
9427 auto *VD = dyn_cast_or_null<ValueDecl>(
9428 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
9429 if (!VD) {
9430 ErrorFound = true;
9431 break;
9432 }
9433 QualType AllocatorType =
9434 VD->getType().getNonLValueExprType(S.getASTContext());
9435 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
9436 if (!Res.isUsable()) {
9437 ErrorFound = true;
9438 break;
9439 }
9440 if (OMPAllocatorHandleT.isNull())
9441 OMPAllocatorHandleT = AllocatorType;
9442 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
9443 ErrorFound = true;
9444 break;
9445 }
9446 Stack->setAllocator(AllocatorKind, Res.get());
9447 }
9448 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009449 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
9450 return false;
9451 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00009452 OMPAllocatorHandleT.addConst();
9453 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009454 return true;
9455}
9456
9457OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
9458 SourceLocation LParenLoc,
9459 SourceLocation EndLoc) {
9460 // OpenMP [2.11.3, allocate Directive, Description]
9461 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +00009462 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009463 return nullptr;
9464
9465 ExprResult Allocator = DefaultLvalueConversion(A);
9466 if (Allocator.isInvalid())
9467 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +00009468 Allocator = PerformImplicitConversion(Allocator.get(),
9469 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009470 Sema::AA_Initializing,
9471 /*AllowExplicit=*/true);
9472 if (Allocator.isInvalid())
9473 return nullptr;
9474 return new (Context)
9475 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
9476}
9477
Alexander Musman64d33f12014-06-04 07:53:32 +00009478OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
9479 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00009480 SourceLocation LParenLoc,
9481 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00009482 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009483 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00009484 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009485 // The parameter of the collapse clause must be a constant
9486 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00009487 ExprResult NumForLoopsResult =
9488 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
9489 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00009490 return nullptr;
9491 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00009492 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00009493}
9494
Alexey Bataev10e775f2015-07-30 11:36:16 +00009495OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
9496 SourceLocation EndLoc,
9497 SourceLocation LParenLoc,
9498 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00009499 // OpenMP [2.7.1, loop construct, Description]
9500 // OpenMP [2.8.1, simd construct, Description]
9501 // OpenMP [2.9.6, distribute construct, Description]
9502 // The parameter of the ordered clause must be a constant
9503 // positive integer expression if any.
9504 if (NumForLoops && LParenLoc.isValid()) {
9505 ExprResult NumForLoopsResult =
9506 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
9507 if (NumForLoopsResult.isInvalid())
9508 return nullptr;
9509 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009510 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +00009511 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00009512 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009513 auto *Clause = OMPOrderedClause::Create(
9514 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
9515 StartLoc, LParenLoc, EndLoc);
9516 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
9517 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +00009518}
9519
Alexey Bataeved09d242014-05-28 05:53:51 +00009520OMPClause *Sema::ActOnOpenMPSimpleClause(
9521 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
9522 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009523 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009524 switch (Kind) {
9525 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009526 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00009527 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
9528 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009529 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009530 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00009531 Res = ActOnOpenMPProcBindClause(
9532 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
9533 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009534 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009535 case OMPC_atomic_default_mem_order:
9536 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
9537 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
9538 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9539 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009540 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009541 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009542 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009543 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009544 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009545 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009546 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009547 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009548 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009549 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00009550 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009551 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00009552 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009553 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009554 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00009555 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009556 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009557 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009558 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009559 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009560 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009561 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009562 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009563 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009564 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009565 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009566 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009567 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009568 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009569 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009570 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009571 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009572 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009573 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009574 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009575 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009576 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009577 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009578 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009579 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009580 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009581 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009582 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009583 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009584 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009585 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009586 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009587 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009588 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009589 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009590 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009591 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009592 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009593 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009594 case OMPC_dynamic_allocators:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009595 llvm_unreachable("Clause is not allowed.");
9596 }
9597 return Res;
9598}
9599
Alexey Bataev6402bca2015-12-28 07:25:51 +00009600static std::string
9601getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
9602 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009603 SmallString<256> Buffer;
9604 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +00009605 unsigned Bound = Last >= 2 ? Last - 2 : 0;
9606 unsigned Skipped = Exclude.size();
9607 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +00009608 for (unsigned I = First; I < Last; ++I) {
9609 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009610 --Skipped;
9611 continue;
9612 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009613 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
9614 if (I == Bound - Skipped)
9615 Out << " or ";
9616 else if (I != Bound + 1 - Skipped)
9617 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +00009618 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009619 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +00009620}
9621
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009622OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9623 SourceLocation KindKwLoc,
9624 SourceLocation StartLoc,
9625 SourceLocation LParenLoc,
9626 SourceLocation EndLoc) {
9627 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00009628 static_assert(OMPC_DEFAULT_unknown > 0,
9629 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009630 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009631 << getListOfPossibleValues(OMPC_default, /*First=*/0,
9632 /*Last=*/OMPC_DEFAULT_unknown)
9633 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009634 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009635 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00009636 switch (Kind) {
9637 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009638 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009639 break;
9640 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009641 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009642 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009643 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009644 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00009645 break;
9646 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009647 return new (Context)
9648 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009649}
9650
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009651OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9652 SourceLocation KindKwLoc,
9653 SourceLocation StartLoc,
9654 SourceLocation LParenLoc,
9655 SourceLocation EndLoc) {
9656 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009657 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009658 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
9659 /*Last=*/OMPC_PROC_BIND_unknown)
9660 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009661 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009662 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009663 return new (Context)
9664 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009665}
9666
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009667OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
9668 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
9669 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9670 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
9671 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9672 << getListOfPossibleValues(
9673 OMPC_atomic_default_mem_order, /*First=*/0,
9674 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
9675 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
9676 return nullptr;
9677 }
9678 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
9679 LParenLoc, EndLoc);
9680}
9681
Alexey Bataev56dafe82014-06-20 07:16:17 +00009682OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009683 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009684 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009685 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009686 SourceLocation EndLoc) {
9687 OMPClause *Res = nullptr;
9688 switch (Kind) {
9689 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009690 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
9691 assert(Argument.size() == NumberOfElements &&
9692 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009693 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009694 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
9695 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
9696 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
9697 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
9698 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009699 break;
9700 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009701 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
9702 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
9703 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
9704 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009705 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00009706 case OMPC_dist_schedule:
9707 Res = ActOnOpenMPDistScheduleClause(
9708 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
9709 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
9710 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009711 case OMPC_defaultmap:
9712 enum { Modifier, DefaultmapKind };
9713 Res = ActOnOpenMPDefaultmapClause(
9714 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
9715 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00009716 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
9717 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009718 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00009719 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009720 case OMPC_num_threads:
9721 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009722 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009723 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009724 case OMPC_collapse:
9725 case OMPC_default:
9726 case OMPC_proc_bind:
9727 case OMPC_private:
9728 case OMPC_firstprivate:
9729 case OMPC_lastprivate:
9730 case OMPC_shared:
9731 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009732 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009733 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009734 case OMPC_linear:
9735 case OMPC_aligned:
9736 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009737 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009738 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009739 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009740 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009741 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009742 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009743 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009744 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009745 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009746 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009747 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009748 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009749 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009750 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009751 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009752 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009753 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009754 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009755 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009756 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009757 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009758 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009759 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009760 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009761 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009762 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009763 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009764 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009765 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009766 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009767 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009768 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009769 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009770 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009771 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009772 case OMPC_atomic_default_mem_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009773 llvm_unreachable("Clause is not allowed.");
9774 }
9775 return Res;
9776}
9777
Alexey Bataev6402bca2015-12-28 07:25:51 +00009778static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
9779 OpenMPScheduleClauseModifier M2,
9780 SourceLocation M1Loc, SourceLocation M2Loc) {
9781 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
9782 SmallVector<unsigned, 2> Excluded;
9783 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
9784 Excluded.push_back(M2);
9785 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
9786 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
9787 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
9788 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
9789 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
9790 << getListOfPossibleValues(OMPC_schedule,
9791 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
9792 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9793 Excluded)
9794 << getOpenMPClauseName(OMPC_schedule);
9795 return true;
9796 }
9797 return false;
9798}
9799
Alexey Bataev56dafe82014-06-20 07:16:17 +00009800OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009801 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009802 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009803 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9804 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
9805 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
9806 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
9807 return nullptr;
9808 // OpenMP, 2.7.1, Loop Construct, Restrictions
9809 // Either the monotonic modifier or the nonmonotonic modifier can be specified
9810 // but not both.
9811 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
9812 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
9813 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
9814 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
9815 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
9816 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
9817 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
9818 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
9819 return nullptr;
9820 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009821 if (Kind == OMPC_SCHEDULE_unknown) {
9822 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00009823 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
9824 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
9825 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9826 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9827 Exclude);
9828 } else {
9829 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9830 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009831 }
9832 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
9833 << Values << getOpenMPClauseName(OMPC_schedule);
9834 return nullptr;
9835 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00009836 // OpenMP, 2.7.1, Loop Construct, Restrictions
9837 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
9838 // schedule(guided).
9839 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
9840 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
9841 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
9842 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
9843 diag::err_omp_schedule_nonmonotonic_static);
9844 return nullptr;
9845 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009846 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00009847 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00009848 if (ChunkSize) {
9849 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
9850 !ChunkSize->isInstantiationDependent() &&
9851 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009852 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +00009853 ExprResult Val =
9854 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
9855 if (Val.isInvalid())
9856 return nullptr;
9857
9858 ValExpr = Val.get();
9859
9860 // OpenMP [2.7.1, Restrictions]
9861 // chunk_size must be a loop invariant integer expression with a positive
9862 // value.
9863 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00009864 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
9865 if (Result.isSigned() && !Result.isStrictlyPositive()) {
9866 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009867 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00009868 return nullptr;
9869 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00009870 } else if (getOpenMPCaptureRegionForClause(
9871 DSAStack->getCurrentDirective(), OMPC_schedule) !=
9872 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00009873 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009874 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009875 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +00009876 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9877 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009878 }
9879 }
9880 }
9881
Alexey Bataev6402bca2015-12-28 07:25:51 +00009882 return new (Context)
9883 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00009884 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009885}
9886
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009887OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
9888 SourceLocation StartLoc,
9889 SourceLocation EndLoc) {
9890 OMPClause *Res = nullptr;
9891 switch (Kind) {
9892 case OMPC_ordered:
9893 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
9894 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00009895 case OMPC_nowait:
9896 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
9897 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009898 case OMPC_untied:
9899 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
9900 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009901 case OMPC_mergeable:
9902 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
9903 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009904 case OMPC_read:
9905 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
9906 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00009907 case OMPC_write:
9908 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
9909 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00009910 case OMPC_update:
9911 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
9912 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00009913 case OMPC_capture:
9914 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
9915 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009916 case OMPC_seq_cst:
9917 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
9918 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00009919 case OMPC_threads:
9920 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
9921 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009922 case OMPC_simd:
9923 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
9924 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00009925 case OMPC_nogroup:
9926 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9927 break;
Kelvin Li1408f912018-09-26 04:28:39 +00009928 case OMPC_unified_address:
9929 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
9930 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +00009931 case OMPC_unified_shared_memory:
9932 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9933 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009934 case OMPC_reverse_offload:
9935 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
9936 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009937 case OMPC_dynamic_allocators:
9938 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
9939 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009940 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009941 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009942 case OMPC_num_threads:
9943 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009944 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009945 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009946 case OMPC_collapse:
9947 case OMPC_schedule:
9948 case OMPC_private:
9949 case OMPC_firstprivate:
9950 case OMPC_lastprivate:
9951 case OMPC_shared:
9952 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009953 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009954 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009955 case OMPC_linear:
9956 case OMPC_aligned:
9957 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009958 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009959 case OMPC_default:
9960 case OMPC_proc_bind:
9961 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009962 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009963 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009964 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009965 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009966 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009967 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009968 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009969 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009970 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00009971 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009972 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009973 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009974 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009975 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009976 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009977 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009978 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009979 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009980 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009981 case OMPC_atomic_default_mem_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009982 llvm_unreachable("Clause is not allowed.");
9983 }
9984 return Res;
9985}
9986
Alexey Bataev236070f2014-06-20 11:19:47 +00009987OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9988 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009989 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00009990 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
9991}
9992
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009993OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9994 SourceLocation EndLoc) {
9995 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
9996}
9997
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009998OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9999 SourceLocation EndLoc) {
10000 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
10001}
10002
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010003OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
10004 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010005 return new (Context) OMPReadClause(StartLoc, EndLoc);
10006}
10007
Alexey Bataevdea47612014-07-23 07:46:59 +000010008OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
10009 SourceLocation EndLoc) {
10010 return new (Context) OMPWriteClause(StartLoc, EndLoc);
10011}
10012
Alexey Bataev67a4f222014-07-23 10:25:33 +000010013OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
10014 SourceLocation EndLoc) {
10015 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
10016}
10017
Alexey Bataev459dec02014-07-24 06:46:57 +000010018OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10019 SourceLocation EndLoc) {
10020 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
10021}
10022
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010023OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10024 SourceLocation EndLoc) {
10025 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
10026}
10027
Alexey Bataev346265e2015-09-25 10:37:12 +000010028OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10029 SourceLocation EndLoc) {
10030 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
10031}
10032
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010033OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10034 SourceLocation EndLoc) {
10035 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
10036}
10037
Alexey Bataevb825de12015-12-07 10:51:44 +000010038OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10039 SourceLocation EndLoc) {
10040 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
10041}
10042
Kelvin Li1408f912018-09-26 04:28:39 +000010043OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10044 SourceLocation EndLoc) {
10045 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
10046}
10047
Patrick Lyster4a370b92018-10-01 13:47:43 +000010048OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10049 SourceLocation EndLoc) {
10050 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10051}
10052
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010053OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10054 SourceLocation EndLoc) {
10055 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
10056}
10057
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010058OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10059 SourceLocation EndLoc) {
10060 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
10061}
10062
Alexey Bataevc5e02582014-06-16 07:08:35 +000010063OMPClause *Sema::ActOnOpenMPVarListClause(
10064 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010065 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10066 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10067 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000010068 OpenMPLinearClauseKind LinKind,
10069 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010070 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
10071 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
10072 SourceLocation StartLoc = Locs.StartLoc;
10073 SourceLocation LParenLoc = Locs.LParenLoc;
10074 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010075 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010076 switch (Kind) {
10077 case OMPC_private:
10078 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10079 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010080 case OMPC_firstprivate:
10081 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10082 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010083 case OMPC_lastprivate:
10084 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10085 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010086 case OMPC_shared:
10087 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
10088 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010089 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000010090 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010091 EndLoc, ReductionOrMapperIdScopeSpec,
10092 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010093 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000010094 case OMPC_task_reduction:
10095 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010096 EndLoc, ReductionOrMapperIdScopeSpec,
10097 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000010098 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000010099 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010100 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10101 EndLoc, ReductionOrMapperIdScopeSpec,
10102 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000010103 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000010104 case OMPC_linear:
10105 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010106 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000010107 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010108 case OMPC_aligned:
10109 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
10110 ColonLoc, EndLoc);
10111 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010112 case OMPC_copyin:
10113 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
10114 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010115 case OMPC_copyprivate:
10116 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10117 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000010118 case OMPC_flush:
10119 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
10120 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010121 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000010122 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010123 StartLoc, LParenLoc, EndLoc);
10124 break;
10125 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010126 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
10127 ReductionOrMapperIdScopeSpec,
10128 ReductionOrMapperId, MapType, IsMapTypeImplicit,
10129 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010130 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010131 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000010132 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
10133 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000010134 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000010135 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000010136 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
10137 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000010138 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000010139 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010140 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010141 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000010142 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010143 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010144 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010145 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010146 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000010147 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000010148 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010149 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010150 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000010151 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010152 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010153 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010154 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010155 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010156 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010157 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010158 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010159 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010160 case OMPC_allocate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010161 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010162 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010163 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010164 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010165 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000010166 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010167 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010168 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010169 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010170 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010171 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010172 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000010173 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000010174 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010175 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010176 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010177 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010178 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010179 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000010180 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010181 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010182 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010183 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010184 case OMPC_atomic_default_mem_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010185 llvm_unreachable("Clause is not allowed.");
10186 }
10187 return Res;
10188}
10189
Alexey Bataev90c228f2016-02-08 09:29:13 +000010190ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000010191 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000010192 ExprResult Res = BuildDeclRefExpr(
10193 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
10194 if (!Res.isUsable())
10195 return ExprError();
10196 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
10197 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
10198 if (!Res.isUsable())
10199 return ExprError();
10200 }
10201 if (VK != VK_LValue && Res.get()->isGLValue()) {
10202 Res = DefaultLvalueConversion(Res.get());
10203 if (!Res.isUsable())
10204 return ExprError();
10205 }
10206 return Res;
10207}
10208
Alexey Bataev60da77e2016-02-29 05:54:20 +000010209static std::pair<ValueDecl *, bool>
10210getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
10211 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010212 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
10213 RefExpr->containsUnexpandedParameterPack())
10214 return std::make_pair(nullptr, true);
10215
Alexey Bataevd985eda2016-02-10 11:29:16 +000010216 // OpenMP [3.1, C/C++]
10217 // A list item is a variable name.
10218 // OpenMP [2.9.3.3, Restrictions, p.1]
10219 // A variable that is part of another variable (as an array or
10220 // structure element) cannot appear in a private clause.
10221 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010222 enum {
10223 NoArrayExpr = -1,
10224 ArraySubscript = 0,
10225 OMPArraySection = 1
10226 } IsArrayExpr = NoArrayExpr;
10227 if (AllowArraySection) {
10228 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010229 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010230 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
10231 Base = TempASE->getBase()->IgnoreParenImpCasts();
10232 RefExpr = Base;
10233 IsArrayExpr = ArraySubscript;
10234 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010235 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010236 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
10237 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10238 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
10239 Base = TempASE->getBase()->IgnoreParenImpCasts();
10240 RefExpr = Base;
10241 IsArrayExpr = OMPArraySection;
10242 }
10243 }
10244 ELoc = RefExpr->getExprLoc();
10245 ERange = RefExpr->getSourceRange();
10246 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +000010247 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
10248 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
10249 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
10250 (S.getCurrentThisType().isNull() || !ME ||
10251 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
10252 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010253 if (IsArrayExpr != NoArrayExpr) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010254 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
10255 << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000010256 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010257 S.Diag(ELoc,
10258 AllowArraySection
10259 ? diag::err_omp_expected_var_name_member_expr_or_array_item
10260 : diag::err_omp_expected_var_name_member_expr)
10261 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
10262 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010263 return std::make_pair(nullptr, false);
10264 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010265 return std::make_pair(
10266 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010267}
10268
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010269OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10270 SourceLocation StartLoc,
10271 SourceLocation LParenLoc,
10272 SourceLocation EndLoc) {
10273 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000010274 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000010275 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010276 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010277 SourceLocation ELoc;
10278 SourceRange ERange;
10279 Expr *SimpleRefExpr = RefExpr;
10280 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010281 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010282 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010283 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010284 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010285 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010286 ValueDecl *D = Res.first;
10287 if (!D)
10288 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010289
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010290 QualType Type = D->getType();
10291 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010292
10293 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10294 // A variable that appears in a private clause must not have an incomplete
10295 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010296 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010297 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010298 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010299
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010300 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10301 // A variable that is privatized must not have a const-qualified type
10302 // unless it is of class type with a mutable member. This restriction does
10303 // not apply to the firstprivate clause.
10304 //
10305 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
10306 // A variable that appears in a private clause must not have a
10307 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010308 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010309 continue;
10310
Alexey Bataev758e55e2013-09-06 18:03:48 +000010311 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10312 // in a Construct]
10313 // Variables with the predetermined data-sharing attributes may not be
10314 // listed in data-sharing attributes clauses, except for the cases
10315 // listed below. For these exceptions only, listing a predetermined
10316 // variable in a data-sharing attribute clause is allowed and overrides
10317 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010318 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010319 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010320 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10321 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000010322 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010323 continue;
10324 }
10325
Alexey Bataeve3727102018-04-18 15:57:46 +000010326 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010327 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010328 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000010329 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010330 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10331 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000010332 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010333 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010334 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010335 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010336 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010337 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010338 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010339 continue;
10340 }
10341
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010342 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10343 // A list item cannot appear in both a map clause and a data-sharing
10344 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000010345 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010346 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010347 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010348 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010349 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
10350 OpenMPClauseKind WhereFoundClauseKind) -> bool {
10351 ConflictKind = WhereFoundClauseKind;
10352 return true;
10353 })) {
10354 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010355 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000010356 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000010357 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000010358 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010359 continue;
10360 }
10361 }
10362
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010363 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
10364 // A variable of class type (or array thereof) that appears in a private
10365 // clause requires an accessible, unambiguous default constructor for the
10366 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000010367 // Generate helper private variable and initialize it with the default
10368 // value. The address of the original variable is replaced by the address of
10369 // the new private variable in CodeGen. This new variable is not added to
10370 // IdResolver, so the code in the OpenMP region uses original variable for
10371 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010372 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010373 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010374 buildVarDecl(*this, ELoc, Type, D->getName(),
10375 D->hasAttrs() ? &D->getAttrs() : nullptr,
10376 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000010377 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010378 if (VDPrivate->isInvalidDecl())
10379 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000010380 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010381 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010382
Alexey Bataev90c228f2016-02-08 09:29:13 +000010383 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010384 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010385 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000010386 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010387 Vars.push_back((VD || CurContext->isDependentContext())
10388 ? RefExpr->IgnoreParens()
10389 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010390 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010391 }
10392
Alexey Bataeved09d242014-05-28 05:53:51 +000010393 if (Vars.empty())
10394 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010395
Alexey Bataev03b340a2014-10-21 03:16:40 +000010396 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10397 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010398}
10399
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010400namespace {
10401class DiagsUninitializedSeveretyRAII {
10402private:
10403 DiagnosticsEngine &Diags;
10404 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000010405 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010406
10407public:
10408 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10409 bool IsIgnored)
10410 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10411 if (!IsIgnored) {
10412 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10413 /*Map*/ diag::Severity::Ignored, Loc);
10414 }
10415 }
10416 ~DiagsUninitializedSeveretyRAII() {
10417 if (!IsIgnored)
10418 Diags.popMappings(SavedLoc);
10419 }
10420};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010421}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010422
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010423OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10424 SourceLocation StartLoc,
10425 SourceLocation LParenLoc,
10426 SourceLocation EndLoc) {
10427 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010428 SmallVector<Expr *, 8> PrivateCopies;
10429 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000010430 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010431 bool IsImplicitClause =
10432 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000010433 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010434
Alexey Bataeve3727102018-04-18 15:57:46 +000010435 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010436 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010437 SourceLocation ELoc;
10438 SourceRange ERange;
10439 Expr *SimpleRefExpr = RefExpr;
10440 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010441 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010442 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010443 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010444 PrivateCopies.push_back(nullptr);
10445 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010446 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010447 ValueDecl *D = Res.first;
10448 if (!D)
10449 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010450
Alexey Bataev60da77e2016-02-29 05:54:20 +000010451 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010452 QualType Type = D->getType();
10453 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010454
10455 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10456 // A variable that appears in a private clause must not have an incomplete
10457 // type or a reference type.
10458 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000010459 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010460 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010461 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010462
10463 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10464 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000010465 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010466 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000010467 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010468
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010469 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000010470 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010471 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010472 DSAStackTy::DSAVarData DVar =
10473 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000010474 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010475 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010476 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010477 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10478 // A list item that specifies a given variable may not appear in more
10479 // than one clause on the same directive, except that a variable may be
10480 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010481 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10482 // A list item may appear in a firstprivate or lastprivate clause but not
10483 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010484 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010485 (isOpenMPDistributeDirective(CurrDir) ||
10486 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010487 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010488 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010489 << getOpenMPClauseName(DVar.CKind)
10490 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010491 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010492 continue;
10493 }
10494
10495 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10496 // in a Construct]
10497 // Variables with the predetermined data-sharing attributes may not be
10498 // listed in data-sharing attributes clauses, except for the cases
10499 // listed below. For these exceptions only, listing a predetermined
10500 // variable in a data-sharing attribute clause is allowed and overrides
10501 // the variable's predetermined data-sharing attributes.
10502 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10503 // in a Construct, C/C++, p.2]
10504 // Variables with const-qualified type having no mutable member may be
10505 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000010506 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010507 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
10508 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010509 << getOpenMPClauseName(DVar.CKind)
10510 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010511 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010512 continue;
10513 }
10514
10515 // OpenMP [2.9.3.4, Restrictions, p.2]
10516 // A list item that is private within a parallel region must not appear
10517 // in a firstprivate clause on a worksharing construct if any of the
10518 // worksharing regions arising from the worksharing construct ever bind
10519 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010520 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10521 // A list item that is private within a teams region must not appear in a
10522 // firstprivate clause on a distribute construct if any of the distribute
10523 // regions arising from the distribute construct ever bind to any of the
10524 // teams regions arising from the teams construct.
10525 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10526 // A list item that appears in a reduction clause of a teams construct
10527 // must not appear in a firstprivate clause on a distribute construct if
10528 // any of the distribute regions arising from the distribute construct
10529 // ever bind to any of the teams regions arising from the teams construct.
10530 if ((isOpenMPWorksharingDirective(CurrDir) ||
10531 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010532 !isOpenMPParallelDirective(CurrDir) &&
10533 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010534 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010535 if (DVar.CKind != OMPC_shared &&
10536 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010537 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010538 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000010539 Diag(ELoc, diag::err_omp_required_access)
10540 << getOpenMPClauseName(OMPC_firstprivate)
10541 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010542 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010543 continue;
10544 }
10545 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010546 // OpenMP [2.9.3.4, Restrictions, p.3]
10547 // A list item that appears in a reduction clause of a parallel construct
10548 // must not appear in a firstprivate clause on a worksharing or task
10549 // construct if any of the worksharing or task regions arising from the
10550 // worksharing or task construct ever bind to any of the parallel regions
10551 // arising from the parallel construct.
10552 // OpenMP [2.9.3.4, Restrictions, p.4]
10553 // A list item that appears in a reduction clause in worksharing
10554 // construct must not appear in a firstprivate clause in a task construct
10555 // encountered during execution of any of the worksharing regions arising
10556 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000010557 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010558 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010559 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10560 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010561 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010562 isOpenMPWorksharingDirective(K) ||
10563 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010564 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010565 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010566 if (DVar.CKind == OMPC_reduction &&
10567 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010568 isOpenMPWorksharingDirective(DVar.DKind) ||
10569 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010570 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10571 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000010572 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010573 continue;
10574 }
10575 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010576
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010577 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10578 // A list item cannot appear in both a map clause and a data-sharing
10579 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +000010580 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010581 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010582 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010583 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000010584 [&ConflictKind](
10585 OMPClauseMappableExprCommon::MappableExprComponentListRef,
10586 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000010587 ConflictKind = WhereFoundClauseKind;
10588 return true;
10589 })) {
10590 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010591 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000010592 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010593 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000010594 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010595 continue;
10596 }
10597 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010598 }
10599
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010600 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010601 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000010602 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010603 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10604 << getOpenMPClauseName(OMPC_firstprivate) << Type
10605 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10606 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010607 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010608 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010609 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010610 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000010611 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010612 continue;
10613 }
10614
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010615 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010616 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010617 buildVarDecl(*this, ELoc, Type, D->getName(),
10618 D->hasAttrs() ? &D->getAttrs() : nullptr,
10619 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010620 // Generate helper private variable and initialize it with the value of the
10621 // original variable. The address of the original variable is replaced by
10622 // the address of the new private variable in the CodeGen. This new variable
10623 // is not added to IdResolver, so the code in the OpenMP region uses
10624 // original variable for proper diagnostics and variable capturing.
10625 Expr *VDInitRefExpr = nullptr;
10626 // For arrays generate initializer for single element and replace it by the
10627 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010628 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010629 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010630 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010631 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010632 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010633 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010634 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
10635 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000010636 InitializedEntity Entity =
10637 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010638 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
10639
10640 InitializationSequence InitSeq(*this, Entity, Kind, Init);
10641 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
10642 if (Result.isInvalid())
10643 VDPrivate->setInvalidDecl();
10644 else
10645 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010646 // Remove temp variable declaration.
10647 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010648 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000010649 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
10650 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000010651 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10652 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000010653 AddInitializerToDecl(VDPrivate,
10654 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010655 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010656 }
10657 if (VDPrivate->isInvalidDecl()) {
10658 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010659 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010660 diag::note_omp_task_predetermined_firstprivate_here);
10661 }
10662 continue;
10663 }
10664 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010665 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000010666 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10667 RefExpr->getExprLoc());
10668 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010669 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010670 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010671 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010672 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010673 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010674 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010675 ExprCaptures.push_back(Ref->getDecl());
10676 }
Alexey Bataev417089f2016-02-17 13:19:37 +000010677 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010678 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010679 Vars.push_back((VD || CurContext->isDependentContext())
10680 ? RefExpr->IgnoreParens()
10681 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010682 PrivateCopies.push_back(VDPrivateRefExpr);
10683 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010684 }
10685
Alexey Bataeved09d242014-05-28 05:53:51 +000010686 if (Vars.empty())
10687 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010688
10689 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010690 Vars, PrivateCopies, Inits,
10691 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010692}
10693
Alexander Musman1bb328c2014-06-04 13:06:39 +000010694OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
10695 SourceLocation StartLoc,
10696 SourceLocation LParenLoc,
10697 SourceLocation EndLoc) {
10698 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000010699 SmallVector<Expr *, 8> SrcExprs;
10700 SmallVector<Expr *, 8> DstExprs;
10701 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000010702 SmallVector<Decl *, 4> ExprCaptures;
10703 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000010704 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010705 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010706 SourceLocation ELoc;
10707 SourceRange ERange;
10708 Expr *SimpleRefExpr = RefExpr;
10709 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000010710 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010711 // It will be analyzed later.
10712 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010713 SrcExprs.push_back(nullptr);
10714 DstExprs.push_back(nullptr);
10715 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010716 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010717 ValueDecl *D = Res.first;
10718 if (!D)
10719 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010720
Alexey Bataev74caaf22016-02-20 04:09:36 +000010721 QualType Type = D->getType();
10722 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010723
10724 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
10725 // A variable that appears in a lastprivate clause must not have an
10726 // incomplete type or a reference type.
10727 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000010728 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000010729 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010730 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010731
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010732 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10733 // A variable that is privatized must not have a const-qualified type
10734 // unless it is of class type with a mutable member. This restriction does
10735 // not apply to the firstprivate clause.
10736 //
10737 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
10738 // A variable that appears in a lastprivate clause must not have a
10739 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010740 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010741 continue;
10742
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010743 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010744 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10745 // in a Construct]
10746 // Variables with the predetermined data-sharing attributes may not be
10747 // listed in data-sharing attributes clauses, except for the cases
10748 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010749 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10750 // A list item may appear in a firstprivate or lastprivate clause but not
10751 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000010752 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010753 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010754 (isOpenMPDistributeDirective(CurrDir) ||
10755 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000010756 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
10757 Diag(ELoc, diag::err_omp_wrong_dsa)
10758 << getOpenMPClauseName(DVar.CKind)
10759 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010760 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010761 continue;
10762 }
10763
Alexey Bataevf29276e2014-06-18 04:14:57 +000010764 // OpenMP [2.14.3.5, Restrictions, p.2]
10765 // A list item that is private within a parallel region, or that appears in
10766 // the reduction clause of a parallel construct, must not appear in a
10767 // lastprivate clause on a worksharing construct if any of the corresponding
10768 // worksharing regions ever binds to any of the corresponding parallel
10769 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000010770 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000010771 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010772 !isOpenMPParallelDirective(CurrDir) &&
10773 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000010774 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010775 if (DVar.CKind != OMPC_shared) {
10776 Diag(ELoc, diag::err_omp_required_access)
10777 << getOpenMPClauseName(OMPC_lastprivate)
10778 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010779 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010780 continue;
10781 }
10782 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010783
Alexander Musman1bb328c2014-06-04 13:06:39 +000010784 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000010785 // A variable of class type (or array thereof) that appears in a
10786 // lastprivate clause requires an accessible, unambiguous default
10787 // constructor for the class type, unless the list item is also specified
10788 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000010789 // A variable of class type (or array thereof) that appears in a
10790 // lastprivate clause requires an accessible, unambiguous copy assignment
10791 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000010792 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010793 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
10794 Type.getUnqualifiedType(), ".lastprivate.src",
10795 D->hasAttrs() ? &D->getAttrs() : nullptr);
10796 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000010797 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010798 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010799 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000010800 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000010801 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000010802 // For arrays generate assignment operation for single element and replace
10803 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010804 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
10805 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010806 if (AssignmentOp.isInvalid())
10807 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000010808 AssignmentOp =
10809 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000010810 if (AssignmentOp.isInvalid())
10811 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010812
Alexey Bataev74caaf22016-02-20 04:09:36 +000010813 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010814 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010815 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010816 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010817 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010818 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000010819 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010820 ExprCaptures.push_back(Ref->getDecl());
10821 }
10822 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000010823 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010824 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010825 ExprResult RefRes = DefaultLvalueConversion(Ref);
10826 if (!RefRes.isUsable())
10827 continue;
10828 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010829 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10830 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010831 if (!PostUpdateRes.isUsable())
10832 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010833 ExprPostUpdates.push_back(
10834 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010835 }
10836 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010837 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010838 Vars.push_back((VD || CurContext->isDependentContext())
10839 ? RefExpr->IgnoreParens()
10840 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000010841 SrcExprs.push_back(PseudoSrcExpr);
10842 DstExprs.push_back(PseudoDstExpr);
10843 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000010844 }
10845
10846 if (Vars.empty())
10847 return nullptr;
10848
10849 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000010850 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010851 buildPreInits(Context, ExprCaptures),
10852 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000010853}
10854
Alexey Bataev758e55e2013-09-06 18:03:48 +000010855OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10856 SourceLocation StartLoc,
10857 SourceLocation LParenLoc,
10858 SourceLocation EndLoc) {
10859 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000010860 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010861 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010862 SourceLocation ELoc;
10863 SourceRange ERange;
10864 Expr *SimpleRefExpr = RefExpr;
10865 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010866 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000010867 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010868 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010869 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010870 ValueDecl *D = Res.first;
10871 if (!D)
10872 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010873
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010874 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010875 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10876 // in a Construct]
10877 // Variables with the predetermined data-sharing attributes may not be
10878 // listed in data-sharing attributes clauses, except for the cases
10879 // listed below. For these exceptions only, listing a predetermined
10880 // variable in a data-sharing attribute clause is allowed and overrides
10881 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010882 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000010883 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
10884 DVar.RefExpr) {
10885 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10886 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010887 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010888 continue;
10889 }
10890
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010891 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010892 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010893 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010894 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010895 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
10896 ? RefExpr->IgnoreParens()
10897 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010898 }
10899
Alexey Bataeved09d242014-05-28 05:53:51 +000010900 if (Vars.empty())
10901 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010902
10903 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
10904}
10905
Alexey Bataevc5e02582014-06-16 07:08:35 +000010906namespace {
10907class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
10908 DSAStackTy *Stack;
10909
10910public:
10911 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010912 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
10913 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010914 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
10915 return false;
10916 if (DVar.CKind != OMPC_unknown)
10917 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010918 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010919 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010920 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010921 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010922 }
10923 return false;
10924 }
10925 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010926 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010927 if (Child && Visit(Child))
10928 return true;
10929 }
10930 return false;
10931 }
Alexey Bataev23b69422014-06-18 07:08:49 +000010932 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010933};
Alexey Bataev23b69422014-06-18 07:08:49 +000010934} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000010935
Alexey Bataev60da77e2016-02-29 05:54:20 +000010936namespace {
10937// Transform MemberExpression for specified FieldDecl of current class to
10938// DeclRefExpr to specified OMPCapturedExprDecl.
10939class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
10940 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000010941 ValueDecl *Field = nullptr;
10942 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010943
10944public:
10945 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
10946 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
10947
10948 ExprResult TransformMemberExpr(MemberExpr *E) {
10949 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
10950 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000010951 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010952 return CapturedExpr;
10953 }
10954 return BaseTransform::TransformMemberExpr(E);
10955 }
10956 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
10957};
10958} // namespace
10959
Alexey Bataev97d18bf2018-04-11 19:21:00 +000010960template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000010961static T filterLookupForUDReductionAndMapper(
10962 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010963 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010964 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010965 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010966 return Res;
10967 }
10968 }
10969 return T();
10970}
10971
Alexey Bataev43b90b72018-09-12 16:31:59 +000010972static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
10973 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
10974
10975 for (auto RD : D->redecls()) {
10976 // Don't bother with extra checks if we already know this one isn't visible.
10977 if (RD == D)
10978 continue;
10979
10980 auto ND = cast<NamedDecl>(RD);
10981 if (LookupResult::isVisible(SemaRef, ND))
10982 return ND;
10983 }
10984
10985 return nullptr;
10986}
10987
10988static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000010989argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000010990 SourceLocation Loc, QualType Ty,
10991 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
10992 // Find all of the associated namespaces and classes based on the
10993 // arguments we have.
10994 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10995 Sema::AssociatedClassSet AssociatedClasses;
10996 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
10997 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
10998 AssociatedClasses);
10999
11000 // C++ [basic.lookup.argdep]p3:
11001 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11002 // and let Y be the lookup set produced by argument dependent
11003 // lookup (defined as follows). If X contains [...] then Y is
11004 // empty. Otherwise Y is the set of declarations found in the
11005 // namespaces associated with the argument types as described
11006 // below. The set of declarations found by the lookup of the name
11007 // is the union of X and Y.
11008 //
11009 // Here, we compute Y and add its members to the overloaded
11010 // candidate set.
11011 for (auto *NS : AssociatedNamespaces) {
11012 // When considering an associated namespace, the lookup is the
11013 // same as the lookup performed when the associated namespace is
11014 // used as a qualifier (3.4.3.2) except that:
11015 //
11016 // -- Any using-directives in the associated namespace are
11017 // ignored.
11018 //
11019 // -- Any namespace-scope friend functions declared in
11020 // associated classes are visible within their respective
11021 // namespaces even if they are not visible during an ordinary
11022 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000011023 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000011024 for (auto *D : R) {
11025 auto *Underlying = D;
11026 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11027 Underlying = USD->getTargetDecl();
11028
Michael Kruse4304e9d2019-02-19 16:38:20 +000011029 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
11030 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000011031 continue;
11032
11033 if (!SemaRef.isVisible(D)) {
11034 D = findAcceptableDecl(SemaRef, D);
11035 if (!D)
11036 continue;
11037 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11038 Underlying = USD->getTargetDecl();
11039 }
11040 Lookups.emplace_back();
11041 Lookups.back().addDecl(Underlying);
11042 }
11043 }
11044}
11045
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011046static ExprResult
11047buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
11048 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
11049 const DeclarationNameInfo &ReductionId, QualType Ty,
11050 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
11051 if (ReductionIdScopeSpec.isInvalid())
11052 return ExprError();
11053 SmallVector<UnresolvedSet<8>, 4> Lookups;
11054 if (S) {
11055 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11056 Lookup.suppressDiagnostics();
11057 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011058 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011059 do {
11060 S = S->getParent();
11061 } while (S && !S->isDeclScope(D));
11062 if (S)
11063 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000011064 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011065 Lookups.back().append(Lookup.begin(), Lookup.end());
11066 Lookup.clear();
11067 }
11068 } else if (auto *ULE =
11069 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
11070 Lookups.push_back(UnresolvedSet<8>());
11071 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011072 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011073 if (D == PrevD)
11074 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000011075 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011076 Lookups.back().addDecl(DRD);
11077 PrevD = D;
11078 }
11079 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000011080 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
11081 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011082 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000011083 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011084 return !D->isInvalidDecl() &&
11085 (D->getType()->isDependentType() ||
11086 D->getType()->isInstantiationDependentType() ||
11087 D->getType()->containsUnexpandedParameterPack());
11088 })) {
11089 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000011090 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000011091 if (Set.empty())
11092 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011093 ResSet.append(Set.begin(), Set.end());
11094 // The last item marks the end of all declarations at the specified scope.
11095 ResSet.addDecl(Set[Set.size() - 1]);
11096 }
11097 return UnresolvedLookupExpr::Create(
11098 SemaRef.Context, /*NamingClass=*/nullptr,
11099 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
11100 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
11101 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000011102 // Lookup inside the classes.
11103 // C++ [over.match.oper]p3:
11104 // For a unary operator @ with an operand of a type whose
11105 // cv-unqualified version is T1, and for a binary operator @ with
11106 // a left operand of a type whose cv-unqualified version is T1 and
11107 // a right operand of a type whose cv-unqualified version is T2,
11108 // three sets of candidate functions, designated member
11109 // candidates, non-member candidates and built-in candidates, are
11110 // constructed as follows:
11111 // -- If T1 is a complete class type or a class currently being
11112 // defined, the set of member candidates is the result of the
11113 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
11114 // the set of member candidates is empty.
11115 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11116 Lookup.suppressDiagnostics();
11117 if (const auto *TyRec = Ty->getAs<RecordType>()) {
11118 // Complete the type if it can be completed.
11119 // If the type is neither complete nor being defined, bail out now.
11120 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
11121 TyRec->getDecl()->getDefinition()) {
11122 Lookup.clear();
11123 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
11124 if (Lookup.empty()) {
11125 Lookups.emplace_back();
11126 Lookups.back().append(Lookup.begin(), Lookup.end());
11127 }
11128 }
11129 }
11130 // Perform ADL.
Alexey Bataev74a04e82019-03-13 19:31:34 +000011131 if (SemaRef.getLangOpts().CPlusPlus) {
11132 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
11133 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11134 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
11135 if (!D->isInvalidDecl() &&
11136 SemaRef.Context.hasSameType(D->getType(), Ty))
11137 return D;
11138 return nullptr;
11139 }))
11140 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
11141 VK_LValue, Loc);
11142 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11143 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
11144 if (!D->isInvalidDecl() &&
11145 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
11146 !Ty.isMoreQualifiedThan(D->getType()))
11147 return D;
11148 return nullptr;
11149 })) {
11150 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
11151 /*DetectVirtual=*/false);
11152 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
11153 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
11154 VD->getType().getUnqualifiedType()))) {
11155 if (SemaRef.CheckBaseClassAccess(
11156 Loc, VD->getType(), Ty, Paths.front(),
11157 /*DiagID=*/0) != Sema::AR_inaccessible) {
11158 SemaRef.BuildBasePathArray(Paths, BasePath);
11159 return SemaRef.BuildDeclRefExpr(
11160 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
11161 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011162 }
11163 }
11164 }
11165 }
11166 if (ReductionIdScopeSpec.isSet()) {
11167 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
11168 return ExprError();
11169 }
11170 return ExprEmpty();
11171}
11172
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011173namespace {
11174/// Data for the reduction-based clauses.
11175struct ReductionData {
11176 /// List of original reduction items.
11177 SmallVector<Expr *, 8> Vars;
11178 /// List of private copies of the reduction items.
11179 SmallVector<Expr *, 8> Privates;
11180 /// LHS expressions for the reduction_op expressions.
11181 SmallVector<Expr *, 8> LHSs;
11182 /// RHS expressions for the reduction_op expressions.
11183 SmallVector<Expr *, 8> RHSs;
11184 /// Reduction operation expression.
11185 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000011186 /// Taskgroup descriptors for the corresponding reduction items in
11187 /// in_reduction clauses.
11188 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011189 /// List of captures for clause.
11190 SmallVector<Decl *, 4> ExprCaptures;
11191 /// List of postupdate expressions.
11192 SmallVector<Expr *, 4> ExprPostUpdates;
11193 ReductionData() = delete;
11194 /// Reserves required memory for the reduction data.
11195 ReductionData(unsigned Size) {
11196 Vars.reserve(Size);
11197 Privates.reserve(Size);
11198 LHSs.reserve(Size);
11199 RHSs.reserve(Size);
11200 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000011201 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011202 ExprCaptures.reserve(Size);
11203 ExprPostUpdates.reserve(Size);
11204 }
11205 /// Stores reduction item and reduction operation only (required for dependent
11206 /// reduction item).
11207 void push(Expr *Item, Expr *ReductionOp) {
11208 Vars.emplace_back(Item);
11209 Privates.emplace_back(nullptr);
11210 LHSs.emplace_back(nullptr);
11211 RHSs.emplace_back(nullptr);
11212 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011213 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011214 }
11215 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000011216 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
11217 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011218 Vars.emplace_back(Item);
11219 Privates.emplace_back(Private);
11220 LHSs.emplace_back(LHS);
11221 RHSs.emplace_back(RHS);
11222 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011223 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011224 }
11225};
11226} // namespace
11227
Alexey Bataeve3727102018-04-18 15:57:46 +000011228static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011229 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
11230 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
11231 const Expr *Length = OASE->getLength();
11232 if (Length == nullptr) {
11233 // For array sections of the form [1:] or [:], we would need to analyze
11234 // the lower bound...
11235 if (OASE->getColonLoc().isValid())
11236 return false;
11237
11238 // This is an array subscript which has implicit length 1!
11239 SingleElement = true;
11240 ArraySizes.push_back(llvm::APSInt::get(1));
11241 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011242 Expr::EvalResult Result;
11243 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011244 return false;
11245
Fangrui Song407659a2018-11-30 23:41:18 +000011246 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011247 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
11248 ArraySizes.push_back(ConstantLengthValue);
11249 }
11250
11251 // Get the base of this array section and walk up from there.
11252 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
11253
11254 // We require length = 1 for all array sections except the right-most to
11255 // guarantee that the memory region is contiguous and has no holes in it.
11256 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
11257 Length = TempOASE->getLength();
11258 if (Length == nullptr) {
11259 // For array sections of the form [1:] or [:], we would need to analyze
11260 // the lower bound...
11261 if (OASE->getColonLoc().isValid())
11262 return false;
11263
11264 // This is an array subscript which has implicit length 1!
11265 ArraySizes.push_back(llvm::APSInt::get(1));
11266 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011267 Expr::EvalResult Result;
11268 if (!Length->EvaluateAsInt(Result, Context))
11269 return false;
11270
11271 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
11272 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011273 return false;
11274
11275 ArraySizes.push_back(ConstantLengthValue);
11276 }
11277 Base = TempOASE->getBase()->IgnoreParenImpCasts();
11278 }
11279
11280 // If we have a single element, we don't need to add the implicit lengths.
11281 if (!SingleElement) {
11282 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
11283 // Has implicit length 1!
11284 ArraySizes.push_back(llvm::APSInt::get(1));
11285 Base = TempASE->getBase()->IgnoreParenImpCasts();
11286 }
11287 }
11288
11289 // This array section can be privatized as a single value or as a constant
11290 // sized array.
11291 return true;
11292}
11293
Alexey Bataeve3727102018-04-18 15:57:46 +000011294static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000011295 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
11296 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11297 SourceLocation ColonLoc, SourceLocation EndLoc,
11298 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011299 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011300 DeclarationName DN = ReductionId.getName();
11301 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011302 BinaryOperatorKind BOK = BO_Comma;
11303
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011304 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011305 // OpenMP [2.14.3.6, reduction clause]
11306 // C
11307 // reduction-identifier is either an identifier or one of the following
11308 // operators: +, -, *, &, |, ^, && and ||
11309 // C++
11310 // reduction-identifier is either an id-expression or one of the following
11311 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000011312 switch (OOK) {
11313 case OO_Plus:
11314 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011315 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011316 break;
11317 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011318 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011319 break;
11320 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011321 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011322 break;
11323 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011324 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011325 break;
11326 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011327 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011328 break;
11329 case OO_AmpAmp:
11330 BOK = BO_LAnd;
11331 break;
11332 case OO_PipePipe:
11333 BOK = BO_LOr;
11334 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011335 case OO_New:
11336 case OO_Delete:
11337 case OO_Array_New:
11338 case OO_Array_Delete:
11339 case OO_Slash:
11340 case OO_Percent:
11341 case OO_Tilde:
11342 case OO_Exclaim:
11343 case OO_Equal:
11344 case OO_Less:
11345 case OO_Greater:
11346 case OO_LessEqual:
11347 case OO_GreaterEqual:
11348 case OO_PlusEqual:
11349 case OO_MinusEqual:
11350 case OO_StarEqual:
11351 case OO_SlashEqual:
11352 case OO_PercentEqual:
11353 case OO_CaretEqual:
11354 case OO_AmpEqual:
11355 case OO_PipeEqual:
11356 case OO_LessLess:
11357 case OO_GreaterGreater:
11358 case OO_LessLessEqual:
11359 case OO_GreaterGreaterEqual:
11360 case OO_EqualEqual:
11361 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000011362 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011363 case OO_PlusPlus:
11364 case OO_MinusMinus:
11365 case OO_Comma:
11366 case OO_ArrowStar:
11367 case OO_Arrow:
11368 case OO_Call:
11369 case OO_Subscript:
11370 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000011371 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011372 case NUM_OVERLOADED_OPERATORS:
11373 llvm_unreachable("Unexpected reduction identifier");
11374 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000011375 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011376 if (II->isStr("max"))
11377 BOK = BO_GT;
11378 else if (II->isStr("min"))
11379 BOK = BO_LT;
11380 }
11381 break;
11382 }
11383 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011384 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000011385 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011386 else
11387 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011388 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011389
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011390 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11391 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000011392 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011393 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000011394 // OpenMP [2.1, C/C++]
11395 // A list item is a variable or array section, subject to the restrictions
11396 // specified in Section 2.4 on page 42 and in each of the sections
11397 // describing clauses and directives for which a list appears.
11398 // OpenMP [2.14.3.3, Restrictions, p.1]
11399 // A variable that is part of another variable (as an array or
11400 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011401 if (!FirstIter && IR != ER)
11402 ++IR;
11403 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011404 SourceLocation ELoc;
11405 SourceRange ERange;
11406 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011407 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000011408 /*AllowArraySection=*/true);
11409 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011410 // Try to find 'declare reduction' corresponding construct before using
11411 // builtin/overloaded operators.
11412 QualType Type = Context.DependentTy;
11413 CXXCastPath BasePath;
11414 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011415 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011416 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011417 Expr *ReductionOp = nullptr;
11418 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011419 (DeclareReductionRef.isUnset() ||
11420 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011421 ReductionOp = DeclareReductionRef.get();
11422 // It will be analyzed later.
11423 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011424 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011425 ValueDecl *D = Res.first;
11426 if (!D)
11427 continue;
11428
Alexey Bataev88202be2017-07-27 13:20:36 +000011429 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000011430 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011431 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11432 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000011433 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000011434 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011435 } else if (OASE) {
11436 QualType BaseType =
11437 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11438 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000011439 Type = ATy->getElementType();
11440 else
11441 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000011442 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011443 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011444 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000011445 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011446 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000011447
Alexey Bataevc5e02582014-06-16 07:08:35 +000011448 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11449 // A variable that appears in a private clause must not have an incomplete
11450 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000011451 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011452 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011453 continue;
11454 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000011455 // A list item that appears in a reduction clause must not be
11456 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011457 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11458 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011459 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000011460
11461 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011462 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11463 // If a list-item is a reference type then it must bind to the same object
11464 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000011465 if (!ASE && !OASE) {
11466 if (VD) {
11467 VarDecl *VDDef = VD->getDefinition();
11468 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11469 DSARefChecker Check(Stack);
11470 if (Check.Visit(VDDef->getInit())) {
11471 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11472 << getOpenMPClauseName(ClauseKind) << ERange;
11473 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11474 continue;
11475 }
Alexey Bataeva1764212015-09-30 09:22:36 +000011476 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000011477 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011478
Alexey Bataevbc529672018-09-28 19:33:14 +000011479 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11480 // in a Construct]
11481 // Variables with the predetermined data-sharing attributes may not be
11482 // listed in data-sharing attributes clauses, except for the cases
11483 // listed below. For these exceptions only, listing a predetermined
11484 // variable in a data-sharing attribute clause is allowed and overrides
11485 // the variable's predetermined data-sharing attributes.
11486 // OpenMP [2.14.3.6, Restrictions, p.3]
11487 // Any number of reduction clauses can be specified on the directive,
11488 // but a list item can appear only once in the reduction clauses for that
11489 // directive.
11490 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11491 if (DVar.CKind == OMPC_reduction) {
11492 S.Diag(ELoc, diag::err_omp_once_referenced)
11493 << getOpenMPClauseName(ClauseKind);
11494 if (DVar.RefExpr)
11495 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
11496 continue;
11497 }
11498 if (DVar.CKind != OMPC_unknown) {
11499 S.Diag(ELoc, diag::err_omp_wrong_dsa)
11500 << getOpenMPClauseName(DVar.CKind)
11501 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000011502 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011503 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000011504 }
Alexey Bataevbc529672018-09-28 19:33:14 +000011505
11506 // OpenMP [2.14.3.6, Restrictions, p.1]
11507 // A list item that appears in a reduction clause of a worksharing
11508 // construct must be shared in the parallel regions to which any of the
11509 // worksharing regions arising from the worksharing construct bind.
11510 if (isOpenMPWorksharingDirective(CurrDir) &&
11511 !isOpenMPParallelDirective(CurrDir) &&
11512 !isOpenMPTeamsDirective(CurrDir)) {
11513 DVar = Stack->getImplicitDSA(D, true);
11514 if (DVar.CKind != OMPC_shared) {
11515 S.Diag(ELoc, diag::err_omp_required_access)
11516 << getOpenMPClauseName(OMPC_reduction)
11517 << getOpenMPClauseName(OMPC_shared);
11518 reportOriginalDsa(S, Stack, D, DVar);
11519 continue;
11520 }
11521 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000011522 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011523
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011524 // Try to find 'declare reduction' corresponding construct before using
11525 // builtin/overloaded operators.
11526 CXXCastPath BasePath;
11527 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011528 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011529 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11530 if (DeclareReductionRef.isInvalid())
11531 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011532 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011533 (DeclareReductionRef.isUnset() ||
11534 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011535 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011536 continue;
11537 }
11538 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
11539 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011540 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011541 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011542 << Type << ReductionIdRange;
11543 continue;
11544 }
11545
11546 // OpenMP [2.14.3.6, reduction clause, Restrictions]
11547 // The type of a list item that appears in a reduction clause must be valid
11548 // for the reduction-identifier. For a max or min reduction in C, the type
11549 // of the list item must be an allowed arithmetic data type: char, int,
11550 // float, double, or _Bool, possibly modified with long, short, signed, or
11551 // unsigned. For a max or min reduction in C++, the type of the list item
11552 // must be an allowed arithmetic data type: char, wchar_t, int, float,
11553 // double, or bool, possibly modified with long, short, signed, or unsigned.
11554 if (DeclareReductionRef.isUnset()) {
11555 if ((BOK == BO_GT || BOK == BO_LT) &&
11556 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011557 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
11558 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000011559 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011560 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011561 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11562 VarDecl::DeclarationOnly;
11563 S.Diag(D->getLocation(),
11564 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011565 << D;
11566 }
11567 continue;
11568 }
11569 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011570 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000011571 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11572 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011573 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011574 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11575 VarDecl::DeclarationOnly;
11576 S.Diag(D->getLocation(),
11577 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011578 << D;
11579 }
11580 continue;
11581 }
11582 }
11583
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011584 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011585 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
11586 D->hasAttrs() ? &D->getAttrs() : nullptr);
11587 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
11588 D->hasAttrs() ? &D->getAttrs() : nullptr);
11589 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011590
11591 // Try if we can determine constant lengths for all array sections and avoid
11592 // the VLA.
11593 bool ConstantLengthOASE = false;
11594 if (OASE) {
11595 bool SingleElement;
11596 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000011597 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011598 Context, OASE, SingleElement, ArraySizes);
11599
11600 // If we don't have a single element, we must emit a constant array type.
11601 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011602 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011603 PrivateTy = Context.getConstantArrayType(
11604 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011605 }
11606 }
11607
11608 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000011609 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000011610 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000011611 if (!Context.getTargetInfo().isVLASupported() &&
11612 S.shouldDiagnoseTargetSupportFromOpenMP()) {
11613 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
11614 S.Diag(ELoc, diag::note_vla_unsupported);
11615 continue;
11616 }
David Majnemer9d168222016-08-05 17:44:54 +000011617 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011618 // Create pseudo array type for private copy. The size for this array will
11619 // be generated during codegen.
11620 // For array subscripts or single variables Private Ty is the same as Type
11621 // (type of the variable or single array element).
11622 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011623 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000011624 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011625 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000011626 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000011627 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011628 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011629 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011630 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000011631 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011632 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
11633 D->hasAttrs() ? &D->getAttrs() : nullptr,
11634 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011635 // Add initializer for private variable.
11636 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011637 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
11638 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011639 if (DeclareReductionRef.isUsable()) {
11640 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
11641 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
11642 if (DRD->getInitializer()) {
11643 Init = DRDRef;
11644 RHSVD->setInit(DRDRef);
11645 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011646 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011647 } else {
11648 switch (BOK) {
11649 case BO_Add:
11650 case BO_Xor:
11651 case BO_Or:
11652 case BO_LOr:
11653 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
11654 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011655 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011656 break;
11657 case BO_Mul:
11658 case BO_LAnd:
11659 if (Type->isScalarType() || Type->isAnyComplexType()) {
11660 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011661 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011662 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011663 break;
11664 case BO_And: {
11665 // '&' reduction op - initializer is '~0'.
11666 QualType OrigType = Type;
11667 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
11668 Type = ComplexTy->getElementType();
11669 if (Type->isRealFloatingType()) {
11670 llvm::APFloat InitValue =
11671 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
11672 /*isIEEE=*/true);
11673 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11674 Type, ELoc);
11675 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011676 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011677 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11678 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11679 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11680 }
11681 if (Init && OrigType->isAnyComplexType()) {
11682 // Init = 0xFFFF + 0xFFFFi;
11683 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011684 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011685 }
11686 Type = OrigType;
11687 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011688 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011689 case BO_LT:
11690 case BO_GT: {
11691 // 'min' reduction op - initializer is 'Largest representable number in
11692 // the reduction list item type'.
11693 // 'max' reduction op - initializer is 'Least representable number in
11694 // the reduction list item type'.
11695 if (Type->isIntegerType() || Type->isPointerType()) {
11696 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000011697 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011698 QualType IntTy =
11699 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
11700 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011701 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
11702 : llvm::APInt::getMinValue(Size)
11703 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
11704 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011705 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11706 if (Type->isPointerType()) {
11707 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000011708 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000011709 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011710 if (CastExpr.isInvalid())
11711 continue;
11712 Init = CastExpr.get();
11713 }
11714 } else if (Type->isRealFloatingType()) {
11715 llvm::APFloat InitValue = llvm::APFloat::getLargest(
11716 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
11717 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11718 Type, ELoc);
11719 }
11720 break;
11721 }
11722 case BO_PtrMemD:
11723 case BO_PtrMemI:
11724 case BO_MulAssign:
11725 case BO_Div:
11726 case BO_Rem:
11727 case BO_Sub:
11728 case BO_Shl:
11729 case BO_Shr:
11730 case BO_LE:
11731 case BO_GE:
11732 case BO_EQ:
11733 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000011734 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011735 case BO_AndAssign:
11736 case BO_XorAssign:
11737 case BO_OrAssign:
11738 case BO_Assign:
11739 case BO_AddAssign:
11740 case BO_SubAssign:
11741 case BO_DivAssign:
11742 case BO_RemAssign:
11743 case BO_ShlAssign:
11744 case BO_ShrAssign:
11745 case BO_Comma:
11746 llvm_unreachable("Unexpected reduction operation");
11747 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011748 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011749 if (Init && DeclareReductionRef.isUnset())
11750 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
11751 else if (!Init)
11752 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011753 if (RHSVD->isInvalidDecl())
11754 continue;
11755 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011756 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
11757 << Type << ReductionIdRange;
11758 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11759 VarDecl::DeclarationOnly;
11760 S.Diag(D->getLocation(),
11761 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000011762 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011763 continue;
11764 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011765 // Store initializer for single element in private copy. Will be used during
11766 // codegen.
11767 PrivateVD->setInit(RHSVD->getInit());
11768 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000011769 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011770 ExprResult ReductionOp;
11771 if (DeclareReductionRef.isUsable()) {
11772 QualType RedTy = DeclareReductionRef.get()->getType();
11773 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011774 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
11775 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011776 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011777 LHS = S.DefaultLvalueConversion(LHS.get());
11778 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011779 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11780 CK_UncheckedDerivedToBase, LHS.get(),
11781 &BasePath, LHS.get()->getValueKind());
11782 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11783 CK_UncheckedDerivedToBase, RHS.get(),
11784 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011785 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011786 FunctionProtoType::ExtProtoInfo EPI;
11787 QualType Params[] = {PtrRedTy, PtrRedTy};
11788 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
11789 auto *OVE = new (Context) OpaqueValueExpr(
11790 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011791 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011792 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000011793 ReductionOp =
11794 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011795 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011796 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011797 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011798 if (ReductionOp.isUsable()) {
11799 if (BOK != BO_LT && BOK != BO_GT) {
11800 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011801 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011802 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011803 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000011804 auto *ConditionalOp = new (Context)
11805 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
11806 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011807 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011808 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011809 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011810 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011811 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011812 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
11813 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011814 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011815 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011816 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011817 }
11818
Alexey Bataevfa312f32017-07-21 18:48:21 +000011819 // OpenMP [2.15.4.6, Restrictions, p.2]
11820 // A list item that appears in an in_reduction clause of a task construct
11821 // must appear in a task_reduction clause of a construct associated with a
11822 // taskgroup region that includes the participating task in its taskgroup
11823 // set. The construct associated with the innermost region that meets this
11824 // condition must specify the same reduction-identifier as the in_reduction
11825 // clause.
11826 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000011827 SourceRange ParentSR;
11828 BinaryOperatorKind ParentBOK;
11829 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000011830 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000011831 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011832 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
11833 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011834 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011835 Stack->getTopMostTaskgroupReductionData(
11836 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011837 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
11838 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
11839 if (!IsParentBOK && !IsParentReductionOp) {
11840 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
11841 continue;
11842 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000011843 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
11844 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
11845 IsParentReductionOp) {
11846 bool EmitError = true;
11847 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
11848 llvm::FoldingSetNodeID RedId, ParentRedId;
11849 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
11850 DeclareReductionRef.get()->Profile(RedId, Context,
11851 /*Canonical=*/true);
11852 EmitError = RedId != ParentRedId;
11853 }
11854 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011855 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000011856 diag::err_omp_reduction_identifier_mismatch)
11857 << ReductionIdRange << RefExpr->getSourceRange();
11858 S.Diag(ParentSR.getBegin(),
11859 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000011860 << ParentSR
11861 << (IsParentBOK ? ParentBOKDSA.RefExpr
11862 : ParentReductionOpDSA.RefExpr)
11863 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000011864 continue;
11865 }
11866 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011867 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
11868 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000011869 }
11870
Alexey Bataev60da77e2016-02-29 05:54:20 +000011871 DeclRefExpr *Ref = nullptr;
11872 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011873 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011874 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011875 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000011876 VarsExpr =
11877 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
11878 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000011879 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011880 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011881 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011882 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011883 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011884 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011885 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011886 if (!RefRes.isUsable())
11887 continue;
11888 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011889 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11890 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011891 if (!PostUpdateRes.isUsable())
11892 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011893 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
11894 Stack->getCurrentDirective() == OMPD_taskgroup) {
11895 S.Diag(RefExpr->getExprLoc(),
11896 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000011897 << RefExpr->getSourceRange();
11898 continue;
11899 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011900 RD.ExprPostUpdates.emplace_back(
11901 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000011902 }
11903 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011904 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000011905 // All reduction items are still marked as reduction (to do not increase
11906 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011907 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011908 if (CurrDir == OMPD_taskgroup) {
11909 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011910 Stack->addTaskgroupReductionData(D, ReductionIdRange,
11911 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000011912 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011913 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011914 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011915 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
11916 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011917 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011918 return RD.Vars.empty();
11919}
Alexey Bataevc5e02582014-06-16 07:08:35 +000011920
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011921OMPClause *Sema::ActOnOpenMPReductionClause(
11922 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11923 SourceLocation ColonLoc, SourceLocation EndLoc,
11924 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11925 ArrayRef<Expr *> UnresolvedReductions) {
11926 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011927 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011928 StartLoc, LParenLoc, ColonLoc, EndLoc,
11929 ReductionIdScopeSpec, ReductionId,
11930 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011931 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000011932
Alexey Bataevc5e02582014-06-16 07:08:35 +000011933 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011934 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11935 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11936 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11937 buildPreInits(Context, RD.ExprCaptures),
11938 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000011939}
11940
Alexey Bataev169d96a2017-07-18 20:17:46 +000011941OMPClause *Sema::ActOnOpenMPTaskReductionClause(
11942 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11943 SourceLocation ColonLoc, SourceLocation EndLoc,
11944 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11945 ArrayRef<Expr *> UnresolvedReductions) {
11946 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011947 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
11948 StartLoc, LParenLoc, ColonLoc, EndLoc,
11949 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011950 UnresolvedReductions, RD))
11951 return nullptr;
11952
11953 return OMPTaskReductionClause::Create(
11954 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11955 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11956 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11957 buildPreInits(Context, RD.ExprCaptures),
11958 buildPostUpdate(*this, RD.ExprPostUpdates));
11959}
11960
Alexey Bataevfa312f32017-07-21 18:48:21 +000011961OMPClause *Sema::ActOnOpenMPInReductionClause(
11962 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11963 SourceLocation ColonLoc, SourceLocation EndLoc,
11964 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11965 ArrayRef<Expr *> UnresolvedReductions) {
11966 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011967 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011968 StartLoc, LParenLoc, ColonLoc, EndLoc,
11969 ReductionIdScopeSpec, ReductionId,
11970 UnresolvedReductions, RD))
11971 return nullptr;
11972
11973 return OMPInReductionClause::Create(
11974 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11975 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000011976 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011977 buildPreInits(Context, RD.ExprCaptures),
11978 buildPostUpdate(*this, RD.ExprPostUpdates));
11979}
11980
Alexey Bataevecba70f2016-04-12 11:02:11 +000011981bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11982 SourceLocation LinLoc) {
11983 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
11984 LinKind == OMPC_LINEAR_unknown) {
11985 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
11986 return true;
11987 }
11988 return false;
11989}
11990
Alexey Bataeve3727102018-04-18 15:57:46 +000011991bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000011992 OpenMPLinearClauseKind LinKind,
11993 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011994 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000011995 // A variable must not have an incomplete type or a reference type.
11996 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
11997 return true;
11998 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
11999 !Type->isReferenceType()) {
12000 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
12001 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
12002 return true;
12003 }
12004 Type = Type.getNonReferenceType();
12005
Joel E. Dennybae586f2019-01-04 22:12:13 +000012006 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12007 // A variable that is privatized must not have a const-qualified type
12008 // unless it is of class type with a mutable member. This restriction does
12009 // not apply to the firstprivate clause.
12010 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000012011 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012012
12013 // A list item must be of integral or pointer type.
12014 Type = Type.getUnqualifiedType().getCanonicalType();
12015 const auto *Ty = Type.getTypePtrOrNull();
12016 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
12017 !Ty->isPointerType())) {
12018 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
12019 if (D) {
12020 bool IsDecl =
12021 !VD ||
12022 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12023 Diag(D->getLocation(),
12024 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12025 << D;
12026 }
12027 return true;
12028 }
12029 return false;
12030}
12031
Alexey Bataev182227b2015-08-20 10:54:39 +000012032OMPClause *Sema::ActOnOpenMPLinearClause(
12033 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
12034 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
12035 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012036 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012037 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000012038 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000012039 SmallVector<Decl *, 4> ExprCaptures;
12040 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012041 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000012042 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000012043 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012044 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012045 SourceLocation ELoc;
12046 SourceRange ERange;
12047 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012048 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012049 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012050 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012051 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012052 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000012053 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000012054 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012055 ValueDecl *D = Res.first;
12056 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000012057 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000012058
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012059 QualType Type = D->getType();
12060 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000012061
12062 // OpenMP [2.14.3.7, linear clause]
12063 // A list-item cannot appear in more than one linear clause.
12064 // A list-item that appears in a linear clause cannot appear in any
12065 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012066 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000012067 if (DVar.RefExpr) {
12068 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12069 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000012070 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000012071 continue;
12072 }
12073
Alexey Bataevecba70f2016-04-12 11:02:11 +000012074 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000012075 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012076 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000012077
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012078 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000012079 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012080 buildVarDecl(*this, ELoc, Type, D->getName(),
12081 D->hasAttrs() ? &D->getAttrs() : nullptr,
12082 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012083 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012084 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012085 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012086 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012087 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012088 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012089 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012090 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012091 ExprCaptures.push_back(Ref->getDecl());
12092 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
12093 ExprResult RefRes = DefaultLvalueConversion(Ref);
12094 if (!RefRes.isUsable())
12095 continue;
12096 ExprResult PostUpdateRes =
12097 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
12098 SimpleRefExpr, RefRes.get());
12099 if (!PostUpdateRes.isUsable())
12100 continue;
12101 ExprPostUpdates.push_back(
12102 IgnoredValueConversions(PostUpdateRes.get()).get());
12103 }
12104 }
12105 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012106 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012107 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012108 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012109 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012110 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012111 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012112 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012113
12114 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012115 Vars.push_back((VD || CurContext->isDependentContext())
12116 ? RefExpr->IgnoreParens()
12117 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012118 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000012119 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000012120 }
12121
12122 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012123 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012124
12125 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000012126 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012127 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
12128 !Step->isInstantiationDependent() &&
12129 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012130 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000012131 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000012132 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012133 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012134 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000012135
Alexander Musman3276a272015-03-21 10:12:56 +000012136 // Build var to save the step value.
12137 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012138 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000012139 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012140 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012141 ExprResult CalcStep =
12142 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012143 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012144
Alexander Musman8dba6642014-04-22 13:09:42 +000012145 // Warn about zero linear step (it would be probably better specified as
12146 // making corresponding variables 'const').
12147 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000012148 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
12149 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000012150 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
12151 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000012152 if (!IsConstant && CalcStep.isUsable()) {
12153 // Calculate the step beforehand instead of doing this on each iteration.
12154 // (This is not used if the number of iterations may be kfold-ed).
12155 CalcStepExpr = CalcStep.get();
12156 }
Alexander Musman8dba6642014-04-22 13:09:42 +000012157 }
12158
Alexey Bataev182227b2015-08-20 10:54:39 +000012159 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
12160 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012161 StepExpr, CalcStepExpr,
12162 buildPreInits(Context, ExprCaptures),
12163 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000012164}
12165
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012166static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
12167 Expr *NumIterations, Sema &SemaRef,
12168 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000012169 // Walk the vars and build update/final expressions for the CodeGen.
12170 SmallVector<Expr *, 8> Updates;
12171 SmallVector<Expr *, 8> Finals;
12172 Expr *Step = Clause.getStep();
12173 Expr *CalcStep = Clause.getCalcStep();
12174 // OpenMP [2.14.3.7, linear clause]
12175 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000012176 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000012177 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012178 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000012179 Step = cast<BinaryOperator>(CalcStep)->getLHS();
12180 bool HasErrors = false;
12181 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012182 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000012183 OpenMPLinearClauseKind LinKind = Clause.getModifier();
12184 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012185 SourceLocation ELoc;
12186 SourceRange ERange;
12187 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012188 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012189 ValueDecl *D = Res.first;
12190 if (Res.second || !D) {
12191 Updates.push_back(nullptr);
12192 Finals.push_back(nullptr);
12193 HasErrors = true;
12194 continue;
12195 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012196 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000012197 // OpenMP [2.15.11, distribute simd Construct]
12198 // A list item may not appear in a linear clause, unless it is the loop
12199 // iteration variable.
12200 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
12201 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
12202 SemaRef.Diag(ELoc,
12203 diag::err_omp_linear_distribute_var_non_loop_iteration);
12204 Updates.push_back(nullptr);
12205 Finals.push_back(nullptr);
12206 HasErrors = true;
12207 continue;
12208 }
Alexander Musman3276a272015-03-21 10:12:56 +000012209 Expr *InitExpr = *CurInit;
12210
12211 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000012212 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012213 Expr *CapturedRef;
12214 if (LinKind == OMPC_LINEAR_uval)
12215 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
12216 else
12217 CapturedRef =
12218 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
12219 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
12220 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000012221
12222 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012223 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000012224 if (!Info.first)
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012225 Update =
Alexey Bataeve3727102018-04-18 15:57:46 +000012226 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012227 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012228 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012229 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012230 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012231 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012232
12233 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012234 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000012235 if (!Info.first)
12236 Final =
12237 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
12238 InitExpr, NumIterations, Step, /*Subtract=*/false);
12239 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012240 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012241 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012242 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012243
Alexander Musman3276a272015-03-21 10:12:56 +000012244 if (!Update.isUsable() || !Final.isUsable()) {
12245 Updates.push_back(nullptr);
12246 Finals.push_back(nullptr);
12247 HasErrors = true;
12248 } else {
12249 Updates.push_back(Update.get());
12250 Finals.push_back(Final.get());
12251 }
Richard Trieucc3949d2016-02-18 22:34:54 +000012252 ++CurInit;
12253 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000012254 }
12255 Clause.setUpdates(Updates);
12256 Clause.setFinals(Finals);
12257 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000012258}
12259
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012260OMPClause *Sema::ActOnOpenMPAlignedClause(
12261 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
12262 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012263 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012264 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000012265 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12266 SourceLocation ELoc;
12267 SourceRange ERange;
12268 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012269 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000012270 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012271 // It will be analyzed later.
12272 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012273 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000012274 ValueDecl *D = Res.first;
12275 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012276 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012277
Alexey Bataev1efd1662016-03-29 10:59:56 +000012278 QualType QType = D->getType();
12279 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012280
12281 // OpenMP [2.8.1, simd construct, Restrictions]
12282 // The type of list items appearing in the aligned clause must be
12283 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012284 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012285 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000012286 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012287 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012288 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012289 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000012290 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012291 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000012292 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012293 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012294 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012295 continue;
12296 }
12297
12298 // OpenMP [2.8.1, simd construct, Restrictions]
12299 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012300 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000012301 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012302 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
12303 << getOpenMPClauseName(OMPC_aligned);
12304 continue;
12305 }
12306
Alexey Bataev1efd1662016-03-29 10:59:56 +000012307 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012308 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000012309 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12310 Vars.push_back(DefaultFunctionArrayConversion(
12311 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
12312 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012313 }
12314
12315 // OpenMP [2.8.1, simd construct, Description]
12316 // The parameter of the aligned clause, alignment, must be a constant
12317 // positive integer expression.
12318 // If no optional parameter is specified, implementation-defined default
12319 // alignments for SIMD instructions on the target platforms are assumed.
12320 if (Alignment != nullptr) {
12321 ExprResult AlignResult =
12322 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
12323 if (AlignResult.isInvalid())
12324 return nullptr;
12325 Alignment = AlignResult.get();
12326 }
12327 if (Vars.empty())
12328 return nullptr;
12329
12330 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
12331 EndLoc, Vars, Alignment);
12332}
12333
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012334OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12335 SourceLocation StartLoc,
12336 SourceLocation LParenLoc,
12337 SourceLocation EndLoc) {
12338 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012339 SmallVector<Expr *, 8> SrcExprs;
12340 SmallVector<Expr *, 8> DstExprs;
12341 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012342 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012343 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
12344 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012345 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012346 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012347 SrcExprs.push_back(nullptr);
12348 DstExprs.push_back(nullptr);
12349 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012350 continue;
12351 }
12352
Alexey Bataeved09d242014-05-28 05:53:51 +000012353 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012354 // OpenMP [2.1, C/C++]
12355 // A list item is a variable name.
12356 // OpenMP [2.14.4.1, Restrictions, p.1]
12357 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000012358 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012359 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012360 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
12361 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012362 continue;
12363 }
12364
12365 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000012366 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012367
12368 QualType Type = VD->getType();
12369 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
12370 // It will be analyzed later.
12371 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012372 SrcExprs.push_back(nullptr);
12373 DstExprs.push_back(nullptr);
12374 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012375 continue;
12376 }
12377
12378 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
12379 // A list item that appears in a copyin clause must be threadprivate.
12380 if (!DSAStack->isThreadPrivate(VD)) {
12381 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000012382 << getOpenMPClauseName(OMPC_copyin)
12383 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012384 continue;
12385 }
12386
12387 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12388 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000012389 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012390 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012391 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12392 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012393 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012394 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012395 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012396 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000012397 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012398 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012399 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012400 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012401 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012402 // For arrays generate assignment operation for single element and replace
12403 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012404 ExprResult AssignmentOp =
12405 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12406 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012407 if (AssignmentOp.isInvalid())
12408 continue;
12409 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012410 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012411 if (AssignmentOp.isInvalid())
12412 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012413
12414 DSAStack->addDSA(VD, DE, OMPC_copyin);
12415 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012416 SrcExprs.push_back(PseudoSrcExpr);
12417 DstExprs.push_back(PseudoDstExpr);
12418 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012419 }
12420
Alexey Bataeved09d242014-05-28 05:53:51 +000012421 if (Vars.empty())
12422 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012423
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012424 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12425 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012426}
12427
Alexey Bataevbae9a792014-06-27 10:37:06 +000012428OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12429 SourceLocation StartLoc,
12430 SourceLocation LParenLoc,
12431 SourceLocation EndLoc) {
12432 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000012433 SmallVector<Expr *, 8> SrcExprs;
12434 SmallVector<Expr *, 8> DstExprs;
12435 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012436 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012437 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12438 SourceLocation ELoc;
12439 SourceRange ERange;
12440 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012441 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000012442 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012443 // It will be analyzed later.
12444 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012445 SrcExprs.push_back(nullptr);
12446 DstExprs.push_back(nullptr);
12447 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012448 }
Alexey Bataeve122da12016-03-17 10:50:17 +000012449 ValueDecl *D = Res.first;
12450 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000012451 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012452
Alexey Bataeve122da12016-03-17 10:50:17 +000012453 QualType Type = D->getType();
12454 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012455
12456 // OpenMP [2.14.4.2, Restrictions, p.2]
12457 // A list item that appears in a copyprivate clause may not appear in a
12458 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000012459 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012460 DSAStackTy::DSAVarData DVar =
12461 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012462 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12463 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012464 Diag(ELoc, diag::err_omp_wrong_dsa)
12465 << getOpenMPClauseName(DVar.CKind)
12466 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012467 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012468 continue;
12469 }
12470
12471 // OpenMP [2.11.4.2, Restrictions, p.1]
12472 // All list items that appear in a copyprivate clause must be either
12473 // threadprivate or private in the enclosing context.
12474 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012475 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012476 if (DVar.CKind == OMPC_shared) {
12477 Diag(ELoc, diag::err_omp_required_access)
12478 << getOpenMPClauseName(OMPC_copyprivate)
12479 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000012480 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012481 continue;
12482 }
12483 }
12484 }
12485
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012486 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012487 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012488 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012489 << getOpenMPClauseName(OMPC_copyprivate) << Type
12490 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012491 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000012492 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012493 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000012494 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012495 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000012496 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012497 continue;
12498 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012499
Alexey Bataevbae9a792014-06-27 10:37:06 +000012500 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12501 // A variable of class type (or array thereof) that appears in a
12502 // copyin clause requires an accessible, unambiguous copy assignment
12503 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012504 Type = Context.getBaseElementType(Type.getNonReferenceType())
12505 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012506 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012507 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000012508 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012509 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
12510 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012511 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000012512 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012513 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
12514 ExprResult AssignmentOp = BuildBinOp(
12515 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012516 if (AssignmentOp.isInvalid())
12517 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012518 AssignmentOp =
12519 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012520 if (AssignmentOp.isInvalid())
12521 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012522
12523 // No need to mark vars as copyprivate, they are already threadprivate or
12524 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000012525 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000012526 Vars.push_back(
12527 VD ? RefExpr->IgnoreParens()
12528 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000012529 SrcExprs.push_back(PseudoSrcExpr);
12530 DstExprs.push_back(PseudoDstExpr);
12531 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000012532 }
12533
12534 if (Vars.empty())
12535 return nullptr;
12536
Alexey Bataeva63048e2015-03-23 06:18:07 +000012537 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12538 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012539}
12540
Alexey Bataev6125da92014-07-21 11:26:11 +000012541OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12542 SourceLocation StartLoc,
12543 SourceLocation LParenLoc,
12544 SourceLocation EndLoc) {
12545 if (VarList.empty())
12546 return nullptr;
12547
12548 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
12549}
Alexey Bataevdea47612014-07-23 07:46:59 +000012550
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012551OMPClause *
12552Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12553 SourceLocation DepLoc, SourceLocation ColonLoc,
12554 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12555 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012556 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012557 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012558 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012559 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000012560 return nullptr;
12561 }
12562 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012563 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12564 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000012565 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012566 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012567 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12568 /*Last=*/OMPC_DEPEND_unknown, Except)
12569 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012570 return nullptr;
12571 }
12572 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000012573 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012574 llvm::APSInt DepCounter(/*BitWidth=*/32);
12575 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000012576 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12577 if (const Expr *OrderedCountExpr =
12578 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012579 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
12580 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012581 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012582 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012583 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000012584 assert(RefExpr && "NULL expr in OpenMP shared clause.");
12585 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12586 // It will be analyzed later.
12587 Vars.push_back(RefExpr);
12588 continue;
12589 }
12590
12591 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000012592 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000012593 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000012594 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012595 DepCounter >= TotalDepCount) {
12596 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
12597 continue;
12598 }
12599 ++DepCounter;
12600 // OpenMP [2.13.9, Summary]
12601 // depend(dependence-type : vec), where dependence-type is:
12602 // 'sink' and where vec is the iteration vector, which has the form:
12603 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
12604 // where n is the value specified by the ordered clause in the loop
12605 // directive, xi denotes the loop iteration variable of the i-th nested
12606 // loop associated with the loop directive, and di is a constant
12607 // non-negative integer.
12608 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012609 // It will be analyzed later.
12610 Vars.push_back(RefExpr);
12611 continue;
12612 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012613 SimpleExpr = SimpleExpr->IgnoreImplicit();
12614 OverloadedOperatorKind OOK = OO_None;
12615 SourceLocation OOLoc;
12616 Expr *LHS = SimpleExpr;
12617 Expr *RHS = nullptr;
12618 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
12619 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
12620 OOLoc = BO->getOperatorLoc();
12621 LHS = BO->getLHS()->IgnoreParenImpCasts();
12622 RHS = BO->getRHS()->IgnoreParenImpCasts();
12623 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
12624 OOK = OCE->getOperator();
12625 OOLoc = OCE->getOperatorLoc();
12626 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12627 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
12628 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
12629 OOK = MCE->getMethodDecl()
12630 ->getNameInfo()
12631 .getName()
12632 .getCXXOverloadedOperator();
12633 OOLoc = MCE->getCallee()->getExprLoc();
12634 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
12635 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012636 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012637 SourceLocation ELoc;
12638 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000012639 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012640 if (Res.second) {
12641 // It will be analyzed later.
12642 Vars.push_back(RefExpr);
12643 }
12644 ValueDecl *D = Res.first;
12645 if (!D)
12646 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012647
Alexey Bataev17daedf2018-02-15 22:42:57 +000012648 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
12649 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
12650 continue;
12651 }
12652 if (RHS) {
12653 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
12654 RHS, OMPC_depend, /*StrictlyPositive=*/false);
12655 if (RHSRes.isInvalid())
12656 continue;
12657 }
12658 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012659 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012660 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012661 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000012662 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000012663 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000012664 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
12665 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000012666 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000012667 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000012668 continue;
12669 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012670 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012671 } else {
12672 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12673 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12674 (ASE &&
12675 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12676 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12677 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12678 << RefExpr->getSourceRange();
12679 continue;
12680 }
12681 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12682 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12683 ExprResult Res =
12684 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12685 getDiagnostics().setSuppressAllDiagnostics(Suppress);
12686 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12687 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12688 << RefExpr->getSourceRange();
12689 continue;
12690 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012691 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012692 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012693 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012694
12695 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
12696 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012697 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012698 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
12699 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
12700 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
12701 }
12702 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
12703 Vars.empty())
12704 return nullptr;
12705
Alexey Bataev8b427062016-05-25 12:36:08 +000012706 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000012707 DepKind, DepLoc, ColonLoc, Vars,
12708 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000012709 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
12710 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000012711 DSAStack->addDoacrossDependClause(C, OpsOffs);
12712 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012713}
Michael Wonge710d542015-08-07 16:16:36 +000012714
12715OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
12716 SourceLocation LParenLoc,
12717 SourceLocation EndLoc) {
12718 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012719 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000012720
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012721 // OpenMP [2.9.1, Restrictions]
12722 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000012723 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000012724 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012725 return nullptr;
12726
Alexey Bataev931e19b2017-10-02 16:32:39 +000012727 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012728 OpenMPDirectiveKind CaptureRegion =
12729 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
12730 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012731 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012732 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012733 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12734 HelperValStmt = buildPreInits(Context, Captures);
12735 }
12736
Alexey Bataev8451efa2018-01-15 19:06:12 +000012737 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
12738 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000012739}
Kelvin Li0bff7af2015-11-23 05:32:03 +000012740
Alexey Bataeve3727102018-04-18 15:57:46 +000012741static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000012742 DSAStackTy *Stack, QualType QTy,
12743 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000012744 NamedDecl *ND;
12745 if (QTy->isIncompleteType(&ND)) {
12746 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
12747 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012748 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000012749 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
12750 !QTy.isTrivialType(SemaRef.Context))
12751 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012752 return true;
12753}
12754
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012755/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012756/// (array section or array subscript) does NOT specify the whole size of the
12757/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012758static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012759 const Expr *E,
12760 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012761 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012762
12763 // If this is an array subscript, it refers to the whole size if the size of
12764 // the dimension is constant and equals 1. Also, an array section assumes the
12765 // format of an array subscript if no colon is used.
12766 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012767 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012768 return ATy->getSize().getSExtValue() != 1;
12769 // Size can't be evaluated statically.
12770 return false;
12771 }
12772
12773 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012774 const Expr *LowerBound = OASE->getLowerBound();
12775 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012776
12777 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000012778 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012779 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000012780 Expr::EvalResult Result;
12781 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012782 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000012783
12784 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012785 if (ConstLowerBound.getSExtValue())
12786 return true;
12787 }
12788
12789 // If we don't have a length we covering the whole dimension.
12790 if (!Length)
12791 return false;
12792
12793 // If the base is a pointer, we don't have a way to get the size of the
12794 // pointee.
12795 if (BaseQTy->isPointerType())
12796 return false;
12797
12798 // We can only check if the length is the same as the size of the dimension
12799 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000012800 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012801 if (!CATy)
12802 return false;
12803
Fangrui Song407659a2018-11-30 23:41:18 +000012804 Expr::EvalResult Result;
12805 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012806 return false; // Can't get the integer value as a constant.
12807
Fangrui Song407659a2018-11-30 23:41:18 +000012808 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012809 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
12810}
12811
12812// Return true if it can be proven that the provided array expression (array
12813// section or array subscript) does NOT specify a single element of the array
12814// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012815static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000012816 const Expr *E,
12817 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012818 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012819
12820 // An array subscript always refer to a single element. Also, an array section
12821 // assumes the format of an array subscript if no colon is used.
12822 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
12823 return false;
12824
12825 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012826 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012827
12828 // If we don't have a length we have to check if the array has unitary size
12829 // for this dimension. Also, we should always expect a length if the base type
12830 // is pointer.
12831 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012832 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012833 return ATy->getSize().getSExtValue() != 1;
12834 // We cannot assume anything.
12835 return false;
12836 }
12837
12838 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000012839 Expr::EvalResult Result;
12840 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012841 return false; // Can't get the integer value as a constant.
12842
Fangrui Song407659a2018-11-30 23:41:18 +000012843 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012844 return ConstLength.getSExtValue() != 1;
12845}
12846
Samuel Antao661c0902016-05-26 17:39:58 +000012847// Return the expression of the base of the mappable expression or null if it
12848// cannot be determined and do all the necessary checks to see if the expression
12849// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000012850// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000012851static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000012852 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000012853 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012854 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012855 SourceLocation ELoc = E->getExprLoc();
12856 SourceRange ERange = E->getSourceRange();
12857
12858 // The base of elements of list in a map clause have to be either:
12859 // - a reference to variable or field.
12860 // - a member expression.
12861 // - an array expression.
12862 //
12863 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
12864 // reference to 'r'.
12865 //
12866 // If we have:
12867 //
12868 // struct SS {
12869 // Bla S;
12870 // foo() {
12871 // #pragma omp target map (S.Arr[:12]);
12872 // }
12873 // }
12874 //
12875 // We want to retrieve the member expression 'this->S';
12876
Alexey Bataeve3727102018-04-18 15:57:46 +000012877 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012878
Samuel Antao5de996e2016-01-22 20:21:36 +000012879 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
12880 // If a list item is an array section, it must specify contiguous storage.
12881 //
12882 // For this restriction it is sufficient that we make sure only references
12883 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012884 // exist except in the rightmost expression (unless they cover the whole
12885 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000012886 //
12887 // r.ArrS[3:5].Arr[6:7]
12888 //
12889 // r.ArrS[3:5].x
12890 //
12891 // but these would be valid:
12892 // r.ArrS[3].Arr[6:7]
12893 //
12894 // r.ArrS[3].x
12895
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012896 bool AllowUnitySizeArraySection = true;
12897 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012898
Dmitry Polukhin644a9252016-03-11 07:58:34 +000012899 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012900 E = E->IgnoreParenImpCasts();
12901
12902 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
12903 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000012904 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012905
12906 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012907
12908 // If we got a reference to a declaration, we should not expect any array
12909 // section before that.
12910 AllowUnitySizeArraySection = false;
12911 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012912
12913 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012914 CurComponents.emplace_back(CurE, CurE->getDecl());
12915 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012916 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000012917
12918 if (isa<CXXThisExpr>(BaseE))
12919 // We found a base expression: this->Val.
12920 RelevantExpr = CurE;
12921 else
12922 E = BaseE;
12923
12924 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012925 if (!NoDiagnose) {
12926 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
12927 << CurE->getSourceRange();
12928 return nullptr;
12929 }
12930 if (RelevantExpr)
12931 return nullptr;
12932 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012933 }
12934
12935 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
12936
12937 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
12938 // A bit-field cannot appear in a map clause.
12939 //
12940 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012941 if (!NoDiagnose) {
12942 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
12943 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
12944 return nullptr;
12945 }
12946 if (RelevantExpr)
12947 return nullptr;
12948 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012949 }
12950
12951 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12952 // If the type of a list item is a reference to a type T then the type
12953 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012954 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012955
12956 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
12957 // A list item cannot be a variable that is a member of a structure with
12958 // a union type.
12959 //
Alexey Bataeve3727102018-04-18 15:57:46 +000012960 if (CurType->isUnionType()) {
12961 if (!NoDiagnose) {
12962 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
12963 << CurE->getSourceRange();
12964 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012965 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012966 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012967 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012968
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012969 // If we got a member expression, we should not expect any array section
12970 // before that:
12971 //
12972 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
12973 // If a list item is an element of a structure, only the rightmost symbol
12974 // of the variable reference can be an array section.
12975 //
12976 AllowUnitySizeArraySection = false;
12977 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012978
12979 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012980 CurComponents.emplace_back(CurE, FD);
12981 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012982 E = CurE->getBase()->IgnoreParenImpCasts();
12983
12984 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012985 if (!NoDiagnose) {
12986 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12987 << 0 << CurE->getSourceRange();
12988 return nullptr;
12989 }
12990 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012991 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012992
12993 // If we got an array subscript that express the whole dimension we
12994 // can have any array expressions before. If it only expressing part of
12995 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000012996 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012997 E->getType()))
12998 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012999
Patrick Lystere13b1e32019-01-02 19:28:48 +000013000 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13001 Expr::EvalResult Result;
13002 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
13003 if (!Result.Val.getInt().isNullValue()) {
13004 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13005 diag::err_omp_invalid_map_this_expr);
13006 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13007 diag::note_omp_invalid_subscript_on_this_ptr_map);
13008 }
13009 }
13010 RelevantExpr = TE;
13011 }
13012
Samuel Antao90927002016-04-26 14:54:23 +000013013 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013014 CurComponents.emplace_back(CurE, nullptr);
13015 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013016 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000013017 E = CurE->getBase()->IgnoreParenImpCasts();
13018
Alexey Bataev27041fa2017-12-05 15:22:49 +000013019 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013020 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13021
Samuel Antao5de996e2016-01-22 20:21:36 +000013022 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13023 // If the type of a list item is a reference to a type T then the type
13024 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000013025 if (CurType->isReferenceType())
13026 CurType = CurType->getPointeeType();
13027
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013028 bool IsPointer = CurType->isAnyPointerType();
13029
13030 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013031 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13032 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013033 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013034 }
13035
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013036 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000013037 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013038 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000013039 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013040
Samuel Antaodab51bb2016-07-18 23:22:11 +000013041 if (AllowWholeSizeArraySection) {
13042 // Any array section is currently allowed. Allowing a whole size array
13043 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013044 //
13045 // If this array section refers to the whole dimension we can still
13046 // accept other array sections before this one, except if the base is a
13047 // pointer. Otherwise, only unitary sections are accepted.
13048 if (NotWhole || IsPointer)
13049 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000013050 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013051 // A unity or whole array section is not allowed and that is not
13052 // compatible with the properties of the current array section.
13053 SemaRef.Diag(
13054 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
13055 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013056 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013057 }
Samuel Antao90927002016-04-26 14:54:23 +000013058
Patrick Lystere13b1e32019-01-02 19:28:48 +000013059 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13060 Expr::EvalResult ResultR;
13061 Expr::EvalResult ResultL;
13062 if (CurE->getLength()->EvaluateAsInt(ResultR,
13063 SemaRef.getASTContext())) {
13064 if (!ResultR.Val.getInt().isOneValue()) {
13065 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13066 diag::err_omp_invalid_map_this_expr);
13067 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13068 diag::note_omp_invalid_length_on_this_ptr_mapping);
13069 }
13070 }
13071 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
13072 ResultL, SemaRef.getASTContext())) {
13073 if (!ResultL.Val.getInt().isNullValue()) {
13074 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13075 diag::err_omp_invalid_map_this_expr);
13076 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13077 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
13078 }
13079 }
13080 RelevantExpr = TE;
13081 }
13082
Samuel Antao90927002016-04-26 14:54:23 +000013083 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013084 CurComponents.emplace_back(CurE, nullptr);
13085 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013086 if (!NoDiagnose) {
13087 // If nothing else worked, this is not a valid map clause expression.
13088 SemaRef.Diag(
13089 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
13090 << ERange;
13091 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000013092 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013093 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013094 }
13095
13096 return RelevantExpr;
13097}
13098
13099// Return true if expression E associated with value VD has conflicts with other
13100// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000013101static bool checkMapConflicts(
13102 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000013103 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000013104 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
13105 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013106 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000013107 SourceLocation ELoc = E->getExprLoc();
13108 SourceRange ERange = E->getSourceRange();
13109
13110 // In order to easily check the conflicts we need to match each component of
13111 // the expression under test with the components of the expressions that are
13112 // already in the stack.
13113
Samuel Antao5de996e2016-01-22 20:21:36 +000013114 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013115 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013116 "Map clause expression with unexpected base!");
13117
13118 // Variables to help detecting enclosing problems in data environment nests.
13119 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000013120 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013121
Samuel Antao90927002016-04-26 14:54:23 +000013122 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
13123 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000013124 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
13125 ERange, CKind, &EnclosingExpr,
13126 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
13127 StackComponents,
13128 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013129 assert(!StackComponents.empty() &&
13130 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013131 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013132 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000013133 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013134
Samuel Antao90927002016-04-26 14:54:23 +000013135 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000013136 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000013137
Samuel Antao5de996e2016-01-22 20:21:36 +000013138 // Expressions must start from the same base. Here we detect at which
13139 // point both expressions diverge from each other and see if we can
13140 // detect if the memory referred to both expressions is contiguous and
13141 // do not overlap.
13142 auto CI = CurComponents.rbegin();
13143 auto CE = CurComponents.rend();
13144 auto SI = StackComponents.rbegin();
13145 auto SE = StackComponents.rend();
13146 for (; CI != CE && SI != SE; ++CI, ++SI) {
13147
13148 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
13149 // At most one list item can be an array item derived from a given
13150 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000013151 if (CurrentRegionOnly &&
13152 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
13153 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
13154 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
13155 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
13156 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000013157 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000013158 << CI->getAssociatedExpression()->getSourceRange();
13159 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
13160 diag::note_used_here)
13161 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000013162 return true;
13163 }
13164
13165 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000013166 if (CI->getAssociatedExpression()->getStmtClass() !=
13167 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000013168 break;
13169
13170 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000013171 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000013172 break;
13173 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000013174 // Check if the extra components of the expressions in the enclosing
13175 // data environment are redundant for the current base declaration.
13176 // If they are, the maps completely overlap, which is legal.
13177 for (; SI != SE; ++SI) {
13178 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000013179 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000013180 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000013181 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013182 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000013183 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013184 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000013185 Type =
13186 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13187 }
13188 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013189 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000013190 SemaRef, SI->getAssociatedExpression(), Type))
13191 break;
13192 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013193
13194 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13195 // List items of map clauses in the same construct must not share
13196 // original storage.
13197 //
13198 // If the expressions are exactly the same or one is a subset of the
13199 // other, it means they are sharing storage.
13200 if (CI == CE && SI == SE) {
13201 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013202 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000013203 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013204 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013205 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013206 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13207 << ERange;
13208 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013209 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13210 << RE->getSourceRange();
13211 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013212 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013213 // If we find the same expression in the enclosing data environment,
13214 // that is legal.
13215 IsEnclosedByDataEnvironmentExpr = true;
13216 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000013217 }
13218
Samuel Antao90927002016-04-26 14:54:23 +000013219 QualType DerivedType =
13220 std::prev(CI)->getAssociatedDeclaration()->getType();
13221 SourceLocation DerivedLoc =
13222 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000013223
13224 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13225 // If the type of a list item is a reference to a type T then the type
13226 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000013227 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013228
13229 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
13230 // A variable for which the type is pointer and an array section
13231 // derived from that variable must not appear as list items of map
13232 // clauses of the same construct.
13233 //
13234 // Also, cover one of the cases in:
13235 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13236 // If any part of the original storage of a list item has corresponding
13237 // storage in the device data environment, all of the original storage
13238 // must have corresponding storage in the device data environment.
13239 //
13240 if (DerivedType->isAnyPointerType()) {
13241 if (CI == CE || SI == SE) {
13242 SemaRef.Diag(
13243 DerivedLoc,
13244 diag::err_omp_pointer_mapped_along_with_derived_section)
13245 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013246 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13247 << RE->getSourceRange();
13248 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013249 }
13250 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000013251 SI->getAssociatedExpression()->getStmtClass() ||
13252 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
13253 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013254 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000013255 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000013256 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013257 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13258 << RE->getSourceRange();
13259 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013260 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013261 }
13262
13263 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13264 // List items of map clauses in the same construct must not share
13265 // original storage.
13266 //
13267 // An expression is a subset of the other.
13268 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013269 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000013270 if (CI != CE || SI != SE) {
13271 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
13272 // a pointer.
13273 auto Begin =
13274 CI != CE ? CurComponents.begin() : StackComponents.begin();
13275 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
13276 auto It = Begin;
13277 while (It != End && !It->getAssociatedDeclaration())
13278 std::advance(It, 1);
13279 assert(It != End &&
13280 "Expected at least one component with the declaration.");
13281 if (It != Begin && It->getAssociatedDeclaration()
13282 ->getType()
13283 .getCanonicalType()
13284 ->isAnyPointerType()) {
13285 IsEnclosedByDataEnvironmentExpr = false;
13286 EnclosingExpr = nullptr;
13287 return false;
13288 }
13289 }
Samuel Antao661c0902016-05-26 17:39:58 +000013290 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013291 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013292 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013293 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13294 << ERange;
13295 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013296 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13297 << RE->getSourceRange();
13298 return true;
13299 }
13300
13301 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000013302 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000013303 if (!CurrentRegionOnly && SI != SE)
13304 EnclosingExpr = RE;
13305
13306 // The current expression is a subset of the expression in the data
13307 // environment.
13308 IsEnclosedByDataEnvironmentExpr |=
13309 (!CurrentRegionOnly && CI != CE && SI == SE);
13310
13311 return false;
13312 });
13313
13314 if (CurrentRegionOnly)
13315 return FoundError;
13316
13317 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13318 // If any part of the original storage of a list item has corresponding
13319 // storage in the device data environment, all of the original storage must
13320 // have corresponding storage in the device data environment.
13321 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
13322 // If a list item is an element of a structure, and a different element of
13323 // the structure has a corresponding list item in the device data environment
13324 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000013325 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000013326 // data environment prior to the task encountering the construct.
13327 //
13328 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
13329 SemaRef.Diag(ELoc,
13330 diag::err_omp_original_storage_is_shared_and_does_not_contain)
13331 << ERange;
13332 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
13333 << EnclosingExpr->getSourceRange();
13334 return true;
13335 }
13336
13337 return FoundError;
13338}
13339
Michael Kruse4304e9d2019-02-19 16:38:20 +000013340// Look up the user-defined mapper given the mapper name and mapped type, and
13341// build a reference to it.
13342ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
13343 CXXScopeSpec &MapperIdScopeSpec,
13344 const DeclarationNameInfo &MapperId,
13345 QualType Type, Expr *UnresolvedMapper) {
13346 if (MapperIdScopeSpec.isInvalid())
13347 return ExprError();
13348 // Find all user-defined mappers with the given MapperId.
13349 SmallVector<UnresolvedSet<8>, 4> Lookups;
13350 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
13351 Lookup.suppressDiagnostics();
13352 if (S) {
13353 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
13354 NamedDecl *D = Lookup.getRepresentativeDecl();
13355 while (S && !S->isDeclScope(D))
13356 S = S->getParent();
13357 if (S)
13358 S = S->getParent();
13359 Lookups.emplace_back();
13360 Lookups.back().append(Lookup.begin(), Lookup.end());
13361 Lookup.clear();
13362 }
13363 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
13364 // Extract the user-defined mappers with the given MapperId.
13365 Lookups.push_back(UnresolvedSet<8>());
13366 for (NamedDecl *D : ULE->decls()) {
13367 auto *DMD = cast<OMPDeclareMapperDecl>(D);
13368 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
13369 Lookups.back().addDecl(DMD);
13370 }
13371 }
13372 // Defer the lookup for dependent types. The results will be passed through
13373 // UnresolvedMapper on instantiation.
13374 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
13375 Type->isInstantiationDependentType() ||
13376 Type->containsUnexpandedParameterPack() ||
13377 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
13378 return !D->isInvalidDecl() &&
13379 (D->getType()->isDependentType() ||
13380 D->getType()->isInstantiationDependentType() ||
13381 D->getType()->containsUnexpandedParameterPack());
13382 })) {
13383 UnresolvedSet<8> URS;
13384 for (const UnresolvedSet<8> &Set : Lookups) {
13385 if (Set.empty())
13386 continue;
13387 URS.append(Set.begin(), Set.end());
13388 }
13389 return UnresolvedLookupExpr::Create(
13390 SemaRef.Context, /*NamingClass=*/nullptr,
13391 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
13392 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
13393 }
13394 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13395 // The type must be of struct, union or class type in C and C++
13396 if (!Type->isStructureOrClassType() && !Type->isUnionType())
13397 return ExprEmpty();
13398 SourceLocation Loc = MapperId.getLoc();
13399 // Perform argument dependent lookup.
13400 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
13401 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
13402 // Return the first user-defined mapper with the desired type.
13403 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13404 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
13405 if (!D->isInvalidDecl() &&
13406 SemaRef.Context.hasSameType(D->getType(), Type))
13407 return D;
13408 return nullptr;
13409 }))
13410 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13411 // Find the first user-defined mapper with a type derived from the desired
13412 // type.
13413 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13414 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
13415 if (!D->isInvalidDecl() &&
13416 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
13417 !Type.isMoreQualifiedThan(D->getType()))
13418 return D;
13419 return nullptr;
13420 })) {
13421 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13422 /*DetectVirtual=*/false);
13423 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
13424 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13425 VD->getType().getUnqualifiedType()))) {
13426 if (SemaRef.CheckBaseClassAccess(
13427 Loc, VD->getType(), Type, Paths.front(),
13428 /*DiagID=*/0) != Sema::AR_inaccessible) {
13429 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13430 }
13431 }
13432 }
13433 }
13434 // Report error if a mapper is specified, but cannot be found.
13435 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
13436 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
13437 << Type << MapperId.getName();
13438 return ExprError();
13439 }
13440 return ExprEmpty();
13441}
13442
Samuel Antao661c0902016-05-26 17:39:58 +000013443namespace {
13444// Utility struct that gathers all the related lists associated with a mappable
13445// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013446struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000013447 // The list of expressions.
13448 ArrayRef<Expr *> VarList;
13449 // The list of processed expressions.
13450 SmallVector<Expr *, 16> ProcessedVarList;
13451 // The mappble components for each expression.
13452 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
13453 // The base declaration of the variable.
13454 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000013455 // The reference to the user-defined mapper associated with every expression.
13456 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000013457
13458 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
13459 // We have a list of components and base declarations for each entry in the
13460 // variable list.
13461 VarComponents.reserve(VarList.size());
13462 VarBaseDeclarations.reserve(VarList.size());
13463 }
13464};
13465}
13466
13467// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000013468// \a CKind. In the check process the valid expressions, mappable expression
13469// components, variables, and user-defined mappers are extracted and used to
13470// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
13471// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
13472// and \a MapperId are expected to be valid if the clause kind is 'map'.
13473static void checkMappableExpressionList(
13474 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
13475 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013476 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
13477 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000013478 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000013479 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013480 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
13481 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000013482 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000013483
13484 // If the identifier of user-defined mapper is not specified, it is "default".
13485 // We do not change the actual name in this clause to distinguish whether a
13486 // mapper is specified explicitly, i.e., it is not explicitly specified when
13487 // MapperId.getName() is empty.
13488 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
13489 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
13490 MapperId.setName(DeclNames.getIdentifier(
13491 &SemaRef.getASTContext().Idents.get("default")));
13492 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013493
13494 // Iterators to find the current unresolved mapper expression.
13495 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
13496 bool UpdateUMIt = false;
13497 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013498
Samuel Antao90927002016-04-26 14:54:23 +000013499 // Keep track of the mappable components and base declarations in this clause.
13500 // Each entry in the list is going to have a list of components associated. We
13501 // record each set of the components so that we can build the clause later on.
13502 // In the end we should have the same amount of declarations and component
13503 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000013504
Alexey Bataeve3727102018-04-18 15:57:46 +000013505 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013506 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013507 SourceLocation ELoc = RE->getExprLoc();
13508
Michael Kruse4304e9d2019-02-19 16:38:20 +000013509 // Find the current unresolved mapper expression.
13510 if (UpdateUMIt && UMIt != UMEnd) {
13511 UMIt++;
13512 assert(
13513 UMIt != UMEnd &&
13514 "Expect the size of UnresolvedMappers to match with that of VarList");
13515 }
13516 UpdateUMIt = true;
13517 if (UMIt != UMEnd)
13518 UnresolvedMapper = *UMIt;
13519
Alexey Bataeve3727102018-04-18 15:57:46 +000013520 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013521
13522 if (VE->isValueDependent() || VE->isTypeDependent() ||
13523 VE->isInstantiationDependent() ||
13524 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000013525 // Try to find the associated user-defined mapper.
13526 ExprResult ER = buildUserDefinedMapperRef(
13527 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13528 VE->getType().getCanonicalType(), UnresolvedMapper);
13529 if (ER.isInvalid())
13530 continue;
13531 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000013532 // We can only analyze this information once the missing information is
13533 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000013534 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013535 continue;
13536 }
13537
Alexey Bataeve3727102018-04-18 15:57:46 +000013538 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013539
Samuel Antao5de996e2016-01-22 20:21:36 +000013540 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000013541 SemaRef.Diag(ELoc,
13542 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000013543 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013544 continue;
13545 }
13546
Samuel Antao90927002016-04-26 14:54:23 +000013547 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
13548 ValueDecl *CurDeclaration = nullptr;
13549
13550 // Obtain the array or member expression bases if required. Also, fill the
13551 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000013552 const Expr *BE = checkMapClauseExpressionBase(
13553 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000013554 if (!BE)
13555 continue;
13556
Samuel Antao90927002016-04-26 14:54:23 +000013557 assert(!CurComponents.empty() &&
13558 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013559
Patrick Lystere13b1e32019-01-02 19:28:48 +000013560 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
13561 // Add store "this" pointer to class in DSAStackTy for future checking
13562 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000013563 // Try to find the associated user-defined mapper.
13564 ExprResult ER = buildUserDefinedMapperRef(
13565 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13566 VE->getType().getCanonicalType(), UnresolvedMapper);
13567 if (ER.isInvalid())
13568 continue;
13569 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000013570 // Skip restriction checking for variable or field declarations
13571 MVLI.ProcessedVarList.push_back(RE);
13572 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13573 MVLI.VarComponents.back().append(CurComponents.begin(),
13574 CurComponents.end());
13575 MVLI.VarBaseDeclarations.push_back(nullptr);
13576 continue;
13577 }
13578
Samuel Antao90927002016-04-26 14:54:23 +000013579 // For the following checks, we rely on the base declaration which is
13580 // expected to be associated with the last component. The declaration is
13581 // expected to be a variable or a field (if 'this' is being mapped).
13582 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
13583 assert(CurDeclaration && "Null decl on map clause.");
13584 assert(
13585 CurDeclaration->isCanonicalDecl() &&
13586 "Expecting components to have associated only canonical declarations.");
13587
13588 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000013589 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000013590
13591 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000013592 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013593
13594 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000013595 // threadprivate variables cannot appear in a map clause.
13596 // OpenMP 4.5 [2.10.5, target update Construct]
13597 // threadprivate variables cannot appear in a from clause.
13598 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013599 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013600 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
13601 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000013602 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013603 continue;
13604 }
13605
Samuel Antao5de996e2016-01-22 20:21:36 +000013606 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13607 // A list item cannot appear in both a map clause and a data-sharing
13608 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000013609
Samuel Antao5de996e2016-01-22 20:21:36 +000013610 // Check conflicts with other map clause expressions. We check the conflicts
13611 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000013612 // environment, because the restrictions are different. We only have to
13613 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000013614 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013615 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013616 break;
Samuel Antao661c0902016-05-26 17:39:58 +000013617 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013618 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013619 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013620 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013621
Samuel Antao661c0902016-05-26 17:39:58 +000013622 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000013623 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13624 // If the type of a list item is a reference to a type T then the type will
13625 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000013626 auto I = llvm::find_if(
13627 CurComponents,
13628 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
13629 return MC.getAssociatedDeclaration();
13630 });
13631 assert(I != CurComponents.end() && "Null decl on map clause.");
13632 QualType Type =
13633 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013634
Samuel Antao661c0902016-05-26 17:39:58 +000013635 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
13636 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000013637 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000013638 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013639 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000013640 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000013641 continue;
13642
Samuel Antao661c0902016-05-26 17:39:58 +000013643 if (CKind == OMPC_map) {
13644 // target enter data
13645 // OpenMP [2.10.2, Restrictions, p. 99]
13646 // A map-type must be specified in all map clauses and must be either
13647 // to or alloc.
13648 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
13649 if (DKind == OMPD_target_enter_data &&
13650 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
13651 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13652 << (IsMapTypeImplicit ? 1 : 0)
13653 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13654 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013655 continue;
13656 }
Samuel Antao661c0902016-05-26 17:39:58 +000013657
13658 // target exit_data
13659 // OpenMP [2.10.3, Restrictions, p. 102]
13660 // A map-type must be specified in all map clauses and must be either
13661 // from, release, or delete.
13662 if (DKind == OMPD_target_exit_data &&
13663 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
13664 MapType == OMPC_MAP_delete)) {
13665 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13666 << (IsMapTypeImplicit ? 1 : 0)
13667 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13668 << getOpenMPDirectiveName(DKind);
13669 continue;
13670 }
13671
13672 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13673 // A list item cannot appear in both a map clause and a data-sharing
13674 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000013675 if (VD && isOpenMPTargetExecutionDirective(DKind)) {
13676 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013677 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000013678 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000013679 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000013680 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000013681 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000013682 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000013683 continue;
13684 }
13685 }
Michael Kruse01f670d2019-02-22 22:29:42 +000013686 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013687
Michael Kruse01f670d2019-02-22 22:29:42 +000013688 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000013689 ExprResult ER = buildUserDefinedMapperRef(
13690 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13691 Type.getCanonicalType(), UnresolvedMapper);
13692 if (ER.isInvalid())
13693 continue;
13694 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013695
Samuel Antao90927002016-04-26 14:54:23 +000013696 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000013697 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000013698
13699 // Store the components in the stack so that they can be used to check
13700 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000013701 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
13702 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000013703
13704 // Save the components and declaration to create the clause. For purposes of
13705 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000013706 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000013707 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13708 MVLI.VarComponents.back().append(CurComponents.begin(),
13709 CurComponents.end());
13710 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
13711 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013712 }
Samuel Antao661c0902016-05-26 17:39:58 +000013713}
13714
Michael Kruse4304e9d2019-02-19 16:38:20 +000013715OMPClause *Sema::ActOnOpenMPMapClause(
13716 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13717 ArrayRef<SourceLocation> MapTypeModifiersLoc,
13718 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
13719 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
13720 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
13721 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
13722 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
13723 OMPC_MAP_MODIFIER_unknown,
13724 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000013725 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
13726
13727 // Process map-type-modifiers, flag errors for duplicate modifiers.
13728 unsigned Count = 0;
13729 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
13730 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
13731 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
13732 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
13733 continue;
13734 }
13735 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000013736 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000013737 Modifiers[Count] = MapTypeModifiers[I];
13738 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
13739 ++Count;
13740 }
13741
Michael Kruse4304e9d2019-02-19 16:38:20 +000013742 MappableVarListInfo MVLI(VarList);
13743 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013744 MapperIdScopeSpec, MapperId, UnresolvedMappers,
13745 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000013746
Samuel Antao5de996e2016-01-22 20:21:36 +000013747 // We need to produce a map clause even if we don't have variables so that
13748 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000013749 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
13750 MVLI.VarBaseDeclarations, MVLI.VarComponents,
13751 MVLI.UDMapperList, Modifiers, ModifiersLoc,
13752 MapperIdScopeSpec.getWithLocInContext(Context),
13753 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013754}
Kelvin Li099bb8c2015-11-24 20:50:12 +000013755
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013756QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
13757 TypeResult ParsedType) {
13758 assert(ParsedType.isUsable());
13759
13760 QualType ReductionType = GetTypeFromParser(ParsedType.get());
13761 if (ReductionType.isNull())
13762 return QualType();
13763
13764 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
13765 // A type name in a declare reduction directive cannot be a function type, an
13766 // array type, a reference type, or a type qualified with const, volatile or
13767 // restrict.
13768 if (ReductionType.hasQualifiers()) {
13769 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
13770 return QualType();
13771 }
13772
13773 if (ReductionType->isFunctionType()) {
13774 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
13775 return QualType();
13776 }
13777 if (ReductionType->isReferenceType()) {
13778 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
13779 return QualType();
13780 }
13781 if (ReductionType->isArrayType()) {
13782 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
13783 return QualType();
13784 }
13785 return ReductionType;
13786}
13787
13788Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
13789 Scope *S, DeclContext *DC, DeclarationName Name,
13790 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
13791 AccessSpecifier AS, Decl *PrevDeclInScope) {
13792 SmallVector<Decl *, 8> Decls;
13793 Decls.reserve(ReductionTypes.size());
13794
13795 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000013796 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013797 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
13798 // A reduction-identifier may not be re-declared in the current scope for the
13799 // same type or for a type that is compatible according to the base language
13800 // rules.
13801 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13802 OMPDeclareReductionDecl *PrevDRD = nullptr;
13803 bool InCompoundScope = true;
13804 if (S != nullptr) {
13805 // Find previous declaration with the same name not referenced in other
13806 // declarations.
13807 FunctionScopeInfo *ParentFn = getEnclosingFunction();
13808 InCompoundScope =
13809 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13810 LookupName(Lookup, S);
13811 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13812 /*AllowInlineNamespace=*/false);
13813 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000013814 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013815 while (Filter.hasNext()) {
13816 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
13817 if (InCompoundScope) {
13818 auto I = UsedAsPrevious.find(PrevDecl);
13819 if (I == UsedAsPrevious.end())
13820 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000013821 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013822 UsedAsPrevious[D] = true;
13823 }
13824 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13825 PrevDecl->getLocation();
13826 }
13827 Filter.done();
13828 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013829 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013830 if (!PrevData.second) {
13831 PrevDRD = PrevData.first;
13832 break;
13833 }
13834 }
13835 }
13836 } else if (PrevDeclInScope != nullptr) {
13837 auto *PrevDRDInScope = PrevDRD =
13838 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
13839 do {
13840 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
13841 PrevDRDInScope->getLocation();
13842 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
13843 } while (PrevDRDInScope != nullptr);
13844 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013845 for (const auto &TyData : ReductionTypes) {
13846 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013847 bool Invalid = false;
13848 if (I != PreviousRedeclTypes.end()) {
13849 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
13850 << TyData.first;
13851 Diag(I->second, diag::note_previous_definition);
13852 Invalid = true;
13853 }
13854 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
13855 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
13856 Name, TyData.first, PrevDRD);
13857 DC->addDecl(DRD);
13858 DRD->setAccess(AS);
13859 Decls.push_back(DRD);
13860 if (Invalid)
13861 DRD->setInvalidDecl();
13862 else
13863 PrevDRD = DRD;
13864 }
13865
13866 return DeclGroupPtrTy::make(
13867 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
13868}
13869
13870void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
13871 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13872
13873 // Enter new function scope.
13874 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013875 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013876 getCurFunction()->setHasOMPDeclareReductionCombiner();
13877
13878 if (S != nullptr)
13879 PushDeclContext(S, DRD);
13880 else
13881 CurContext = DRD;
13882
Faisal Valid143a0c2017-04-01 21:30:49 +000013883 PushExpressionEvaluationContext(
13884 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013885
13886 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013887 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
13888 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
13889 // uses semantics of argument handles by value, but it should be passed by
13890 // reference. C lang does not support references, so pass all parameters as
13891 // pointers.
13892 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013893 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013894 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013895 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
13896 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
13897 // uses semantics of argument handles by value, but it should be passed by
13898 // reference. C lang does not support references, so pass all parameters as
13899 // pointers.
13900 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013901 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013902 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
13903 if (S != nullptr) {
13904 PushOnScopeChains(OmpInParm, S);
13905 PushOnScopeChains(OmpOutParm, S);
13906 } else {
13907 DRD->addDecl(OmpInParm);
13908 DRD->addDecl(OmpOutParm);
13909 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013910 Expr *InE =
13911 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
13912 Expr *OutE =
13913 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
13914 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013915}
13916
13917void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
13918 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13919 DiscardCleanupsInEvaluationContext();
13920 PopExpressionEvaluationContext();
13921
13922 PopDeclContext();
13923 PopFunctionScopeInfo();
13924
13925 if (Combiner != nullptr)
13926 DRD->setCombiner(Combiner);
13927 else
13928 DRD->setInvalidDecl();
13929}
13930
Alexey Bataev070f43a2017-09-06 14:49:58 +000013931VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013932 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13933
13934 // Enter new function scope.
13935 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013936 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013937
13938 if (S != nullptr)
13939 PushDeclContext(S, DRD);
13940 else
13941 CurContext = DRD;
13942
Faisal Valid143a0c2017-04-01 21:30:49 +000013943 PushExpressionEvaluationContext(
13944 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013945
13946 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013947 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
13948 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
13949 // uses semantics of argument handles by value, but it should be passed by
13950 // reference. C lang does not support references, so pass all parameters as
13951 // pointers.
13952 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013953 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013954 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013955 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
13956 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
13957 // uses semantics of argument handles by value, but it should be passed by
13958 // reference. C lang does not support references, so pass all parameters as
13959 // pointers.
13960 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013961 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013962 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013963 if (S != nullptr) {
13964 PushOnScopeChains(OmpPrivParm, S);
13965 PushOnScopeChains(OmpOrigParm, S);
13966 } else {
13967 DRD->addDecl(OmpPrivParm);
13968 DRD->addDecl(OmpOrigParm);
13969 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013970 Expr *OrigE =
13971 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
13972 Expr *PrivE =
13973 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
13974 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000013975 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013976}
13977
Alexey Bataev070f43a2017-09-06 14:49:58 +000013978void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
13979 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013980 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13981 DiscardCleanupsInEvaluationContext();
13982 PopExpressionEvaluationContext();
13983
13984 PopDeclContext();
13985 PopFunctionScopeInfo();
13986
Alexey Bataev070f43a2017-09-06 14:49:58 +000013987 if (Initializer != nullptr) {
13988 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
13989 } else if (OmpPrivParm->hasInit()) {
13990 DRD->setInitializer(OmpPrivParm->getInit(),
13991 OmpPrivParm->isDirectInit()
13992 ? OMPDeclareReductionDecl::DirectInit
13993 : OMPDeclareReductionDecl::CopyInit);
13994 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013995 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000013996 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013997}
13998
13999Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
14000 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014001 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014002 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014003 if (S)
14004 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
14005 /*AddToContext=*/false);
14006 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014007 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014008 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014009 }
14010 return DeclReductions;
14011}
14012
Michael Kruse251e1482019-02-01 20:25:04 +000014013TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
14014 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14015 QualType T = TInfo->getType();
14016 if (D.isInvalidType())
14017 return true;
14018
14019 if (getLangOpts().CPlusPlus) {
14020 // Check that there are no default arguments (C++ only).
14021 CheckExtraCXXDefaultArguments(D);
14022 }
14023
14024 return CreateParsedType(T, TInfo);
14025}
14026
14027QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
14028 TypeResult ParsedType) {
14029 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
14030
14031 QualType MapperType = GetTypeFromParser(ParsedType.get());
14032 assert(!MapperType.isNull() && "Expect valid mapper type");
14033
14034 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14035 // The type must be of struct, union or class type in C and C++
14036 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
14037 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
14038 return QualType();
14039 }
14040 return MapperType;
14041}
14042
14043OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
14044 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
14045 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
14046 Decl *PrevDeclInScope) {
14047 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
14048 forRedeclarationInCurContext());
14049 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14050 // A mapper-identifier may not be redeclared in the current scope for the
14051 // same type or for a type that is compatible according to the base language
14052 // rules.
14053 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
14054 OMPDeclareMapperDecl *PrevDMD = nullptr;
14055 bool InCompoundScope = true;
14056 if (S != nullptr) {
14057 // Find previous declaration with the same name not referenced in other
14058 // declarations.
14059 FunctionScopeInfo *ParentFn = getEnclosingFunction();
14060 InCompoundScope =
14061 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
14062 LookupName(Lookup, S);
14063 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14064 /*AllowInlineNamespace=*/false);
14065 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
14066 LookupResult::Filter Filter = Lookup.makeFilter();
14067 while (Filter.hasNext()) {
14068 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
14069 if (InCompoundScope) {
14070 auto I = UsedAsPrevious.find(PrevDecl);
14071 if (I == UsedAsPrevious.end())
14072 UsedAsPrevious[PrevDecl] = false;
14073 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
14074 UsedAsPrevious[D] = true;
14075 }
14076 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14077 PrevDecl->getLocation();
14078 }
14079 Filter.done();
14080 if (InCompoundScope) {
14081 for (const auto &PrevData : UsedAsPrevious) {
14082 if (!PrevData.second) {
14083 PrevDMD = PrevData.first;
14084 break;
14085 }
14086 }
14087 }
14088 } else if (PrevDeclInScope) {
14089 auto *PrevDMDInScope = PrevDMD =
14090 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
14091 do {
14092 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
14093 PrevDMDInScope->getLocation();
14094 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
14095 } while (PrevDMDInScope != nullptr);
14096 }
14097 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
14098 bool Invalid = false;
14099 if (I != PreviousRedeclTypes.end()) {
14100 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
14101 << MapperType << Name;
14102 Diag(I->second, diag::note_previous_definition);
14103 Invalid = true;
14104 }
14105 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
14106 MapperType, VN, PrevDMD);
14107 DC->addDecl(DMD);
14108 DMD->setAccess(AS);
14109 if (Invalid)
14110 DMD->setInvalidDecl();
14111
14112 // Enter new function scope.
14113 PushFunctionScope();
14114 setFunctionHasBranchProtectedScope();
14115
14116 CurContext = DMD;
14117
14118 return DMD;
14119}
14120
14121void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
14122 Scope *S,
14123 QualType MapperType,
14124 SourceLocation StartLoc,
14125 DeclarationName VN) {
14126 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
14127 if (S)
14128 PushOnScopeChains(VD, S);
14129 else
14130 DMD->addDecl(VD);
14131 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
14132 DMD->setMapperVarRef(MapperVarRefExpr);
14133}
14134
14135Sema::DeclGroupPtrTy
14136Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
14137 ArrayRef<OMPClause *> ClauseList) {
14138 PopDeclContext();
14139 PopFunctionScopeInfo();
14140
14141 if (D) {
14142 if (S)
14143 PushOnScopeChains(D, S, /*AddToContext=*/false);
14144 D->CreateClauses(Context, ClauseList);
14145 }
14146
14147 return DeclGroupPtrTy::make(DeclGroupRef(D));
14148}
14149
David Majnemer9d168222016-08-05 17:44:54 +000014150OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000014151 SourceLocation StartLoc,
14152 SourceLocation LParenLoc,
14153 SourceLocation EndLoc) {
14154 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014155 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014156
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014157 // OpenMP [teams Constrcut, Restrictions]
14158 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014159 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000014160 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014161 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014162
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014163 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014164 OpenMPDirectiveKind CaptureRegion =
14165 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
14166 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014167 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014168 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014169 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14170 HelperValStmt = buildPreInits(Context, Captures);
14171 }
14172
14173 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
14174 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000014175}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014176
14177OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
14178 SourceLocation StartLoc,
14179 SourceLocation LParenLoc,
14180 SourceLocation EndLoc) {
14181 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014182 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014183
14184 // OpenMP [teams Constrcut, Restrictions]
14185 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014186 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000014187 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014188 return nullptr;
14189
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014190 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014191 OpenMPDirectiveKind CaptureRegion =
14192 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
14193 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014194 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014195 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014196 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14197 HelperValStmt = buildPreInits(Context, Captures);
14198 }
14199
14200 return new (Context) OMPThreadLimitClause(
14201 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014202}
Alexey Bataeva0569352015-12-01 10:17:31 +000014203
14204OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
14205 SourceLocation StartLoc,
14206 SourceLocation LParenLoc,
14207 SourceLocation EndLoc) {
14208 Expr *ValExpr = Priority;
14209
14210 // OpenMP [2.9.1, task Constrcut]
14211 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014212 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000014213 /*StrictlyPositive=*/false))
14214 return nullptr;
14215
14216 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14217}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014218
14219OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
14220 SourceLocation StartLoc,
14221 SourceLocation LParenLoc,
14222 SourceLocation EndLoc) {
14223 Expr *ValExpr = Grainsize;
14224
14225 // OpenMP [2.9.2, taskloop Constrcut]
14226 // The parameter of the grainsize clause must be a positive integer
14227 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014228 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014229 /*StrictlyPositive=*/true))
14230 return nullptr;
14231
14232 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14233}
Alexey Bataev382967a2015-12-08 12:06:20 +000014234
14235OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
14236 SourceLocation StartLoc,
14237 SourceLocation LParenLoc,
14238 SourceLocation EndLoc) {
14239 Expr *ValExpr = NumTasks;
14240
14241 // OpenMP [2.9.2, taskloop Constrcut]
14242 // The parameter of the num_tasks clause must be a positive integer
14243 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014244 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000014245 /*StrictlyPositive=*/true))
14246 return nullptr;
14247
14248 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14249}
14250
Alexey Bataev28c75412015-12-15 08:19:24 +000014251OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
14252 SourceLocation LParenLoc,
14253 SourceLocation EndLoc) {
14254 // OpenMP [2.13.2, critical construct, Description]
14255 // ... where hint-expression is an integer constant expression that evaluates
14256 // to a valid lock hint.
14257 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
14258 if (HintExpr.isInvalid())
14259 return nullptr;
14260 return new (Context)
14261 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
14262}
14263
Carlo Bertollib4adf552016-01-15 18:50:31 +000014264OMPClause *Sema::ActOnOpenMPDistScheduleClause(
14265 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14266 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
14267 SourceLocation EndLoc) {
14268 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
14269 std::string Values;
14270 Values += "'";
14271 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
14272 Values += "'";
14273 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14274 << Values << getOpenMPClauseName(OMPC_dist_schedule);
14275 return nullptr;
14276 }
14277 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000014278 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000014279 if (ChunkSize) {
14280 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14281 !ChunkSize->isInstantiationDependent() &&
14282 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014283 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000014284 ExprResult Val =
14285 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14286 if (Val.isInvalid())
14287 return nullptr;
14288
14289 ValExpr = Val.get();
14290
14291 // OpenMP [2.7.1, Restrictions]
14292 // chunk_size must be a loop invariant integer expression with a positive
14293 // value.
14294 llvm::APSInt Result;
14295 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
14296 if (Result.isSigned() && !Result.isStrictlyPositive()) {
14297 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14298 << "dist_schedule" << ChunkSize->getSourceRange();
14299 return nullptr;
14300 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000014301 } else if (getOpenMPCaptureRegionForClause(
14302 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
14303 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000014304 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014305 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014306 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000014307 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14308 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014309 }
14310 }
14311 }
14312
14313 return new (Context)
14314 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000014315 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014316}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014317
14318OMPClause *Sema::ActOnOpenMPDefaultmapClause(
14319 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
14320 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
14321 SourceLocation KindLoc, SourceLocation EndLoc) {
14322 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000014323 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014324 std::string Value;
14325 SourceLocation Loc;
14326 Value += "'";
14327 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
14328 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014329 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014330 Loc = MLoc;
14331 } else {
14332 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014333 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014334 Loc = KindLoc;
14335 }
14336 Value += "'";
14337 Diag(Loc, diag::err_omp_unexpected_clause_value)
14338 << Value << getOpenMPClauseName(OMPC_defaultmap);
14339 return nullptr;
14340 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000014341 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014342
14343 return new (Context)
14344 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
14345}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014346
14347bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
14348 DeclContext *CurLexicalContext = getCurLexicalContext();
14349 if (!CurLexicalContext->isFileContext() &&
14350 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000014351 !CurLexicalContext->isExternCXXContext() &&
14352 !isa<CXXRecordDecl>(CurLexicalContext) &&
14353 !isa<ClassTemplateDecl>(CurLexicalContext) &&
14354 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
14355 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014356 Diag(Loc, diag::err_omp_region_not_file_context);
14357 return false;
14358 }
Kelvin Libc38e632018-09-10 02:07:09 +000014359 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014360 return true;
14361}
14362
14363void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000014364 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014365 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000014366 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014367}
14368
David Majnemer9d168222016-08-05 17:44:54 +000014369void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
14370 CXXScopeSpec &ScopeSpec,
14371 const DeclarationNameInfo &Id,
14372 OMPDeclareTargetDeclAttr::MapTypeTy MT,
14373 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014374 LookupResult Lookup(*this, Id, LookupOrdinaryName);
14375 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
14376
14377 if (Lookup.isAmbiguous())
14378 return;
14379 Lookup.suppressDiagnostics();
14380
14381 if (!Lookup.isSingleResult()) {
14382 if (TypoCorrection Corrected =
14383 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
14384 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
14385 CTK_ErrorRecovery)) {
14386 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
14387 << Id.getName());
14388 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
14389 return;
14390 }
14391
14392 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
14393 return;
14394 }
14395
14396 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev30a78212018-09-11 13:59:10 +000014397 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
14398 isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014399 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
14400 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
Alexey Bataev30a78212018-09-11 13:59:10 +000014401 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14402 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
14403 cast<ValueDecl>(ND));
14404 if (!Res) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014405 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014406 ND->addAttr(A);
14407 if (ASTMutationListener *ML = Context.getASTMutationListener())
14408 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000014409 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Alexey Bataev30a78212018-09-11 13:59:10 +000014410 } else if (*Res != MT) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014411 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
14412 << Id.getName();
14413 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014414 } else {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014415 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataeve3727102018-04-18 15:57:46 +000014416 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014417}
14418
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014419static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
14420 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014421 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014422 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000014423 auto *VD = cast<VarDecl>(D);
14424 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
14425 return;
14426 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
14427 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014428}
14429
14430static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
14431 Sema &SemaRef, DSAStackTy *Stack,
14432 ValueDecl *VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014433 return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14434 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
14435 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014436}
14437
Kelvin Li1ce87c72017-12-12 20:08:12 +000014438void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
14439 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014440 if (!D || D->isInvalidDecl())
14441 return;
14442 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014443 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014444 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000014445 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000014446 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
14447 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000014448 return;
14449 // 2.10.6: threadprivate variable cannot appear in a declare target
14450 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014451 if (DSAStack->isThreadPrivate(VD)) {
14452 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000014453 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014454 return;
14455 }
14456 }
Alexey Bataev97b72212018-08-14 18:31:20 +000014457 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
14458 D = FTD->getTemplatedDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014459 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014460 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14461 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
14462 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000014463 assert(IdLoc.isValid() && "Source location is expected");
14464 Diag(IdLoc, diag::err_omp_function_in_link_clause);
14465 Diag(FD->getLocation(), diag::note_defined_here) << FD;
14466 return;
14467 }
14468 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014469 if (auto *VD = dyn_cast<ValueDecl>(D)) {
14470 // Problem if any with var declared with incomplete type will be reported
14471 // as normal, so no need to check it here.
14472 if ((E || !VD->getType()->isIncompleteType()) &&
14473 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
14474 return;
14475 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
14476 // Checking declaration inside declare target region.
14477 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
14478 isa<FunctionTemplateDecl>(D)) {
14479 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
14480 Context, OMPDeclareTargetDeclAttr::MT_To);
14481 D->addAttr(A);
14482 if (ASTMutationListener *ML = Context.getASTMutationListener())
14483 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
14484 }
14485 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014486 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014487 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014488 if (!E)
14489 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014490 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
14491}
Samuel Antao661c0902016-05-26 17:39:58 +000014492
14493OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000014494 CXXScopeSpec &MapperIdScopeSpec,
14495 DeclarationNameInfo &MapperId,
14496 const OMPVarListLocTy &Locs,
14497 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000014498 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014499 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
14500 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000014501 if (MVLI.ProcessedVarList.empty())
14502 return nullptr;
14503
Michael Kruse01f670d2019-02-22 22:29:42 +000014504 return OMPToClause::Create(
14505 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14506 MVLI.VarComponents, MVLI.UDMapperList,
14507 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000014508}
Samuel Antaoec172c62016-05-26 17:49:04 +000014509
14510OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000014511 CXXScopeSpec &MapperIdScopeSpec,
14512 DeclarationNameInfo &MapperId,
14513 const OMPVarListLocTy &Locs,
14514 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014515 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014516 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
14517 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000014518 if (MVLI.ProcessedVarList.empty())
14519 return nullptr;
14520
Michael Kruse0336c752019-02-25 20:34:15 +000014521 return OMPFromClause::Create(
14522 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14523 MVLI.VarComponents, MVLI.UDMapperList,
14524 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000014525}
Carlo Bertolli2404b172016-07-13 15:37:16 +000014526
14527OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014528 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000014529 MappableVarListInfo MVLI(VarList);
14530 SmallVector<Expr *, 8> PrivateCopies;
14531 SmallVector<Expr *, 8> Inits;
14532
Alexey Bataeve3727102018-04-18 15:57:46 +000014533 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014534 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
14535 SourceLocation ELoc;
14536 SourceRange ERange;
14537 Expr *SimpleRefExpr = RefExpr;
14538 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14539 if (Res.second) {
14540 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000014541 MVLI.ProcessedVarList.push_back(RefExpr);
14542 PrivateCopies.push_back(nullptr);
14543 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014544 }
14545 ValueDecl *D = Res.first;
14546 if (!D)
14547 continue;
14548
14549 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000014550 Type = Type.getNonReferenceType().getUnqualifiedType();
14551
14552 auto *VD = dyn_cast<VarDecl>(D);
14553
14554 // Item should be a pointer or reference to pointer.
14555 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014556 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
14557 << 0 << RefExpr->getSourceRange();
14558 continue;
14559 }
Samuel Antaocc10b852016-07-28 14:23:26 +000014560
14561 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014562 auto VDPrivate =
14563 buildVarDecl(*this, ELoc, Type, D->getName(),
14564 D->hasAttrs() ? &D->getAttrs() : nullptr,
14565 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000014566 if (VDPrivate->isInvalidDecl())
14567 continue;
14568
14569 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014570 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000014571 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
14572
14573 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000014574 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000014575 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000014576 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
14577 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000014578 AddInitializerToDecl(VDPrivate,
14579 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014580 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000014581
14582 // If required, build a capture to implement the privatization initialized
14583 // with the current list item value.
14584 DeclRefExpr *Ref = nullptr;
14585 if (!VD)
14586 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14587 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
14588 PrivateCopies.push_back(VDPrivateRefExpr);
14589 Inits.push_back(VDInitRefExpr);
14590
14591 // We need to add a data sharing attribute for this variable to make sure it
14592 // is correctly captured. A variable that shows up in a use_device_ptr has
14593 // similar properties of a first private variable.
14594 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
14595
14596 // Create a mappable component for the list item. List items in this clause
14597 // only need a component.
14598 MVLI.VarBaseDeclarations.push_back(D);
14599 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14600 MVLI.VarComponents.back().push_back(
14601 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000014602 }
14603
Samuel Antaocc10b852016-07-28 14:23:26 +000014604 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000014605 return nullptr;
14606
Samuel Antaocc10b852016-07-28 14:23:26 +000014607 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000014608 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
14609 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014610}
Carlo Bertolli70594e92016-07-13 17:16:49 +000014611
14612OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014613 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000014614 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000014615 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000014616 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000014617 SourceLocation ELoc;
14618 SourceRange ERange;
14619 Expr *SimpleRefExpr = RefExpr;
14620 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14621 if (Res.second) {
14622 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000014623 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014624 }
14625 ValueDecl *D = Res.first;
14626 if (!D)
14627 continue;
14628
14629 QualType Type = D->getType();
14630 // item should be a pointer or array or reference to pointer or array
14631 if (!Type.getNonReferenceType()->isPointerType() &&
14632 !Type.getNonReferenceType()->isArrayType()) {
14633 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
14634 << 0 << RefExpr->getSourceRange();
14635 continue;
14636 }
Samuel Antao6890b092016-07-28 14:25:09 +000014637
14638 // Check if the declaration in the clause does not show up in any data
14639 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000014640 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000014641 if (isOpenMPPrivate(DVar.CKind)) {
14642 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
14643 << getOpenMPClauseName(DVar.CKind)
14644 << getOpenMPClauseName(OMPC_is_device_ptr)
14645 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000014646 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000014647 continue;
14648 }
14649
Alexey Bataeve3727102018-04-18 15:57:46 +000014650 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000014651 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000014652 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000014653 [&ConflictExpr](
14654 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
14655 OpenMPClauseKind) -> bool {
14656 ConflictExpr = R.front().getAssociatedExpression();
14657 return true;
14658 })) {
14659 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
14660 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
14661 << ConflictExpr->getSourceRange();
14662 continue;
14663 }
14664
14665 // Store the components in the stack so that they can be used to check
14666 // against other clauses later on.
14667 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
14668 DSAStack->addMappableExpressionComponents(
14669 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
14670
14671 // Record the expression we've just processed.
14672 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
14673
14674 // Create a mappable component for the list item. List items in this clause
14675 // only need a component. We use a null declaration to signal fields in
14676 // 'this'.
14677 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
14678 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
14679 "Unexpected device pointer expression!");
14680 MVLI.VarBaseDeclarations.push_back(
14681 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
14682 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14683 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014684 }
14685
Samuel Antao6890b092016-07-28 14:25:09 +000014686 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000014687 return nullptr;
14688
Michael Kruse4304e9d2019-02-19 16:38:20 +000014689 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
14690 MVLI.VarBaseDeclarations,
14691 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014692}