blob: 2011c0b92771cfb7bae3fcdf860ab4d393e5fa44 [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};
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000196 /// Vector of previously encountered target directives
197 SmallVector<SourceLocation, 2> TargetLocations;
Kelvin Li1408f912018-09-26 04:28:39 +0000198
Alexey Bataev758e55e2013-09-06 18:03:48 +0000199public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000200 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000201
Alexey Bataev27ef9512019-03-20 20:14:22 +0000202 /// Sets omp_allocator_handle_t type.
203 void setOMPAllocatorHandleT(QualType Ty) { OMPAllocatorHandleT = Ty; }
204 /// Gets omp_allocator_handle_t type.
205 QualType getOMPAllocatorHandleT() const { return OMPAllocatorHandleT; }
206 /// Sets the given default allocator.
207 void setAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
208 Expr *Allocator) {
209 OMPPredefinedAllocators[AllocatorKind] = Allocator;
210 }
211 /// Returns the specified default allocator.
212 Expr *getAllocator(OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind) const {
213 return OMPPredefinedAllocators[AllocatorKind];
214 }
215
Alexey Bataevaac108a2015-06-23 04:51:00 +0000216 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000217 OpenMPClauseKind getClauseParsingMode() const {
218 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
219 return ClauseKindMode;
220 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000221 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000222
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000223 bool isForceVarCapturing() const { return ForceCapturing; }
224 void setForceVarCapturing(bool V) { ForceCapturing = V; }
225
Alexey Bataev60705422018-10-30 15:50:12 +0000226 void setForceCaptureByReferenceInTargetExecutable(bool V) {
227 ForceCaptureByReferenceInTargetExecutable = V;
228 }
229 bool isForceCaptureByReferenceInTargetExecutable() const {
230 return ForceCaptureByReferenceInTargetExecutable;
231 }
232
Alexey Bataev758e55e2013-09-06 18:03:48 +0000233 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000234 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000235 if (Stack.empty() ||
236 Stack.back().second != CurrentNonCapturingFunctionScope)
237 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
238 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
239 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000240 }
241
242 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000243 assert(!Stack.back().first.empty() &&
244 "Data-sharing attributes stack is empty!");
245 Stack.back().first.pop_back();
246 }
247
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000248 /// Marks that we're started loop parsing.
249 void loopInit() {
250 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
251 "Expected loop-based directive.");
252 Stack.back().first.back().LoopStart = true;
253 }
254 /// Start capturing of the variables in the loop context.
255 void loopStart() {
256 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
257 "Expected loop-based directive.");
258 Stack.back().first.back().LoopStart = false;
259 }
260 /// true, if variables are captured, false otherwise.
261 bool isLoopStarted() const {
262 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
263 "Expected loop-based directive.");
264 return !Stack.back().first.back().LoopStart;
265 }
266 /// Marks (or clears) declaration as possibly loop counter.
267 void resetPossibleLoopCounter(const Decl *D = nullptr) {
268 Stack.back().first.back().PossiblyLoopCounter =
269 D ? D->getCanonicalDecl() : D;
270 }
271 /// Gets the possible loop counter decl.
272 const Decl *getPossiblyLoopCunter() const {
273 return Stack.back().first.back().PossiblyLoopCounter;
274 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000275 /// Start new OpenMP region stack in new non-capturing function.
276 void pushFunction() {
277 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
278 assert(!isa<CapturingScopeInfo>(CurFnScope));
279 CurrentNonCapturingFunctionScope = CurFnScope;
280 }
281 /// Pop region stack for non-capturing function.
282 void popFunction(const FunctionScopeInfo *OldFSI) {
283 if (!Stack.empty() && Stack.back().second == OldFSI) {
284 assert(Stack.back().first.empty());
285 Stack.pop_back();
286 }
287 CurrentNonCapturingFunctionScope = nullptr;
288 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
289 if (!isa<CapturingScopeInfo>(FSI)) {
290 CurrentNonCapturingFunctionScope = FSI;
291 break;
292 }
293 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000294 }
295
Alexey Bataeve3727102018-04-18 15:57:46 +0000296 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000297 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000298 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000299 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000300 getCriticalWithHint(const DeclarationNameInfo &Name) const {
301 auto I = Criticals.find(Name.getAsString());
302 if (I != Criticals.end())
303 return I->second;
304 return std::make_pair(nullptr, llvm::APSInt());
305 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000306 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000307 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000308 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000309 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000310
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000311 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000312 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000313 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000314 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000315 /// \return The index of the loop control variable in the list of associated
316 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000317 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000318 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000319 /// parent region.
320 /// \return The index of the loop control variable in the list of associated
321 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000322 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000323 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000324 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000325 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000326
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000327 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000328 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000329 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000330
Alexey Bataevfa312f32017-07-21 18:48:21 +0000331 /// Adds additional information for the reduction items with the reduction id
332 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000333 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000334 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000335 /// Adds additional information for the reduction items with the reduction id
336 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000337 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000338 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000339 /// Returns the location and reduction operation from the innermost parent
340 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000341 const DSAVarData
342 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
343 BinaryOperatorKind &BOK,
344 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000345 /// Returns the location and reduction operation from the innermost parent
346 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000347 const DSAVarData
348 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
349 const Expr *&ReductionRef,
350 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000351 /// Return reduction reference expression for the current taskgroup.
352 Expr *getTaskgroupReductionRef() const {
353 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
354 "taskgroup reference expression requested for non taskgroup "
355 "directive.");
356 return Stack.back().first.back().TaskgroupReductionRef;
357 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000358 /// Checks if the given \p VD declaration is actually a taskgroup reduction
359 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000360 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Alexey Bataev88202be2017-07-27 13:20:36 +0000361 return Stack.back().first[Level].TaskgroupReductionRef &&
362 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
363 ->getDecl() == VD;
364 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000365
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000366 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000367 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000368 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000369 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000370 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000371 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000372 /// match specified \a CPred predicate in any directive which matches \a DPred
373 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000374 const DSAVarData
375 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
376 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
377 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000378 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000379 /// match specified \a CPred predicate in any innermost directive which
380 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000381 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000382 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000383 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
384 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000385 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000386 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000387 /// attributes which match specified \a CPred predicate at the specified
388 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000389 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000390 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000391 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000392
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000393 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000394 /// specified \a DPred predicate.
395 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000396 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000397 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000398
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000399 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000400 bool hasDirective(
401 const llvm::function_ref<bool(
402 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
403 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000404 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000405
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000406 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000407 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000408 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000409 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000410 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000411 OpenMPDirectiveKind getDirective(unsigned Level) const {
412 assert(!isStackEmpty() && "No directive at specified level.");
413 return Stack.back().first[Level].Directive;
414 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000415 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000416 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000417 if (isStackEmpty() || Stack.back().first.size() == 1)
418 return OMPD_unknown;
419 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000420 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000421
Kelvin Li1408f912018-09-26 04:28:39 +0000422 /// Add requires decl to internal vector
423 void addRequiresDecl(OMPRequiresDecl *RD) {
424 RequiresDecls.push_back(RD);
425 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000426
Alexey Bataev318f431b2019-03-22 15:25:12 +0000427 /// Checks if the defined 'requires' directive has specified type of clause.
428 template <typename ClauseType>
429 bool hasRequiresDeclWithClause() {
430 return llvm::any_of(RequiresDecls, [](const OMPRequiresDecl *D) {
431 return llvm::any_of(D->clauselists(), [](const OMPClause *C) {
432 return isa<ClauseType>(C);
433 });
434 });
435 }
436
Kelvin Li1408f912018-09-26 04:28:39 +0000437 /// Checks for a duplicate clause amongst previously declared requires
438 /// directives
439 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
440 bool IsDuplicate = false;
441 for (OMPClause *CNew : ClauseList) {
442 for (const OMPRequiresDecl *D : RequiresDecls) {
443 for (const OMPClause *CPrev : D->clauselists()) {
444 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
445 SemaRef.Diag(CNew->getBeginLoc(),
446 diag::err_omp_requires_clause_redeclaration)
447 << getOpenMPClauseName(CNew->getClauseKind());
448 SemaRef.Diag(CPrev->getBeginLoc(),
449 diag::note_omp_requires_previous_clause)
450 << getOpenMPClauseName(CPrev->getClauseKind());
451 IsDuplicate = true;
452 }
453 }
454 }
455 }
456 return IsDuplicate;
457 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000458
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +0000459 /// Add location of previously encountered target to internal vector
460 void addTargetDirLocation(SourceLocation LocStart) {
461 TargetLocations.push_back(LocStart);
462 }
463
464 // Return previously encountered target region locations.
465 ArrayRef<SourceLocation> getEncounteredTargetLocs() const {
466 return TargetLocations;
467 }
468
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000469 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000470 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000471 assert(!isStackEmpty());
472 Stack.back().first.back().DefaultAttr = DSA_none;
473 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000474 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000475 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000476 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000477 assert(!isStackEmpty());
478 Stack.back().first.back().DefaultAttr = DSA_shared;
479 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000480 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000481 /// Set default data mapping attribute to 'tofrom:scalar'.
482 void setDefaultDMAToFromScalar(SourceLocation Loc) {
483 assert(!isStackEmpty());
484 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
485 Stack.back().first.back().DefaultMapAttrLoc = Loc;
486 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000487
488 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000489 return isStackEmpty() ? DSA_unspecified
490 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000491 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000492 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000493 return isStackEmpty() ? SourceLocation()
494 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000495 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000496 DefaultMapAttributes getDefaultDMA() const {
497 return isStackEmpty() ? DMA_unspecified
498 : Stack.back().first.back().DefaultMapAttr;
499 }
500 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
501 return Stack.back().first[Level].DefaultMapAttr;
502 }
503 SourceLocation getDefaultDMALocation() const {
504 return isStackEmpty() ? SourceLocation()
505 : Stack.back().first.back().DefaultMapAttrLoc;
506 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000507
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000508 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000509 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000510 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000511 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000512 }
513
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000514 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000515 void setOrderedRegion(bool IsOrdered, const Expr *Param,
516 OMPOrderedClause *Clause) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000517 assert(!isStackEmpty());
Alexey Bataevf138fda2018-08-13 19:04:24 +0000518 if (IsOrdered)
519 Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
520 else
521 Stack.back().first.back().OrderedRegion.reset();
522 }
523 /// Returns true, if region is ordered (has associated 'ordered' clause),
524 /// false - otherwise.
525 bool isOrderedRegion() const {
526 if (isStackEmpty())
527 return false;
528 return Stack.back().first.rbegin()->OrderedRegion.hasValue();
529 }
530 /// Returns optional parameter for the ordered region.
531 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
532 if (isStackEmpty() ||
533 !Stack.back().first.rbegin()->OrderedRegion.hasValue())
534 return std::make_pair(nullptr, nullptr);
535 return Stack.back().first.rbegin()->OrderedRegion.getValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000536 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000537 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000538 /// 'ordered' clause), false - otherwise.
539 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000540 if (isStackEmpty() || Stack.back().first.size() == 1)
541 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000542 return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000543 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000544 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000545 std::pair<const Expr *, OMPOrderedClause *>
546 getParentOrderedRegionParam() const {
547 if (isStackEmpty() || Stack.back().first.size() == 1 ||
548 !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
549 return std::make_pair(nullptr, nullptr);
550 return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
Alexey Bataev346265e2015-09-25 10:37:12 +0000551 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000552 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000553 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000554 assert(!isStackEmpty());
555 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000556 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000557 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000558 /// 'nowait' clause), false - otherwise.
559 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000560 if (isStackEmpty() || Stack.back().first.size() == 1)
561 return false;
562 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000563 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000564 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000565 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000566 if (!isStackEmpty() && Stack.back().first.size() > 1) {
567 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
568 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
569 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000570 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000571 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000572 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000573 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000574 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000575
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000576 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000577 void setAssociatedLoops(unsigned Val) {
578 assert(!isStackEmpty());
579 Stack.back().first.back().AssociatedLoops = Val;
580 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000581 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000582 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000583 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000584 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000585
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000586 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000587 /// region.
588 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000589 if (!isStackEmpty() && Stack.back().first.size() > 1) {
590 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
591 TeamsRegionLoc;
592 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000593 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000594 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000595 bool hasInnerTeamsRegion() const {
596 return getInnerTeamsRegionLoc().isValid();
597 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000598 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000599 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000600 return isStackEmpty() ? SourceLocation()
601 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000602 }
603
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000604 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000605 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000606 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000607 SourceLocation getConstructLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000608 return isStackEmpty() ? SourceLocation()
609 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000610 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000611
Samuel Antao4c8035b2016-12-12 18:00:20 +0000612 /// Do the check specified in \a Check to all component lists and return true
613 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000614 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000615 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000616 const llvm::function_ref<
617 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000618 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000619 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000620 if (isStackEmpty())
621 return false;
622 auto SI = Stack.back().first.rbegin();
623 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000624
625 if (SI == SE)
626 return false;
627
Alexey Bataeve3727102018-04-18 15:57:46 +0000628 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000629 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000630 else
631 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000632
633 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000634 auto MI = SI->MappedExprComponents.find(VD);
635 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000636 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
637 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000638 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000639 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000640 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000641 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000642 }
643
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000644 /// Do the check specified in \a Check to all component lists at a given level
645 /// and return true if any issue is found.
646 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000647 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000648 const llvm::function_ref<
649 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000650 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000651 Check) const {
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000652 if (isStackEmpty())
653 return false;
654
655 auto StartI = Stack.back().first.begin();
656 auto EndI = Stack.back().first.end();
657 if (std::distance(StartI, EndI) <= (int)Level)
658 return false;
659 std::advance(StartI, Level);
660
661 auto MI = StartI->MappedExprComponents.find(VD);
662 if (MI != StartI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000663 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
664 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000665 if (Check(L, MI->second.Kind))
666 return true;
667 return false;
668 }
669
Samuel Antao4c8035b2016-12-12 18:00:20 +0000670 /// Create a new mappable expression component list associated with a given
671 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000672 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000673 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000674 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
675 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000676 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000677 "Not expecting to retrieve components from a empty stack!");
Alexey Bataeve3727102018-04-18 15:57:46 +0000678 MappedExprComponentTy &MEC =
679 Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000680 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000681 MEC.Components.resize(MEC.Components.size() + 1);
682 MEC.Components.back().append(Components.begin(), Components.end());
683 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000684 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000685
686 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000687 assert(!isStackEmpty());
688 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000689 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000690 void addDoacrossDependClause(OMPDependClause *C,
691 const OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000692 assert(!isStackEmpty() && Stack.back().first.size() > 1);
Alexey Bataeve3727102018-04-18 15:57:46 +0000693 SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000694 assert(isOpenMPWorksharingDirective(StackElem.Directive));
Alexey Bataeve3727102018-04-18 15:57:46 +0000695 StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000696 }
697 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
698 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000699 assert(!isStackEmpty());
Alexey Bataeve3727102018-04-18 15:57:46 +0000700 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000701 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000702 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000703 return llvm::make_range(Ref.begin(), Ref.end());
704 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000705 return llvm::make_range(StackElem.DoacrossDepends.end(),
706 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000707 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000708
709 // Store types of classes which have been explicitly mapped
710 void addMappedClassesQualTypes(QualType QT) {
711 SharingMapTy &StackElem = Stack.back().first.back();
712 StackElem.MappedClassesQualTypes.insert(QT);
713 }
714
715 // Return set of mapped classes types
716 bool isClassPreviouslyMapped(QualType QT) const {
717 const SharingMapTy &StackElem = Stack.back().first.back();
718 return StackElem.MappedClassesQualTypes.count(QT) != 0;
719 }
720
Alexey Bataeva495c642019-03-11 19:51:42 +0000721 /// Adds global declare target to the parent target region.
722 void addToParentTargetRegionLinkGlobals(DeclRefExpr *E) {
723 assert(*OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
724 E->getDecl()) == OMPDeclareTargetDeclAttr::MT_Link &&
725 "Expected declare target link global.");
726 if (isStackEmpty())
727 return;
728 auto It = Stack.back().first.rbegin();
729 while (It != Stack.back().first.rend() &&
730 !isOpenMPTargetExecutionDirective(It->Directive))
731 ++It;
732 if (It != Stack.back().first.rend()) {
733 assert(isOpenMPTargetExecutionDirective(It->Directive) &&
734 "Expected target executable directive.");
735 It->DeclareTargetLinkVarDecls.push_back(E);
736 }
737 }
738
739 /// Returns the list of globals with declare target link if current directive
740 /// is target.
741 ArrayRef<DeclRefExpr *> getLinkGlobals() const {
742 assert(isOpenMPTargetExecutionDirective(getCurrentDirective()) &&
743 "Expected target executable directive.");
744 return Stack.back().first.back().DeclareTargetLinkVarDecls;
745 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000746};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000747
748bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
749 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
750}
751
752bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
753 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000754}
Alexey Bataeve3727102018-04-18 15:57:46 +0000755
Alexey Bataeved09d242014-05-28 05:53:51 +0000756} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000757
Alexey Bataeve3727102018-04-18 15:57:46 +0000758static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000759 if (const auto *FE = dyn_cast<FullExpr>(E))
760 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000761
Alexey Bataeve3727102018-04-18 15:57:46 +0000762 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000763 E = MTE->GetTemporaryExpr();
764
Alexey Bataeve3727102018-04-18 15:57:46 +0000765 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000766 E = Binder->getSubExpr();
767
Alexey Bataeve3727102018-04-18 15:57:46 +0000768 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000769 E = ICE->getSubExprAsWritten();
770 return E->IgnoreParens();
771}
772
Alexey Bataeve3727102018-04-18 15:57:46 +0000773static Expr *getExprAsWritten(Expr *E) {
774 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
775}
776
777static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
778 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
779 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000780 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000781 const auto *VD = dyn_cast<VarDecl>(D);
782 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000783 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000784 VD = VD->getCanonicalDecl();
785 D = VD;
786 } else {
787 assert(FD);
788 FD = FD->getCanonicalDecl();
789 D = FD;
790 }
791 return D;
792}
793
Alexey Bataeve3727102018-04-18 15:57:46 +0000794static ValueDecl *getCanonicalDecl(ValueDecl *D) {
795 return const_cast<ValueDecl *>(
796 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
797}
798
799DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
800 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000801 D = getCanonicalDecl(D);
802 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000803 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000804 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000805 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000806 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
807 // in a region but not in construct]
808 // File-scope or namespace-scope variables referenced in called routines
809 // in the region are shared unless they appear in a threadprivate
810 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000811 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000812 DVar.CKind = OMPC_shared;
813
814 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
815 // in a region but not in construct]
816 // Variables with static storage duration that are declared in called
817 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000818 if (VD && VD->hasGlobalStorage())
819 DVar.CKind = OMPC_shared;
820
821 // Non-static data members are shared by default.
822 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000823 DVar.CKind = OMPC_shared;
824
Alexey Bataev758e55e2013-09-06 18:03:48 +0000825 return DVar;
826 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000827
Alexey Bataevec3da872014-01-31 05:15:34 +0000828 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
829 // in a Construct, C/C++, predetermined, p.1]
830 // Variables with automatic storage duration that are declared in a scope
831 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000832 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
833 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000834 DVar.CKind = OMPC_private;
835 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000836 }
837
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000838 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000839 // Explicitly specified attributes and local variables with predetermined
840 // attributes.
841 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000842 const DSAInfo &Data = Iter->SharingMap.lookup(D);
843 DVar.RefExpr = Data.RefExpr.getPointer();
844 DVar.PrivateCopy = Data.PrivateCopy;
845 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000846 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000847 return DVar;
848 }
849
850 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
851 // in a Construct, C/C++, implicitly determined, p.1]
852 // In a parallel or task construct, the data-sharing attributes of these
853 // variables are determined by the default clause, if present.
854 switch (Iter->DefaultAttr) {
855 case DSA_shared:
856 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000857 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000858 return DVar;
859 case DSA_none:
860 return DVar;
861 case DSA_unspecified:
862 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
863 // in a Construct, implicitly determined, p.2]
864 // In a parallel construct, if no default clause is present, these
865 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000866 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000867 if (isOpenMPParallelDirective(DVar.DKind) ||
868 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000869 DVar.CKind = OMPC_shared;
870 return DVar;
871 }
872
873 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
874 // in a Construct, implicitly determined, p.4]
875 // In a task construct, if no default clause is present, a variable that in
876 // the enclosing context is determined to be shared by all implicit tasks
877 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000878 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000879 DSAVarData DVarTemp;
Alexey Bataeve3727102018-04-18 15:57:46 +0000880 iterator I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000881 do {
882 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000883 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000884 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000885 // In a task construct, if no default clause is present, a variable
886 // whose data-sharing attribute is not determined by the rules above is
887 // firstprivate.
888 DVarTemp = getDSA(I, D);
889 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000890 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000891 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000892 return DVar;
893 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000894 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000895 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000896 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000897 return DVar;
898 }
899 }
900 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
901 // in a Construct, implicitly determined, p.3]
902 // For constructs other than task, if no default clause is present, these
903 // variables inherit their data-sharing attributes from the enclosing
904 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000905 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000906}
907
Alexey Bataeve3727102018-04-18 15:57:46 +0000908const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
909 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000910 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000911 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000912 SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000913 auto It = StackElem.AlignedMap.find(D);
914 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000915 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000916 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000917 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000918 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000919 assert(It->second && "Unexpected nullptr expr in the aligned map");
920 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000921}
922
Alexey Bataeve3727102018-04-18 15:57:46 +0000923void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000924 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000925 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000926 SharingMapTy &StackElem = Stack.back().first.back();
927 StackElem.LCVMap.try_emplace(
928 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +0000929}
930
Alexey Bataeve3727102018-04-18 15:57:46 +0000931const DSAStackTy::LCDeclInfo
932DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000933 assert(!isStackEmpty() && "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 = Stack.back().first.back();
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 DSAStackTy::LCDeclInfo
943DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000944 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
945 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000946 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000947 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000948 auto It = StackElem.LCVMap.find(D);
949 if (It != StackElem.LCVMap.end())
950 return It->second;
951 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000952}
953
Alexey Bataeve3727102018-04-18 15:57:46 +0000954const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000955 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
956 "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000957 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000958 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000959 return nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +0000960 for (const auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000961 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000962 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000963 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000964}
965
Alexey Bataeve3727102018-04-18 15:57:46 +0000966void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000967 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000968 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000969 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000970 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000971 Data.Attributes = A;
972 Data.RefExpr.setPointer(E);
973 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000974 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000975 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000976 DSAInfo &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000977 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
978 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
979 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
980 (isLoopControlVariable(D).first && A == OMPC_private));
981 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
982 Data.RefExpr.setInt(/*IntVal=*/true);
983 return;
984 }
985 const bool IsLastprivate =
986 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
987 Data.Attributes = A;
988 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
989 Data.PrivateCopy = PrivateCopy;
990 if (PrivateCopy) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000991 DSAInfo &Data =
992 Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000993 Data.Attributes = A;
994 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
995 Data.PrivateCopy = nullptr;
996 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000997 }
998}
999
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00001000/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001001static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001002 StringRef Name, const AttrVec *Attrs = nullptr,
1003 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001004 DeclContext *DC = SemaRef.CurContext;
1005 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
1006 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +00001007 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001008 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
1009 if (Attrs) {
1010 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
1011 I != E; ++I)
1012 Decl->addAttr(*I);
1013 }
1014 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001015 if (OrigRef) {
1016 Decl->addAttr(
1017 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
1018 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001019 return Decl;
1020}
1021
1022static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
1023 SourceLocation Loc,
1024 bool RefersToCapture = false) {
1025 D->setReferenced();
1026 D->markUsed(S.Context);
1027 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
1028 SourceLocation(), D, RefersToCapture, Loc, Ty,
1029 VK_LValue);
1030}
1031
Alexey Bataeve3727102018-04-18 15:57:46 +00001032void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001033 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001034 D = getCanonicalDecl(D);
1035 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001036 assert(
Richard Trieu09f14112017-07-21 21:29:35 +00001037 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001038 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +00001039 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001040 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001041 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001042 "Additional reduction info may be specified only once for reduction "
1043 "items.");
1044 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001045 Expr *&TaskgroupReductionRef =
1046 Stack.back().first.back().TaskgroupReductionRef;
1047 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001048 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1049 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001050 TaskgroupReductionRef =
1051 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001052 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001053}
1054
Alexey Bataeve3727102018-04-18 15:57:46 +00001055void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001056 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001057 D = getCanonicalDecl(D);
1058 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +00001059 assert(
Richard Trieu09f14112017-07-21 21:29:35 +00001060 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001061 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +00001062 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +00001063 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001064 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +00001065 "Additional reduction info may be specified only once for reduction "
1066 "items.");
1067 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001068 Expr *&TaskgroupReductionRef =
1069 Stack.back().first.back().TaskgroupReductionRef;
1070 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001071 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1072 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001073 TaskgroupReductionRef =
1074 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001075 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001076}
1077
Alexey Bataeve3727102018-04-18 15:57:46 +00001078const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1079 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1080 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001081 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001082 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1083 if (Stack.back().first.empty())
1084 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001085 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1086 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001087 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001088 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001089 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001090 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001091 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001092 if (!ReductionData.ReductionOp ||
1093 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001094 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001095 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001096 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001097 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1098 "expression for the descriptor is not "
1099 "set.");
1100 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001101 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1102 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001103 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001104 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001105}
1106
Alexey Bataeve3727102018-04-18 15:57:46 +00001107const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1108 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1109 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001110 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001111 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1112 if (Stack.back().first.empty())
1113 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001114 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1115 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001116 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001117 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001118 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001119 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001120 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001121 if (!ReductionData.ReductionOp ||
1122 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001123 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001124 SR = ReductionData.ReductionRange;
1125 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001126 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1127 "expression for the descriptor is not "
1128 "set.");
1129 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001130 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1131 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001132 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001133 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001134}
1135
Alexey Bataeve3727102018-04-18 15:57:46 +00001136bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001137 D = D->getCanonicalDecl();
Alexey Bataev852525d2018-03-02 17:17:12 +00001138 if (!isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001139 iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001140 Scope *TopScope = nullptr;
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001141 while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) &&
Alexey Bataev852525d2018-03-02 17:17:12 +00001142 !isOpenMPTargetExecutionDirective(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +00001143 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +00001144 if (I == E)
1145 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001146 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001147 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001148 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +00001149 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +00001150 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001151 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001152 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001153}
1154
Joel E. Dennyd2649292019-01-04 22:11:56 +00001155static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1156 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001157 bool *IsClassType = nullptr) {
1158 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001159 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001160 bool IsConstant = Type.isConstant(Context);
1161 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001162 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1163 ? Type->getAsCXXRecordDecl()
1164 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001165 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1166 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1167 RD = CTD->getTemplatedDecl();
1168 if (IsClassType)
1169 *IsClassType = RD;
1170 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1171 RD->hasDefinition() && RD->hasMutableFields());
1172}
1173
Joel E. Dennyd2649292019-01-04 22:11:56 +00001174static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1175 QualType Type, OpenMPClauseKind CKind,
1176 SourceLocation ELoc,
1177 bool AcceptIfMutable = true,
1178 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001179 ASTContext &Context = SemaRef.getASTContext();
1180 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001181 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1182 unsigned Diag = ListItemNotVar
1183 ? diag::err_omp_const_list_item
1184 : IsClassType ? diag::err_omp_const_not_mutable_variable
1185 : diag::err_omp_const_variable;
1186 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1187 if (!ListItemNotVar && D) {
1188 const VarDecl *VD = dyn_cast<VarDecl>(D);
1189 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1190 VarDecl::DeclarationOnly;
1191 SemaRef.Diag(D->getLocation(),
1192 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1193 << D;
1194 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001195 return true;
1196 }
1197 return false;
1198}
1199
Alexey Bataeve3727102018-04-18 15:57:46 +00001200const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1201 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001202 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001203 DSAVarData DVar;
1204
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001205 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001206 auto TI = Threadprivates.find(D);
1207 if (TI != Threadprivates.end()) {
1208 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001209 DVar.CKind = OMPC_threadprivate;
1210 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001211 }
1212 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001213 DVar.RefExpr = buildDeclRefExpr(
1214 SemaRef, VD, D->getType().getNonReferenceType(),
1215 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1216 DVar.CKind = OMPC_threadprivate;
1217 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001218 return DVar;
1219 }
1220 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1221 // in a Construct, C/C++, predetermined, p.1]
1222 // Variables appearing in threadprivate directives are threadprivate.
1223 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1224 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1225 SemaRef.getLangOpts().OpenMPUseTLS &&
1226 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1227 (VD && VD->getStorageClass() == SC_Register &&
1228 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1229 DVar.RefExpr = buildDeclRefExpr(
1230 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1231 DVar.CKind = OMPC_threadprivate;
1232 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1233 return DVar;
1234 }
1235 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1236 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1237 !isLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001238 iterator IterTarget =
Alexey Bataev852525d2018-03-02 17:17:12 +00001239 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
1240 [](const SharingMapTy &Data) {
1241 return isOpenMPTargetExecutionDirective(Data.Directive);
1242 });
1243 if (IterTarget != Stack.back().first.rend()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001244 iterator ParentIterTarget = std::next(IterTarget, 1);
1245 for (iterator Iter = Stack.back().first.rbegin();
1246 Iter != ParentIterTarget; std::advance(Iter, 1)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001247 if (isOpenMPLocal(VD, Iter)) {
1248 DVar.RefExpr =
1249 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1250 D->getLocation());
1251 DVar.CKind = OMPC_threadprivate;
1252 return DVar;
1253 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001254 }
1255 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1256 auto DSAIter = IterTarget->SharingMap.find(D);
1257 if (DSAIter != IterTarget->SharingMap.end() &&
1258 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1259 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1260 DVar.CKind = OMPC_threadprivate;
1261 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001262 }
1263 iterator End = Stack.back().first.rend();
1264 if (!SemaRef.isOpenMPCapturedByRef(
1265 D, std::distance(ParentIterTarget, End))) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001266 DVar.RefExpr =
1267 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1268 IterTarget->ConstructLoc);
1269 DVar.CKind = OMPC_threadprivate;
1270 return DVar;
1271 }
1272 }
1273 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001274 }
1275
Alexey Bataev4b465392017-04-26 15:06:24 +00001276 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001277 // Not in OpenMP execution region and top scope was already checked.
1278 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001279
Alexey Bataev758e55e2013-09-06 18:03:48 +00001280 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001281 // in a Construct, C/C++, predetermined, p.4]
1282 // Static data members are shared.
1283 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1284 // in a Construct, C/C++, predetermined, p.7]
1285 // Variables with static storage duration that are declared in a scope
1286 // inside the construct are shared.
Alexey Bataeve3727102018-04-18 15:57:46 +00001287 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001288 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001289 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001290 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +00001291 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001292
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001293 DVar.CKind = OMPC_shared;
1294 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001295 }
1296
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001297 // The predetermined shared attribute for const-qualified types having no
1298 // mutable members was removed after OpenMP 3.1.
1299 if (SemaRef.LangOpts.OpenMP <= 31) {
1300 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1301 // in a Construct, C/C++, predetermined, p.6]
1302 // Variables with const qualified type having no mutable member are
1303 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001304 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001305 // Variables with const-qualified type having no mutable member may be
1306 // listed in a firstprivate clause, even if they are static data members.
1307 DSAVarData DVarTemp = hasInnermostDSA(
1308 D,
1309 [](OpenMPClauseKind C) {
1310 return C == OMPC_firstprivate || C == OMPC_shared;
1311 },
1312 MatchesAlways, FromParent);
1313 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1314 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001315
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001316 DVar.CKind = OMPC_shared;
1317 return DVar;
1318 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001319 }
1320
Alexey Bataev758e55e2013-09-06 18:03:48 +00001321 // Explicitly specified attributes and local variables with predetermined
1322 // attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +00001323 iterator I = Stack.back().first.rbegin();
1324 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001325 if (FromParent && I != EndI)
1326 std::advance(I, 1);
Alexey Bataeve3727102018-04-18 15:57:46 +00001327 auto It = I->SharingMap.find(D);
1328 if (It != I->SharingMap.end()) {
1329 const DSAInfo &Data = It->getSecond();
1330 DVar.RefExpr = Data.RefExpr.getPointer();
1331 DVar.PrivateCopy = Data.PrivateCopy;
1332 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001333 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001334 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001335 }
1336
1337 return DVar;
1338}
1339
Alexey Bataeve3727102018-04-18 15:57:46 +00001340const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1341 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001342 if (isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001343 iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001344 return getDSA(I, D);
1345 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001346 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001347 iterator StartI = Stack.back().first.rbegin();
1348 iterator EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001349 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001350 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001351 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001352}
1353
Alexey Bataeve3727102018-04-18 15:57:46 +00001354const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001355DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001356 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1357 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001358 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001359 if (isStackEmpty())
1360 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001361 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001362 iterator I = Stack.back().first.rbegin();
1363 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001364 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001365 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001366 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001367 if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001368 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001369 iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001370 DSAVarData DVar = getDSA(NewI, D);
1371 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001372 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001373 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001374 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001375}
1376
Alexey Bataeve3727102018-04-18 15:57:46 +00001377const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001378 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1379 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001380 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001381 if (isStackEmpty())
1382 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001383 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001384 iterator StartI = Stack.back().first.rbegin();
1385 iterator EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001386 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001387 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001388 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001389 return {};
Alexey Bataeve3727102018-04-18 15:57:46 +00001390 iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001391 DSAVarData DVar = getDSA(NewI, D);
1392 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001393}
1394
Alexey Bataevaac108a2015-06-23 04:51:00 +00001395bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001396 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1397 unsigned Level, bool NotLastprivate) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001398 if (isStackEmpty())
1399 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001400 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001401 auto StartI = Stack.back().first.begin();
1402 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001403 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001404 return false;
1405 std::advance(StartI, Level);
Alexey Bataeve3727102018-04-18 15:57:46 +00001406 auto I = StartI->SharingMap.find(D);
Alexey Bataev92b33652018-11-21 19:41:10 +00001407 if ((I != StartI->SharingMap.end()) &&
Alexey Bataeve3727102018-04-18 15:57:46 +00001408 I->getSecond().RefExpr.getPointer() &&
1409 CPred(I->getSecond().Attributes) &&
Alexey Bataev92b33652018-11-21 19:41:10 +00001410 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1411 return true;
1412 // Check predetermined rules for the loop control variables.
1413 auto LI = StartI->LCVMap.find(D);
1414 if (LI != StartI->LCVMap.end())
1415 return CPred(OMPC_private);
1416 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001417}
1418
Samuel Antao4be30e92015-10-02 17:14:03 +00001419bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001420 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1421 unsigned Level) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001422 if (isStackEmpty())
1423 return false;
1424 auto StartI = Stack.back().first.begin();
1425 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001426 if (std::distance(StartI, EndI) <= (int)Level)
1427 return false;
1428 std::advance(StartI, Level);
1429 return DPred(StartI->Directive);
1430}
1431
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001432bool DSAStackTy::hasDirective(
1433 const llvm::function_ref<bool(OpenMPDirectiveKind,
1434 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001435 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001436 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001437 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001438 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001439 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001440 auto StartI = std::next(Stack.back().first.rbegin());
1441 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001442 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001443 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001444 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1445 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1446 return true;
1447 }
1448 return false;
1449}
1450
Alexey Bataev758e55e2013-09-06 18:03:48 +00001451void Sema::InitDataSharingAttributesStack() {
1452 VarDataSharingAttributesStack = new DSAStackTy(*this);
1453}
1454
1455#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1456
Alexey Bataev4b465392017-04-26 15:06:24 +00001457void Sema::pushOpenMPFunctionRegion() {
1458 DSAStack->pushFunction();
1459}
1460
1461void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1462 DSAStack->popFunction(OldFSI);
1463}
1464
Alexey Bataevc416e642019-02-08 18:02:25 +00001465static bool isOpenMPDeviceDelayedContext(Sema &S) {
1466 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1467 "Expected OpenMP device compilation.");
1468 return !S.isInOpenMPTargetExecutionDirective() &&
1469 !S.isInOpenMPDeclareTargetContext();
1470}
1471
1472/// Do we know that we will eventually codegen the given function?
1473static bool isKnownEmitted(Sema &S, FunctionDecl *FD) {
1474 assert(S.LangOpts.OpenMP && S.LangOpts.OpenMPIsDevice &&
1475 "Expected OpenMP device compilation.");
1476 // Templates are emitted when they're instantiated.
1477 if (FD->isDependentContext())
1478 return false;
1479
1480 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
1481 FD->getCanonicalDecl()))
1482 return true;
1483
1484 // Otherwise, the function is known-emitted if it's in our set of
1485 // known-emitted functions.
1486 return S.DeviceKnownEmittedFns.count(FD) > 0;
1487}
1488
1489Sema::DeviceDiagBuilder Sema::diagIfOpenMPDeviceCode(SourceLocation Loc,
1490 unsigned DiagID) {
1491 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1492 "Expected OpenMP device compilation.");
1493 return DeviceDiagBuilder((isOpenMPDeviceDelayedContext(*this) &&
1494 !isKnownEmitted(*this, getCurFunctionDecl()))
1495 ? DeviceDiagBuilder::K_Deferred
1496 : DeviceDiagBuilder::K_Immediate,
1497 Loc, DiagID, getCurFunctionDecl(), *this);
1498}
1499
1500void Sema::checkOpenMPDeviceFunction(SourceLocation Loc, FunctionDecl *Callee) {
1501 assert(LangOpts.OpenMP && LangOpts.OpenMPIsDevice &&
1502 "Expected OpenMP device compilation.");
1503 assert(Callee && "Callee may not be null.");
1504 FunctionDecl *Caller = getCurFunctionDecl();
1505
1506 // If the caller is known-emitted, mark the callee as known-emitted.
1507 // Otherwise, mark the call in our call graph so we can traverse it later.
1508 if (!isOpenMPDeviceDelayedContext(*this) ||
1509 (Caller && isKnownEmitted(*this, Caller)))
1510 markKnownEmitted(*this, Caller, Callee, Loc, isKnownEmitted);
1511 else if (Caller)
1512 DeviceCallGraph[Caller].insert({Callee, Loc});
1513}
1514
Alexey Bataev123ad192019-02-27 20:29:45 +00001515void Sema::checkOpenMPDeviceExpr(const Expr *E) {
1516 assert(getLangOpts().OpenMP && getLangOpts().OpenMPIsDevice &&
1517 "OpenMP device compilation mode is expected.");
1518 QualType Ty = E->getType();
1519 if ((Ty->isFloat16Type() && !Context.getTargetInfo().hasFloat16Type()) ||
1520 (Ty->isFloat128Type() && !Context.getTargetInfo().hasFloat128Type()) ||
1521 (Ty->isIntegerType() && Context.getTypeSize(Ty) == 128 &&
1522 !Context.getTargetInfo().hasInt128Type()))
1523 targetDiag(E->getExprLoc(), diag::err_type_unsupported)
1524 << Ty << E->getSourceRange();
1525}
1526
Alexey Bataeve3727102018-04-18 15:57:46 +00001527bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001528 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1529
Alexey Bataeve3727102018-04-18 15:57:46 +00001530 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001531 bool IsByRef = true;
1532
1533 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001534 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001535 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001536
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001537 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001538 // This table summarizes how a given variable should be passed to the device
1539 // given its type and the clauses where it appears. This table is based on
1540 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1541 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1542 //
1543 // =========================================================================
1544 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1545 // | |(tofrom:scalar)| | pvt | | | |
1546 // =========================================================================
1547 // | scl | | | | - | | bycopy|
1548 // | scl | | - | x | - | - | bycopy|
1549 // | scl | | x | - | - | - | null |
1550 // | scl | x | | | - | | byref |
1551 // | scl | x | - | x | - | - | bycopy|
1552 // | scl | x | x | - | - | - | null |
1553 // | scl | | - | - | - | x | byref |
1554 // | scl | x | - | - | - | x | byref |
1555 //
1556 // | agg | n.a. | | | - | | byref |
1557 // | agg | n.a. | - | x | - | - | byref |
1558 // | agg | n.a. | x | - | - | - | null |
1559 // | agg | n.a. | - | - | - | x | byref |
1560 // | agg | n.a. | - | - | - | x[] | byref |
1561 //
1562 // | ptr | n.a. | | | - | | bycopy|
1563 // | ptr | n.a. | - | x | - | - | bycopy|
1564 // | ptr | n.a. | x | - | - | - | null |
1565 // | ptr | n.a. | - | - | - | x | byref |
1566 // | ptr | n.a. | - | - | - | x[] | bycopy|
1567 // | ptr | n.a. | - | - | x | | bycopy|
1568 // | ptr | n.a. | - | - | x | x | bycopy|
1569 // | ptr | n.a. | - | - | x | x[] | bycopy|
1570 // =========================================================================
1571 // Legend:
1572 // scl - scalar
1573 // ptr - pointer
1574 // agg - aggregate
1575 // x - applies
1576 // - - invalid in this combination
1577 // [] - mapped with an array section
1578 // byref - should be mapped by reference
1579 // byval - should be mapped by value
1580 // null - initialize a local variable to null on the device
1581 //
1582 // Observations:
1583 // - All scalar declarations that show up in a map clause have to be passed
1584 // by reference, because they may have been mapped in the enclosing data
1585 // environment.
1586 // - If the scalar value does not fit the size of uintptr, it has to be
1587 // passed by reference, regardless the result in the table above.
1588 // - For pointers mapped by value that have either an implicit map or an
1589 // array section, the runtime library may pass the NULL value to the
1590 // device instead of the value passed to it by the compiler.
1591
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001592 if (Ty->isReferenceType())
1593 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001594
1595 // Locate map clauses and see if the variable being captured is referred to
1596 // in any of those clauses. Here we only care about variables, not fields,
1597 // because fields are part of aggregates.
1598 bool IsVariableUsedInMapClause = false;
1599 bool IsVariableAssociatedWithSection = false;
1600
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001601 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001602 D, Level,
1603 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1604 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001605 MapExprComponents,
1606 OpenMPClauseKind WhereFoundClauseKind) {
1607 // Only the map clause information influences how a variable is
1608 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001609 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001610 if (WhereFoundClauseKind != OMPC_map)
1611 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001612
1613 auto EI = MapExprComponents.rbegin();
1614 auto EE = MapExprComponents.rend();
1615
1616 assert(EI != EE && "Invalid map expression!");
1617
1618 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1619 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1620
1621 ++EI;
1622 if (EI == EE)
1623 return false;
1624
1625 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1626 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1627 isa<MemberExpr>(EI->getAssociatedExpression())) {
1628 IsVariableAssociatedWithSection = true;
1629 // There is nothing more we need to know about this variable.
1630 return true;
1631 }
1632
1633 // Keep looking for more map info.
1634 return false;
1635 });
1636
1637 if (IsVariableUsedInMapClause) {
1638 // If variable is identified in a map clause it is always captured by
1639 // reference except if it is a pointer that is dereferenced somehow.
1640 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1641 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001642 // By default, all the data that has a scalar type is mapped by copy
1643 // (except for reduction variables).
1644 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001645 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1646 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001647 !Ty->isScalarType() ||
1648 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1649 DSAStack->hasExplicitDSA(
1650 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001651 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001652 }
1653
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001654 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001655 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001656 ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1657 !Ty->isAnyPointerType()) ||
1658 !DSAStack->hasExplicitDSA(
1659 D,
1660 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1661 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001662 // If the variable is artificial and must be captured by value - try to
1663 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001664 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1665 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001666 }
1667
Samuel Antao86ace552016-04-27 22:40:57 +00001668 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001669 // and alignment, because the runtime library only deals with uintptr types.
1670 // If it does not fit the uintptr size, we need to pass the data by reference
1671 // instead.
1672 if (!IsByRef &&
1673 (Ctx.getTypeSizeInChars(Ty) >
1674 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001675 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001676 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001677 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001678
1679 return IsByRef;
1680}
1681
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001682unsigned Sema::getOpenMPNestingLevel() const {
1683 assert(getLangOpts().OpenMP);
1684 return DSAStack->getNestingLevel();
1685}
1686
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001687bool Sema::isInOpenMPTargetExecutionDirective() const {
1688 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1689 !DSAStack->isClauseParsingMode()) ||
1690 DSAStack->hasDirective(
1691 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1692 SourceLocation) -> bool {
1693 return isOpenMPTargetExecutionDirective(K);
1694 },
1695 false);
1696}
1697
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001698VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001699 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001700 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001701
1702 // If we are attempting to capture a global variable in a directive with
1703 // 'target' we return true so that this global is also mapped to the device.
1704 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001705 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001706 if (VD && !VD->hasLocalStorage()) {
1707 if (isInOpenMPDeclareTargetContext() &&
1708 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1709 // Try to mark variable as declare target if it is used in capturing
1710 // regions.
Alexey Bataev97b72212018-08-14 18:31:20 +00001711 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001712 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001713 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001714 } else if (isInOpenMPTargetExecutionDirective()) {
1715 // If the declaration is enclosed in a 'declare target' directive,
1716 // then it should not be captured.
1717 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001718 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001719 return nullptr;
1720 return VD;
1721 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001722 }
Alexey Bataev60705422018-10-30 15:50:12 +00001723 // Capture variables captured by reference in lambdas for target-based
1724 // directives.
1725 if (VD && !DSAStack->isClauseParsingMode()) {
1726 if (const auto *RD = VD->getType()
1727 .getCanonicalType()
1728 .getNonReferenceType()
1729 ->getAsCXXRecordDecl()) {
1730 bool SavedForceCaptureByReferenceInTargetExecutable =
1731 DSAStack->isForceCaptureByReferenceInTargetExecutable();
1732 DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
Alexey Bataevd1840e52018-11-16 21:13:33 +00001733 if (RD->isLambda()) {
1734 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
1735 FieldDecl *ThisCapture;
1736 RD->getCaptureFields(Captures, ThisCapture);
Alexey Bataev60705422018-10-30 15:50:12 +00001737 for (const LambdaCapture &LC : RD->captures()) {
1738 if (LC.getCaptureKind() == LCK_ByRef) {
1739 VarDecl *VD = LC.getCapturedVar();
1740 DeclContext *VDC = VD->getDeclContext();
1741 if (!VDC->Encloses(CurContext))
1742 continue;
1743 DSAStackTy::DSAVarData DVarPrivate =
1744 DSAStack->getTopDSA(VD, /*FromParent=*/false);
1745 // Do not capture already captured variables.
1746 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
1747 DVarPrivate.CKind == OMPC_unknown &&
1748 !DSAStack->checkMappableExprComponentListsForDecl(
1749 D, /*CurrentRegionOnly=*/true,
1750 [](OMPClauseMappableExprCommon::
1751 MappableExprComponentListRef,
1752 OpenMPClauseKind) { return true; }))
1753 MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
1754 } else if (LC.getCaptureKind() == LCK_This) {
Alexey Bataevd1840e52018-11-16 21:13:33 +00001755 QualType ThisTy = getCurrentThisType();
1756 if (!ThisTy.isNull() &&
1757 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
1758 CheckCXXThisCapture(LC.getLocation());
Alexey Bataev60705422018-10-30 15:50:12 +00001759 }
1760 }
Alexey Bataevd1840e52018-11-16 21:13:33 +00001761 }
Alexey Bataev60705422018-10-30 15:50:12 +00001762 DSAStack->setForceCaptureByReferenceInTargetExecutable(
1763 SavedForceCaptureByReferenceInTargetExecutable);
1764 }
1765 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001766
Alexey Bataev48977c32015-08-04 08:10:48 +00001767 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1768 (!DSAStack->isClauseParsingMode() ||
1769 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001770 auto &&Info = DSAStack->isLoopControlVariable(D);
1771 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001772 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001773 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001774 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001775 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001776 DSAStackTy::DSAVarData DVarPrivate =
1777 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001778 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001779 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001780 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1781 [](OpenMPDirectiveKind) { return true; },
1782 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001783 if (DVarPrivate.CKind != OMPC_unknown)
1784 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001785 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001786 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001787}
1788
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001789void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1790 unsigned Level) const {
1791 SmallVector<OpenMPDirectiveKind, 4> Regions;
1792 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1793 FunctionScopesIndex -= Regions.size();
1794}
1795
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001796void Sema::startOpenMPLoop() {
1797 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1798 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1799 DSAStack->loopInit();
1800}
1801
Alexey Bataeve3727102018-04-18 15:57:46 +00001802bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001803 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001804 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1805 if (DSAStack->getAssociatedLoops() > 0 &&
1806 !DSAStack->isLoopStarted()) {
1807 DSAStack->resetPossibleLoopCounter(D);
1808 DSAStack->loopStart();
1809 return true;
1810 }
1811 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1812 DSAStack->isLoopControlVariable(D).first) &&
1813 !DSAStack->hasExplicitDSA(
1814 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1815 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
1816 return true;
1817 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00001818 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001819 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001820 (DSAStack->isClauseParsingMode() &&
1821 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001822 // Consider taskgroup reduction descriptor variable a private to avoid
1823 // possible capture in the region.
1824 (DSAStack->hasExplicitDirective(
1825 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1826 Level) &&
1827 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001828}
1829
Alexey Bataeve3727102018-04-18 15:57:46 +00001830void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1831 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001832 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1833 D = getCanonicalDecl(D);
1834 OpenMPClauseKind OMPC = OMPC_unknown;
1835 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1836 const unsigned NewLevel = I - 1;
1837 if (DSAStack->hasExplicitDSA(D,
1838 [&OMPC](const OpenMPClauseKind K) {
1839 if (isOpenMPPrivate(K)) {
1840 OMPC = K;
1841 return true;
1842 }
1843 return false;
1844 },
1845 NewLevel))
1846 break;
1847 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1848 D, NewLevel,
1849 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1850 OpenMPClauseKind) { return true; })) {
1851 OMPC = OMPC_map;
1852 break;
1853 }
1854 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1855 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001856 OMPC = OMPC_map;
1857 if (D->getType()->isScalarType() &&
1858 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1859 DefaultMapAttributes::DMA_tofrom_scalar)
1860 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001861 break;
1862 }
1863 }
1864 if (OMPC != OMPC_unknown)
1865 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1866}
1867
Alexey Bataeve3727102018-04-18 15:57:46 +00001868bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1869 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00001870 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1871 // Return true if the current level is no longer enclosed in a target region.
1872
Alexey Bataeve3727102018-04-18 15:57:46 +00001873 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001874 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001875 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1876 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001877}
1878
Alexey Bataeved09d242014-05-28 05:53:51 +00001879void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001880
1881void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1882 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001883 Scope *CurScope, SourceLocation Loc) {
1884 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001885 PushExpressionEvaluationContext(
1886 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001887}
1888
Alexey Bataevaac108a2015-06-23 04:51:00 +00001889void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1890 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001891}
1892
Alexey Bataevaac108a2015-06-23 04:51:00 +00001893void Sema::EndOpenMPClause() {
1894 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001895}
1896
Alexey Bataeve106f252019-04-01 14:25:31 +00001897static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
1898 ArrayRef<OMPClause *> Clauses);
1899
Alexey Bataev758e55e2013-09-06 18:03:48 +00001900void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001901 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1902 // A variable of class type (or array thereof) that appears in a lastprivate
1903 // clause requires an accessible, unambiguous default constructor for the
1904 // class type, unless the list item is also specified in a firstprivate
1905 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001906 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1907 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001908 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1909 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00001910 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001911 if (DE->isValueDependent() || DE->isTypeDependent()) {
1912 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001913 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001914 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001915 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00001916 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00001917 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00001918 const DSAStackTy::DSAVarData DVar =
1919 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001920 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001921 // Generate helper private variable and initialize it with the
1922 // default value. The address of the original variable is replaced
1923 // by the address of the new private variable in CodeGen. This new
1924 // variable is not added to IdResolver, so the code in the OpenMP
1925 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00001926 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001927 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001928 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00001929 ActOnUninitializedDecl(VDPrivate);
Alexey Bataeve106f252019-04-01 14:25:31 +00001930 if (VDPrivate->isInvalidDecl()) {
1931 PrivateCopies.push_back(nullptr);
Alexey Bataev38e89532015-04-16 04:54:05 +00001932 continue;
Alexey Bataeve106f252019-04-01 14:25:31 +00001933 }
Alexey Bataev39f915b82015-05-08 10:41:21 +00001934 PrivateCopies.push_back(buildDeclRefExpr(
1935 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001936 } else {
1937 // The variable is also a firstprivate, so initialization sequence
1938 // for private copy is generated already.
1939 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001940 }
1941 }
Alexey Bataeve106f252019-04-01 14:25:31 +00001942 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001943 }
1944 }
Alexey Bataeve106f252019-04-01 14:25:31 +00001945 // Check allocate clauses.
1946 if (!CurContext->isDependentContext())
1947 checkAllocateClauses(*this, DSAStack, D->clauses());
Alexey Bataevf29276e2014-06-18 04:14:57 +00001948 }
1949
Alexey Bataev758e55e2013-09-06 18:03:48 +00001950 DSAStack->pop();
1951 DiscardCleanupsInEvaluationContext();
1952 PopExpressionEvaluationContext();
1953}
1954
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001955static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1956 Expr *NumIterations, Sema &SemaRef,
1957 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001958
Alexey Bataeva769e072013-03-22 06:34:35 +00001959namespace {
1960
Alexey Bataeve3727102018-04-18 15:57:46 +00001961class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001962private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001963 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001964
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001965public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001966 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001967 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001968 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00001969 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001970 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001971 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1972 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001973 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001974 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001975 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00001976
1977 std::unique_ptr<CorrectionCandidateCallback> clone() override {
1978 return llvm::make_unique<VarDeclFilterCCC>(*this);
1979 }
1980
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001981};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001982
Alexey Bataeve3727102018-04-18 15:57:46 +00001983class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001984private:
1985 Sema &SemaRef;
1986
1987public:
1988 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1989 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1990 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataev25ed0c02019-03-07 17:54:44 +00001991 if (ND && ((isa<VarDecl>(ND) && ND->getKind() == Decl::Var) ||
1992 isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001993 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1994 SemaRef.getCurScope());
1995 }
1996 return false;
1997 }
Bruno Ricci70ad3962019-03-25 17:08:51 +00001998
1999 std::unique_ptr<CorrectionCandidateCallback> clone() override {
2000 return llvm::make_unique<VarOrFuncDeclFilterCCC>(*this);
2001 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +00002002};
2003
Alexey Bataeved09d242014-05-28 05:53:51 +00002004} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002005
2006ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
2007 CXXScopeSpec &ScopeSpec,
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002008 const DeclarationNameInfo &Id,
2009 OpenMPDirectiveKind Kind) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002010 LookupResult Lookup(*this, Id, LookupOrdinaryName);
2011 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
2012
2013 if (Lookup.isAmbiguous())
2014 return ExprError();
2015
2016 VarDecl *VD;
2017 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +00002018 VarDeclFilterCCC CCC(*this);
2019 if (TypoCorrection Corrected =
2020 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
2021 CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00002022 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002023 PDiag(Lookup.empty()
2024 ? diag::err_undeclared_var_use_suggest
2025 : diag::err_omp_expected_var_arg_suggest)
2026 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00002027 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002028 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00002029 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
2030 : diag::err_omp_expected_var_arg)
2031 << Id.getName();
2032 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002033 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002034 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
2035 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
2036 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
2037 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002038 }
2039 Lookup.suppressDiagnostics();
2040
2041 // OpenMP [2.9.2, Syntax, C/C++]
2042 // Variables must be file-scope, namespace-scope, or static block-scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002043 if (Kind == OMPD_threadprivate && !VD->hasGlobalStorage()) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002044 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002045 << getOpenMPDirectiveName(Kind) << !VD->isStaticLocal();
Alexey Bataeved09d242014-05-28 05:53:51 +00002046 bool IsDecl =
2047 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002048 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00002049 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2050 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002051 return ExprError();
2052 }
2053
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002054 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00002055 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002056 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
2057 // A threadprivate directive for file-scope variables must appear outside
2058 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002059 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
2060 !getCurLexicalContext()->isTranslationUnit()) {
2061 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002062 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002063 bool IsDecl =
2064 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2065 Diag(VD->getLocation(),
2066 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2067 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002068 return ExprError();
2069 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002070 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
2071 // A threadprivate directive for static class member variables must appear
2072 // in the class definition, in the same scope in which the member
2073 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002074 if (CanonicalVD->isStaticDataMember() &&
2075 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
2076 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002077 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002078 bool IsDecl =
2079 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2080 Diag(VD->getLocation(),
2081 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2082 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002083 return ExprError();
2084 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002085 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
2086 // A threadprivate directive for namespace-scope variables must appear
2087 // outside any definition or declaration other than the namespace
2088 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002089 if (CanonicalVD->getDeclContext()->isNamespace() &&
2090 (!getCurLexicalContext()->isFileContext() ||
2091 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
2092 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002093 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002094 bool IsDecl =
2095 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2096 Diag(VD->getLocation(),
2097 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2098 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002099 return ExprError();
2100 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002101 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
2102 // A threadprivate directive for static block-scope variables must appear
2103 // in the scope of the variable and not in a nested scope.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002104 if (CanonicalVD->isLocalVarDecl() && CurScope &&
Alexey Bataev7d2960b2013-09-26 03:24:06 +00002105 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002106 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002107 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataeved09d242014-05-28 05:53:51 +00002108 bool IsDecl =
2109 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2110 Diag(VD->getLocation(),
2111 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2112 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002113 return ExprError();
2114 }
2115
2116 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
2117 // A threadprivate directive must lexically precede all references to any
2118 // of the variables in its list.
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002119 if (Kind == OMPD_threadprivate && VD->isUsed() &&
2120 !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002121 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002122 << getOpenMPDirectiveName(Kind) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002123 return ExprError();
2124 }
2125
2126 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00002127 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
2128 SourceLocation(), VD,
2129 /*RefersToEnclosingVariableOrCapture=*/false,
2130 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002131}
2132
Alexey Bataeved09d242014-05-28 05:53:51 +00002133Sema::DeclGroupPtrTy
2134Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
2135 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002136 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002137 CurContext->addDecl(D);
2138 return DeclGroupPtrTy::make(DeclGroupRef(D));
2139 }
David Blaikie0403cb12016-01-15 23:43:25 +00002140 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00002141}
2142
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002143namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002144class LocalVarRefChecker final
2145 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002146 Sema &SemaRef;
2147
2148public:
2149 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002150 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002151 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002152 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002153 diag::err_omp_local_var_in_threadprivate_init)
2154 << E->getSourceRange();
2155 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2156 << VD << VD->getSourceRange();
2157 return true;
2158 }
2159 }
2160 return false;
2161 }
2162 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002163 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002164 if (Child && Visit(Child))
2165 return true;
2166 }
2167 return false;
2168 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002169 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002170};
2171} // namespace
2172
Alexey Bataeved09d242014-05-28 05:53:51 +00002173OMPThreadPrivateDecl *
2174Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002175 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002176 for (Expr *RefExpr : VarList) {
2177 auto *DE = cast<DeclRefExpr>(RefExpr);
2178 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002179 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002180
Alexey Bataev376b4a42016-02-09 09:41:09 +00002181 // Mark variable as used.
2182 VD->setReferenced();
2183 VD->markUsed(Context);
2184
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002185 QualType QType = VD->getType();
2186 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2187 // It will be analyzed later.
2188 Vars.push_back(DE);
2189 continue;
2190 }
2191
Alexey Bataeva769e072013-03-22 06:34:35 +00002192 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2193 // A threadprivate variable must not have an incomplete type.
2194 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002195 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002196 continue;
2197 }
2198
2199 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2200 // A threadprivate variable must not have a reference type.
2201 if (VD->getType()->isReferenceType()) {
2202 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002203 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2204 bool IsDecl =
2205 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2206 Diag(VD->getLocation(),
2207 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2208 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002209 continue;
2210 }
2211
Samuel Antaof8b50122015-07-13 22:54:53 +00002212 // Check if this is a TLS variable. If TLS is not being supported, produce
2213 // the corresponding diagnostic.
2214 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2215 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2216 getLangOpts().OpenMPUseTLS &&
2217 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002218 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2219 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002220 Diag(ILoc, diag::err_omp_var_thread_local)
2221 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002222 bool IsDecl =
2223 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2224 Diag(VD->getLocation(),
2225 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2226 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002227 continue;
2228 }
2229
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002230 // Check if initial value of threadprivate variable reference variable with
2231 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002232 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002233 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002234 if (Checker.Visit(Init))
2235 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002236 }
2237
Alexey Bataeved09d242014-05-28 05:53:51 +00002238 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002239 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002240 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2241 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002242 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002243 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002244 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002245 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002246 if (!Vars.empty()) {
2247 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2248 Vars);
2249 D->setAccess(AS_public);
2250 }
2251 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002252}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002253
Alexey Bataev27ef9512019-03-20 20:14:22 +00002254static OMPAllocateDeclAttr::AllocatorTypeTy
2255getAllocatorKind(Sema &S, DSAStackTy *Stack, Expr *Allocator) {
2256 if (!Allocator)
2257 return OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2258 if (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2259 Allocator->isInstantiationDependent() ||
Alexey Bataev441510e2019-03-21 19:05:07 +00002260 Allocator->containsUnexpandedParameterPack())
Alexey Bataev27ef9512019-03-20 20:14:22 +00002261 return OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataev27ef9512019-03-20 20:14:22 +00002262 auto AllocatorKindRes = OMPAllocateDeclAttr::OMPUserDefinedMemAlloc;
Alexey Bataeve106f252019-04-01 14:25:31 +00002263 const Expr *AE = Allocator->IgnoreParenImpCasts();
Alexey Bataev27ef9512019-03-20 20:14:22 +00002264 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
2265 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
2266 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
Alexey Bataeve106f252019-04-01 14:25:31 +00002267 const Expr *DefAllocator = Stack->getAllocator(AllocatorKind);
Alexey Bataev441510e2019-03-21 19:05:07 +00002268 llvm::FoldingSetNodeID AEId, DAEId;
2269 AE->Profile(AEId, S.getASTContext(), /*Canonical=*/true);
2270 DefAllocator->Profile(DAEId, S.getASTContext(), /*Canonical=*/true);
2271 if (AEId == DAEId) {
Alexey Bataev27ef9512019-03-20 20:14:22 +00002272 AllocatorKindRes = AllocatorKind;
2273 break;
2274 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002275 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002276 return AllocatorKindRes;
2277}
2278
Alexey Bataeve106f252019-04-01 14:25:31 +00002279static bool checkPreviousOMPAllocateAttribute(
2280 Sema &S, DSAStackTy *Stack, Expr *RefExpr, VarDecl *VD,
2281 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind, Expr *Allocator) {
2282 if (!VD->hasAttr<OMPAllocateDeclAttr>())
2283 return false;
2284 const auto *A = VD->getAttr<OMPAllocateDeclAttr>();
2285 Expr *PrevAllocator = A->getAllocator();
2286 OMPAllocateDeclAttr::AllocatorTypeTy PrevAllocatorKind =
2287 getAllocatorKind(S, Stack, PrevAllocator);
2288 bool AllocatorsMatch = AllocatorKind == PrevAllocatorKind;
2289 if (AllocatorsMatch &&
2290 AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc &&
2291 Allocator && PrevAllocator) {
2292 const Expr *AE = Allocator->IgnoreParenImpCasts();
2293 const Expr *PAE = PrevAllocator->IgnoreParenImpCasts();
2294 llvm::FoldingSetNodeID AEId, PAEId;
2295 AE->Profile(AEId, S.Context, /*Canonical=*/true);
2296 PAE->Profile(PAEId, S.Context, /*Canonical=*/true);
2297 AllocatorsMatch = AEId == PAEId;
2298 }
2299 if (!AllocatorsMatch) {
2300 SmallString<256> AllocatorBuffer;
2301 llvm::raw_svector_ostream AllocatorStream(AllocatorBuffer);
2302 if (Allocator)
2303 Allocator->printPretty(AllocatorStream, nullptr, S.getPrintingPolicy());
2304 SmallString<256> PrevAllocatorBuffer;
2305 llvm::raw_svector_ostream PrevAllocatorStream(PrevAllocatorBuffer);
2306 if (PrevAllocator)
2307 PrevAllocator->printPretty(PrevAllocatorStream, nullptr,
2308 S.getPrintingPolicy());
2309
2310 SourceLocation AllocatorLoc =
2311 Allocator ? Allocator->getExprLoc() : RefExpr->getExprLoc();
2312 SourceRange AllocatorRange =
2313 Allocator ? Allocator->getSourceRange() : RefExpr->getSourceRange();
2314 SourceLocation PrevAllocatorLoc =
2315 PrevAllocator ? PrevAllocator->getExprLoc() : A->getLocation();
2316 SourceRange PrevAllocatorRange =
2317 PrevAllocator ? PrevAllocator->getSourceRange() : A->getRange();
2318 S.Diag(AllocatorLoc, diag::warn_omp_used_different_allocator)
2319 << (Allocator ? 1 : 0) << AllocatorStream.str()
2320 << (PrevAllocator ? 1 : 0) << PrevAllocatorStream.str()
2321 << AllocatorRange;
2322 S.Diag(PrevAllocatorLoc, diag::note_omp_previous_allocator)
2323 << PrevAllocatorRange;
2324 return true;
2325 }
2326 return false;
2327}
2328
2329static void
2330applyOMPAllocateAttribute(Sema &S, VarDecl *VD,
2331 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind,
2332 Expr *Allocator, SourceRange SR) {
2333 if (VD->hasAttr<OMPAllocateDeclAttr>())
2334 return;
2335 if (Allocator &&
2336 (Allocator->isTypeDependent() || Allocator->isValueDependent() ||
2337 Allocator->isInstantiationDependent() ||
2338 Allocator->containsUnexpandedParameterPack()))
2339 return;
2340 auto *A = OMPAllocateDeclAttr::CreateImplicit(S.Context, AllocatorKind,
2341 Allocator, SR);
2342 VD->addAttr(A);
2343 if (ASTMutationListener *ML = S.Context.getASTMutationListener())
2344 ML->DeclarationMarkedOpenMPAllocate(VD, A);
2345}
2346
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002347Sema::DeclGroupPtrTy Sema::ActOnOpenMPAllocateDirective(
2348 SourceLocation Loc, ArrayRef<Expr *> VarList,
2349 ArrayRef<OMPClause *> Clauses, DeclContext *Owner) {
2350 assert(Clauses.size() <= 1 && "Expected at most one clause.");
2351 Expr *Allocator = nullptr;
Alexey Bataev2213dd62019-03-22 14:41:39 +00002352 if (Clauses.empty()) {
Alexey Bataevf4936072019-03-22 15:32:02 +00002353 // OpenMP 5.0, 2.11.3 allocate Directive, Restrictions.
2354 // allocate directives that appear in a target region must specify an
2355 // allocator clause unless a requires directive with the dynamic_allocators
2356 // clause is present in the same compilation unit.
Alexey Bataev318f431b2019-03-22 15:25:12 +00002357 if (LangOpts.OpenMPIsDevice &&
2358 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
Alexey Bataev2213dd62019-03-22 14:41:39 +00002359 targetDiag(Loc, diag::err_expected_allocator_clause);
2360 } else {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00002361 Allocator = cast<OMPAllocatorClause>(Clauses.back())->getAllocator();
Alexey Bataev2213dd62019-03-22 14:41:39 +00002362 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00002363 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
2364 getAllocatorKind(*this, DSAStack, Allocator);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002365 SmallVector<Expr *, 8> Vars;
2366 for (Expr *RefExpr : VarList) {
2367 auto *DE = cast<DeclRefExpr>(RefExpr);
2368 auto *VD = cast<VarDecl>(DE->getDecl());
2369
2370 // Check if this is a TLS variable or global register.
2371 if (VD->getTLSKind() != VarDecl::TLS_None ||
2372 VD->hasAttr<OMPThreadPrivateDeclAttr>() ||
2373 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2374 !VD->isLocalVarDecl()))
2375 continue;
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002376
Alexey Bataev282555a2019-03-19 20:33:44 +00002377 // If the used several times in the allocate directive, the same allocator
2378 // must be used.
Alexey Bataeve106f252019-04-01 14:25:31 +00002379 if (checkPreviousOMPAllocateAttribute(*this, DSAStack, RefExpr, VD,
2380 AllocatorKind, Allocator))
2381 continue;
Alexey Bataev282555a2019-03-19 20:33:44 +00002382
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002383 // OpenMP, 2.11.3 allocate Directive, Restrictions, C / C++
2384 // If a list item has a static storage type, the allocator expression in the
2385 // allocator clause must be a constant expression that evaluates to one of
2386 // the predefined memory allocator values.
2387 if (Allocator && VD->hasGlobalStorage()) {
Alexey Bataev441510e2019-03-21 19:05:07 +00002388 if (AllocatorKind == OMPAllocateDeclAttr::OMPUserDefinedMemAlloc) {
Alexey Bataevd2fc9652019-03-19 18:39:11 +00002389 Diag(Allocator->getExprLoc(),
2390 diag::err_omp_expected_predefined_allocator)
2391 << Allocator->getSourceRange();
2392 bool IsDecl = VD->isThisDeclarationADefinition(Context) ==
2393 VarDecl::DeclarationOnly;
2394 Diag(VD->getLocation(),
2395 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2396 << VD;
2397 continue;
2398 }
2399 }
2400
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002401 Vars.push_back(RefExpr);
Alexey Bataeve106f252019-04-01 14:25:31 +00002402 applyOMPAllocateAttribute(*this, VD, AllocatorKind, Allocator,
2403 DE->getSourceRange());
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002404 }
2405 if (Vars.empty())
2406 return nullptr;
2407 if (!Owner)
2408 Owner = getCurLexicalContext();
Alexey Bataeve106f252019-04-01 14:25:31 +00002409 auto *D = OMPAllocateDecl::Create(Context, Owner, Loc, Vars, Clauses);
Alexey Bataev25ed0c02019-03-07 17:54:44 +00002410 D->setAccess(AS_public);
2411 Owner->addDecl(D);
2412 return DeclGroupPtrTy::make(DeclGroupRef(D));
2413}
2414
2415Sema::DeclGroupPtrTy
Kelvin Li1408f912018-09-26 04:28:39 +00002416Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2417 ArrayRef<OMPClause *> ClauseList) {
2418 OMPRequiresDecl *D = nullptr;
2419 if (!CurContext->isFileContext()) {
2420 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2421 } else {
2422 D = CheckOMPRequiresDecl(Loc, ClauseList);
2423 if (D) {
2424 CurContext->addDecl(D);
2425 DSAStack->addRequiresDecl(D);
2426 }
2427 }
2428 return DeclGroupPtrTy::make(DeclGroupRef(D));
2429}
2430
2431OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2432 ArrayRef<OMPClause *> ClauseList) {
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00002433 /// For target specific clauses, the requires directive cannot be
2434 /// specified after the handling of any of the target regions in the
2435 /// current compilation unit.
2436 ArrayRef<SourceLocation> TargetLocations =
2437 DSAStack->getEncounteredTargetLocs();
2438 if (!TargetLocations.empty()) {
2439 for (const OMPClause *CNew : ClauseList) {
2440 // Check if any of the requires clauses affect target regions.
2441 if (isa<OMPUnifiedSharedMemoryClause>(CNew) ||
2442 isa<OMPUnifiedAddressClause>(CNew) ||
2443 isa<OMPReverseOffloadClause>(CNew) ||
2444 isa<OMPDynamicAllocatorsClause>(CNew)) {
2445 Diag(Loc, diag::err_omp_target_before_requires)
2446 << getOpenMPClauseName(CNew->getClauseKind());
2447 for (SourceLocation TargetLoc : TargetLocations) {
2448 Diag(TargetLoc, diag::note_omp_requires_encountered_target);
2449 }
2450 }
2451 }
2452 }
2453
Kelvin Li1408f912018-09-26 04:28:39 +00002454 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2455 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2456 ClauseList);
2457 return nullptr;
2458}
2459
Alexey Bataeve3727102018-04-18 15:57:46 +00002460static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2461 const ValueDecl *D,
2462 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002463 bool IsLoopIterVar = false) {
2464 if (DVar.RefExpr) {
2465 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2466 << getOpenMPClauseName(DVar.CKind);
2467 return;
2468 }
2469 enum {
2470 PDSA_StaticMemberShared,
2471 PDSA_StaticLocalVarShared,
2472 PDSA_LoopIterVarPrivate,
2473 PDSA_LoopIterVarLinear,
2474 PDSA_LoopIterVarLastprivate,
2475 PDSA_ConstVarShared,
2476 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002477 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002478 PDSA_LocalVarPrivate,
2479 PDSA_Implicit
2480 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002481 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002482 auto ReportLoc = D->getLocation();
2483 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002484 if (IsLoopIterVar) {
2485 if (DVar.CKind == OMPC_private)
2486 Reason = PDSA_LoopIterVarPrivate;
2487 else if (DVar.CKind == OMPC_lastprivate)
2488 Reason = PDSA_LoopIterVarLastprivate;
2489 else
2490 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002491 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2492 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002493 Reason = PDSA_TaskVarFirstprivate;
2494 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002495 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002496 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002497 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002498 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002499 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002500 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002501 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002502 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002503 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002504 ReportHint = true;
2505 Reason = PDSA_LocalVarPrivate;
2506 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002507 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002508 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002509 << Reason << ReportHint
2510 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2511 } else if (DVar.ImplicitDSALoc.isValid()) {
2512 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2513 << getOpenMPClauseName(DVar.CKind);
2514 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002515}
2516
Alexey Bataev758e55e2013-09-06 18:03:48 +00002517namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002518class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002519 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002520 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002521 bool ErrorFound = false;
2522 CapturedStmt *CS = nullptr;
2523 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2524 llvm::SmallVector<Expr *, 4> ImplicitMap;
2525 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2526 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002527
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002528 void VisitSubCaptures(OMPExecutableDirective *S) {
2529 // Check implicitly captured variables.
2530 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2531 return;
2532 for (const CapturedStmt::Capture &Cap :
2533 S->getInnermostCapturedStmt()->captures()) {
2534 if (!Cap.capturesVariable())
2535 continue;
2536 VarDecl *VD = Cap.getCapturedVar();
2537 // Do not try to map the variable if it or its sub-component was mapped
2538 // already.
2539 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2540 Stack->checkMappableExprComponentListsForDecl(
2541 VD, /*CurrentRegionOnly=*/true,
2542 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2543 OpenMPClauseKind) { return true; }))
2544 continue;
2545 DeclRefExpr *DRE = buildDeclRefExpr(
2546 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2547 Cap.getLocation(), /*RefersToCapture=*/true);
2548 Visit(DRE);
2549 }
2550 }
2551
Alexey Bataev758e55e2013-09-06 18:03:48 +00002552public:
2553 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002554 if (E->isTypeDependent() || E->isValueDependent() ||
2555 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2556 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002557 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002558 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002559 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002560 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002561 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002562
Alexey Bataeve3727102018-04-18 15:57:46 +00002563 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002564 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002565 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002566 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002567
Alexey Bataevafe50572017-10-06 17:00:28 +00002568 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002569 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002570 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002571 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2572 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002573 return;
2574
Alexey Bataeve3727102018-04-18 15:57:46 +00002575 SourceLocation ELoc = E->getExprLoc();
2576 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002577 // The default(none) clause requires that each variable that is referenced
2578 // in the construct, and does not have a predetermined data-sharing
2579 // attribute, must have its data-sharing attribute explicitly determined
2580 // by being listed in a data-sharing attribute clause.
2581 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002582 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002583 VarsWithInheritedDSA.count(VD) == 0) {
2584 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002585 return;
2586 }
2587
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002588 if (isOpenMPTargetExecutionDirective(DKind) &&
2589 !Stack->isLoopControlVariable(VD).first) {
2590 if (!Stack->checkMappableExprComponentListsForDecl(
2591 VD, /*CurrentRegionOnly=*/true,
2592 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2593 StackComponents,
2594 OpenMPClauseKind) {
2595 // Variable is used if it has been marked as an array, array
2596 // section or the variable iself.
2597 return StackComponents.size() == 1 ||
2598 std::all_of(
2599 std::next(StackComponents.rbegin()),
2600 StackComponents.rend(),
2601 [](const OMPClauseMappableExprCommon::
2602 MappableComponent &MC) {
2603 return MC.getAssociatedDeclaration() ==
2604 nullptr &&
2605 (isa<OMPArraySectionExpr>(
2606 MC.getAssociatedExpression()) ||
2607 isa<ArraySubscriptExpr>(
2608 MC.getAssociatedExpression()));
2609 });
2610 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002611 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002612 // By default lambdas are captured as firstprivates.
2613 if (const auto *RD =
2614 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002615 IsFirstprivate = RD->isLambda();
2616 IsFirstprivate =
2617 IsFirstprivate ||
2618 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002619 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002620 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002621 ImplicitFirstprivate.emplace_back(E);
2622 else
2623 ImplicitMap.emplace_back(E);
2624 return;
2625 }
2626 }
2627
Alexey Bataev758e55e2013-09-06 18:03:48 +00002628 // OpenMP [2.9.3.6, Restrictions, p.2]
2629 // A list item that appears in a reduction clause of the innermost
2630 // enclosing worksharing or parallel construct may not be accessed in an
2631 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002632 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002633 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2634 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002635 return isOpenMPParallelDirective(K) ||
2636 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2637 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002638 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002639 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002640 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002641 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002642 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002643 return;
2644 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002645
2646 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002647 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002648 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataeva495c642019-03-11 19:51:42 +00002649 !Stack->isLoopControlVariable(VD).first) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002650 ImplicitFirstprivate.push_back(E);
Alexey Bataeva495c642019-03-11 19:51:42 +00002651 return;
2652 }
2653
2654 // Store implicitly used globals with declare target link for parent
2655 // target.
2656 if (!isOpenMPTargetExecutionDirective(DKind) && Res &&
2657 *Res == OMPDeclareTargetDeclAttr::MT_Link) {
2658 Stack->addToParentTargetRegionLinkGlobals(E);
2659 return;
2660 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002661 }
2662 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002663 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002664 if (E->isTypeDependent() || E->isValueDependent() ||
2665 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2666 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002667 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002668 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002669 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002670 if (!FD)
2671 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002672 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002673 // Check if the variable has explicit DSA set and stop analysis if it
2674 // so.
2675 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2676 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002677
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002678 if (isOpenMPTargetExecutionDirective(DKind) &&
2679 !Stack->isLoopControlVariable(FD).first &&
2680 !Stack->checkMappableExprComponentListsForDecl(
2681 FD, /*CurrentRegionOnly=*/true,
2682 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2683 StackComponents,
2684 OpenMPClauseKind) {
2685 return isa<CXXThisExpr>(
2686 cast<MemberExpr>(
2687 StackComponents.back().getAssociatedExpression())
2688 ->getBase()
2689 ->IgnoreParens());
2690 })) {
2691 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2692 // A bit-field cannot appear in a map clause.
2693 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002694 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002695 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002696
2697 // Check to see if the member expression is referencing a class that
2698 // has already been explicitly mapped
2699 if (Stack->isClassPreviouslyMapped(TE->getType()))
2700 return;
2701
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002702 ImplicitMap.emplace_back(E);
2703 return;
2704 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002705
Alexey Bataeve3727102018-04-18 15:57:46 +00002706 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002707 // OpenMP [2.9.3.6, Restrictions, p.2]
2708 // A list item that appears in a reduction clause of the innermost
2709 // enclosing worksharing or parallel construct may not be accessed in
2710 // an explicit task.
2711 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002712 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2713 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002714 return isOpenMPParallelDirective(K) ||
2715 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2716 },
2717 /*FromParent=*/true);
2718 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2719 ErrorFound = true;
2720 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002721 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002722 return;
2723 }
2724
2725 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002726 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002727 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002728 !Stack->isLoopControlVariable(FD).first) {
2729 // Check if there is a captured expression for the current field in the
2730 // region. Do not mark it as firstprivate unless there is no captured
2731 // expression.
2732 // TODO: try to make it firstprivate.
2733 if (DVar.CKind != OMPC_unknown)
2734 ImplicitFirstprivate.push_back(E);
2735 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002736 return;
2737 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002738 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002739 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002740 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002741 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002742 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002743 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002744 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2745 if (!Stack->checkMappableExprComponentListsForDecl(
2746 VD, /*CurrentRegionOnly=*/true,
2747 [&CurComponents](
2748 OMPClauseMappableExprCommon::MappableExprComponentListRef
2749 StackComponents,
2750 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002751 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002752 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002753 for (const auto &SC : llvm::reverse(StackComponents)) {
2754 // Do both expressions have the same kind?
2755 if (CCI->getAssociatedExpression()->getStmtClass() !=
2756 SC.getAssociatedExpression()->getStmtClass())
2757 if (!(isa<OMPArraySectionExpr>(
2758 SC.getAssociatedExpression()) &&
2759 isa<ArraySubscriptExpr>(
2760 CCI->getAssociatedExpression())))
2761 return false;
2762
Alexey Bataeve3727102018-04-18 15:57:46 +00002763 const Decl *CCD = CCI->getAssociatedDeclaration();
2764 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002765 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2766 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2767 if (SCD != CCD)
2768 return false;
2769 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002770 if (CCI == CCE)
2771 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002772 }
2773 return true;
2774 })) {
2775 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002776 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002777 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002778 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00002779 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002780 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002781 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002782 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002783 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002784 // for task|target directives.
2785 // Skip analysis of arguments of implicitly defined map clause for target
2786 // directives.
2787 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2788 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002789 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002790 if (CC)
2791 Visit(CC);
2792 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002793 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002794 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00002795 // Check implicitly captured variables.
2796 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002797 }
2798 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002799 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002800 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00002801 // Check implicitly captured variables in the task-based directives to
2802 // check if they must be firstprivatized.
2803 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002804 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002805 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002806 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002807
Alexey Bataeve3727102018-04-18 15:57:46 +00002808 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002809 ArrayRef<Expr *> getImplicitFirstprivate() const {
2810 return ImplicitFirstprivate;
2811 }
2812 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00002813 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002814 return VarsWithInheritedDSA;
2815 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002816
Alexey Bataev7ff55242014-06-19 09:13:45 +00002817 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
Alexey Bataeva495c642019-03-11 19:51:42 +00002818 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {
2819 // Process declare target link variables for the target directives.
2820 if (isOpenMPTargetExecutionDirective(S->getCurrentDirective())) {
2821 for (DeclRefExpr *E : Stack->getLinkGlobals())
2822 Visit(E);
2823 }
2824 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002825};
Alexey Bataeved09d242014-05-28 05:53:51 +00002826} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002827
Alexey Bataevbae9a792014-06-27 10:37:06 +00002828void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002829 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002830 case OMPD_parallel:
2831 case OMPD_parallel_for:
2832 case OMPD_parallel_for_simd:
2833 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002834 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002835 case OMPD_teams_distribute:
2836 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002837 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002838 QualType KmpInt32PtrTy =
2839 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002840 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002841 std::make_pair(".global_tid.", KmpInt32PtrTy),
2842 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2843 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002844 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002845 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2846 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002847 break;
2848 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002849 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002850 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002851 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002852 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002853 case OMPD_target_teams_distribute:
2854 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002855 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2856 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2857 QualType KmpInt32PtrTy =
2858 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2859 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002860 FunctionProtoType::ExtProtoInfo EPI;
2861 EPI.Variadic = true;
2862 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2863 Sema::CapturedParamNameType Params[] = {
2864 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002865 std::make_pair(".part_id.", KmpInt32PtrTy),
2866 std::make_pair(".privates.", VoidPtrTy),
2867 std::make_pair(
2868 ".copy_fn.",
2869 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002870 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2871 std::make_pair(StringRef(), QualType()) // __context with shared vars
2872 };
2873 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2874 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002875 // Mark this captured region as inlined, because we don't use outlined
2876 // function directly.
2877 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2878 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002879 Context, AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002880 Sema::CapturedParamNameType ParamsTarget[] = {
2881 std::make_pair(StringRef(), QualType()) // __context with shared vars
2882 };
2883 // Start a captured region for 'target' with no implicit parameters.
2884 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2885 ParamsTarget);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002886 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002887 std::make_pair(".global_tid.", KmpInt32PtrTy),
2888 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2889 std::make_pair(StringRef(), QualType()) // __context with shared vars
2890 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002891 // Start a captured region for 'teams' or 'parallel'. Both regions have
2892 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002893 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002894 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002895 break;
2896 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002897 case OMPD_target:
2898 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002899 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2900 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2901 QualType KmpInt32PtrTy =
2902 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2903 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002904 FunctionProtoType::ExtProtoInfo EPI;
2905 EPI.Variadic = true;
2906 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2907 Sema::CapturedParamNameType Params[] = {
2908 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002909 std::make_pair(".part_id.", KmpInt32PtrTy),
2910 std::make_pair(".privates.", VoidPtrTy),
2911 std::make_pair(
2912 ".copy_fn.",
2913 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002914 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2915 std::make_pair(StringRef(), QualType()) // __context with shared vars
2916 };
2917 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2918 Params);
2919 // Mark this captured region as inlined, because we don't use outlined
2920 // function directly.
2921 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2922 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002923 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00002924 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2925 std::make_pair(StringRef(), QualType()));
2926 break;
2927 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002928 case OMPD_simd:
2929 case OMPD_for:
2930 case OMPD_for_simd:
2931 case OMPD_sections:
2932 case OMPD_section:
2933 case OMPD_single:
2934 case OMPD_master:
2935 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002936 case OMPD_taskgroup:
2937 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002938 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002939 case OMPD_ordered:
2940 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002941 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002942 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002943 std::make_pair(StringRef(), QualType()) // __context with shared vars
2944 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002945 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2946 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002947 break;
2948 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002949 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002950 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2951 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2952 QualType KmpInt32PtrTy =
2953 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2954 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002955 FunctionProtoType::ExtProtoInfo EPI;
2956 EPI.Variadic = true;
2957 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002958 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002959 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002960 std::make_pair(".part_id.", KmpInt32PtrTy),
2961 std::make_pair(".privates.", VoidPtrTy),
2962 std::make_pair(
2963 ".copy_fn.",
2964 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002965 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002966 std::make_pair(StringRef(), QualType()) // __context with shared vars
2967 };
2968 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2969 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002970 // Mark this captured region as inlined, because we don't use outlined
2971 // function directly.
2972 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2973 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002974 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002975 break;
2976 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002977 case OMPD_taskloop:
2978 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002979 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002980 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2981 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002982 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002983 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2984 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002985 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002986 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2987 .withConst();
2988 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2989 QualType KmpInt32PtrTy =
2990 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2991 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00002992 FunctionProtoType::ExtProtoInfo EPI;
2993 EPI.Variadic = true;
2994 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002995 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002996 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002997 std::make_pair(".part_id.", KmpInt32PtrTy),
2998 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00002999 std::make_pair(
3000 ".copy_fn.",
3001 Context.getPointerType(CopyFnType).withConst().withRestrict()),
3002 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3003 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003004 std::make_pair(".ub.", KmpUInt64Ty),
3005 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00003006 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003007 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00003008 std::make_pair(StringRef(), QualType()) // __context with shared vars
3009 };
3010 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3011 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00003012 // Mark this captured region as inlined, because we don't use outlined
3013 // function directly.
3014 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3015 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003016 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00003017 break;
3018 }
Kelvin Li4a39add2016-07-05 05:00:15 +00003019 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00003020 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003021 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00003022 QualType KmpInt32PtrTy =
3023 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3024 Sema::CapturedParamNameType Params[] = {
3025 std::make_pair(".global_tid.", KmpInt32PtrTy),
3026 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003027 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3028 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00003029 std::make_pair(StringRef(), QualType()) // __context with shared vars
3030 };
3031 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3032 Params);
3033 break;
3034 }
Alexey Bataev647dd842018-01-15 20:59:40 +00003035 case OMPD_target_teams_distribute_parallel_for:
3036 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003037 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003038 QualType KmpInt32PtrTy =
3039 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003040 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00003041
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003042 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00003043 FunctionProtoType::ExtProtoInfo EPI;
3044 EPI.Variadic = true;
3045 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3046 Sema::CapturedParamNameType Params[] = {
3047 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003048 std::make_pair(".part_id.", KmpInt32PtrTy),
3049 std::make_pair(".privates.", VoidPtrTy),
3050 std::make_pair(
3051 ".copy_fn.",
3052 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00003053 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3054 std::make_pair(StringRef(), QualType()) // __context with shared vars
3055 };
3056 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3057 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00003058 // Mark this captured region as inlined, because we don't use outlined
3059 // function directly.
3060 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3061 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003062 Context, AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00003063 Sema::CapturedParamNameType ParamsTarget[] = {
3064 std::make_pair(StringRef(), QualType()) // __context with shared vars
3065 };
3066 // Start a captured region for 'target' with no implicit parameters.
3067 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3068 ParamsTarget);
3069
3070 Sema::CapturedParamNameType ParamsTeams[] = {
3071 std::make_pair(".global_tid.", KmpInt32PtrTy),
3072 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3073 std::make_pair(StringRef(), QualType()) // __context with shared vars
3074 };
3075 // Start a captured region for 'target' with no implicit parameters.
3076 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3077 ParamsTeams);
3078
3079 Sema::CapturedParamNameType ParamsParallel[] = {
3080 std::make_pair(".global_tid.", KmpInt32PtrTy),
3081 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003082 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3083 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00003084 std::make_pair(StringRef(), QualType()) // __context with shared vars
3085 };
3086 // Start a captured region for 'teams' or 'parallel'. Both regions have
3087 // the same implicit parameters.
3088 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3089 ParamsParallel);
3090 break;
3091 }
3092
Alexey Bataev46506272017-12-05 17:41:34 +00003093 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00003094 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003095 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00003096 QualType KmpInt32PtrTy =
3097 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3098
3099 Sema::CapturedParamNameType ParamsTeams[] = {
3100 std::make_pair(".global_tid.", KmpInt32PtrTy),
3101 std::make_pair(".bound_tid.", KmpInt32PtrTy),
3102 std::make_pair(StringRef(), QualType()) // __context with shared vars
3103 };
3104 // Start a captured region for 'target' with no implicit parameters.
3105 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3106 ParamsTeams);
3107
3108 Sema::CapturedParamNameType ParamsParallel[] = {
3109 std::make_pair(".global_tid.", KmpInt32PtrTy),
3110 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003111 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
3112 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00003113 std::make_pair(StringRef(), QualType()) // __context with shared vars
3114 };
3115 // Start a captured region for 'teams' or 'parallel'. Both regions have
3116 // the same implicit parameters.
3117 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3118 ParamsParallel);
3119 break;
3120 }
Alexey Bataev7828b252017-11-21 17:08:48 +00003121 case OMPD_target_update:
3122 case OMPD_target_enter_data:
3123 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003124 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
3125 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
3126 QualType KmpInt32PtrTy =
3127 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
3128 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00003129 FunctionProtoType::ExtProtoInfo EPI;
3130 EPI.Variadic = true;
3131 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
3132 Sema::CapturedParamNameType Params[] = {
3133 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003134 std::make_pair(".part_id.", KmpInt32PtrTy),
3135 std::make_pair(".privates.", VoidPtrTy),
3136 std::make_pair(
3137 ".copy_fn.",
3138 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00003139 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
3140 std::make_pair(StringRef(), QualType()) // __context with shared vars
3141 };
3142 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
3143 Params);
3144 // Mark this captured region as inlined, because we don't use outlined
3145 // function directly.
3146 getCurCapturedRegion()->TheCapturedDecl->addAttr(
3147 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00003148 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00003149 break;
3150 }
Alexey Bataev9959db52014-05-06 10:08:46 +00003151 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00003152 case OMPD_allocate:
Alexey Bataevee9af452014-11-21 11:33:46 +00003153 case OMPD_taskyield:
3154 case OMPD_barrier:
3155 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003156 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00003157 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00003158 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003159 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00003160 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003161 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003162 case OMPD_declare_target:
3163 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00003164 case OMPD_requires:
Alexey Bataev9959db52014-05-06 10:08:46 +00003165 llvm_unreachable("OpenMP Directive is not allowed");
3166 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00003167 llvm_unreachable("Unknown OpenMP directive");
3168 }
3169}
3170
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003171int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
3172 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3173 getOpenMPCaptureRegions(CaptureRegions, DKind);
3174 return CaptureRegions.size();
3175}
3176
Alexey Bataev3392d762016-02-16 11:18:12 +00003177static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00003178 Expr *CaptureExpr, bool WithInit,
3179 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003180 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00003181 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003182 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00003183 QualType Ty = Init->getType();
3184 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003185 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00003186 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003187 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00003188 Ty = C.getPointerType(Ty);
3189 ExprResult Res =
3190 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
3191 if (!Res.isUsable())
3192 return nullptr;
3193 Init = Res.get();
3194 }
Alexey Bataev61205072016-03-02 04:57:40 +00003195 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00003196 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00003197 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003198 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00003199 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00003200 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00003201 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00003202 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003203 return CED;
3204}
3205
Alexey Bataev61205072016-03-02 04:57:40 +00003206static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
3207 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003208 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00003209 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00003210 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00003211 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00003212 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
3213 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00003214 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00003215 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00003216}
3217
Alexey Bataev5a3af132016-03-29 08:58:54 +00003218static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003219 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00003220 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003221 OMPCapturedExprDecl *CD = buildCaptureDecl(
3222 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
3223 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003224 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
3225 CaptureExpr->getExprLoc());
3226 }
3227 ExprResult Res = Ref;
3228 if (!S.getLangOpts().CPlusPlus &&
3229 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003230 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00003231 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00003232 if (!Res.isUsable())
3233 return ExprError();
3234 }
3235 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00003236}
3237
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003238namespace {
3239// OpenMP directives parsed in this section are represented as a
3240// CapturedStatement with an associated statement. If a syntax error
3241// is detected during the parsing of the associated statement, the
3242// compiler must abort processing and close the CapturedStatement.
3243//
3244// Combined directives such as 'target parallel' have more than one
3245// nested CapturedStatements. This RAII ensures that we unwind out
3246// of all the nested CapturedStatements when an error is found.
3247class CaptureRegionUnwinderRAII {
3248private:
3249 Sema &S;
3250 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00003251 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003252
3253public:
3254 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
3255 OpenMPDirectiveKind DKind)
3256 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
3257 ~CaptureRegionUnwinderRAII() {
3258 if (ErrorFound) {
3259 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
3260 while (--ThisCaptureLevel >= 0)
3261 S.ActOnCapturedRegionError();
3262 }
3263 }
3264};
3265} // namespace
3266
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003267StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
3268 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003269 bool ErrorFound = false;
3270 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
3271 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003272 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003273 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003274 return StmtError();
3275 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003276
Alexey Bataev2ba67042017-11-28 21:11:44 +00003277 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
3278 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00003279 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00003280 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00003281 SmallVector<const OMPLinearClause *, 4> LCs;
3282 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00003283 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00003284 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003285 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
3286 Clause->getClauseKind() == OMPC_in_reduction) {
3287 // Capture taskgroup task_reduction descriptors inside the tasking regions
3288 // with the corresponding in_reduction items.
3289 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00003290 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003291 if (E)
3292 MarkDeclarationsReferencedInExpr(E);
3293 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00003294 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003295 Clause->getClauseKind() == OMPC_copyprivate ||
3296 (getLangOpts().OpenMPUseTLS &&
3297 getASTContext().getTargetInfo().isTLSSupported() &&
3298 Clause->getClauseKind() == OMPC_copyin)) {
3299 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00003300 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00003301 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003302 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00003303 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003304 }
3305 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00003306 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00003307 } else if (CaptureRegions.size() > 1 ||
3308 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003309 if (auto *C = OMPClauseWithPreInit::get(Clause))
3310 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00003311 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003312 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00003313 MarkDeclarationsReferencedInExpr(E);
3314 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003315 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003316 if (Clause->getClauseKind() == OMPC_schedule)
3317 SC = cast<OMPScheduleClause>(Clause);
3318 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00003319 OC = cast<OMPOrderedClause>(Clause);
3320 else if (Clause->getClauseKind() == OMPC_linear)
3321 LCs.push_back(cast<OMPLinearClause>(Clause));
3322 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003323 // OpenMP, 2.7.1 Loop Construct, Restrictions
3324 // The nonmonotonic modifier cannot be specified if an ordered clause is
3325 // specified.
3326 if (SC &&
3327 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
3328 SC->getSecondScheduleModifier() ==
3329 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
3330 OC) {
3331 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
3332 ? SC->getFirstScheduleModifierLoc()
3333 : SC->getSecondScheduleModifierLoc(),
3334 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003335 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00003336 ErrorFound = true;
3337 }
Alexey Bataev993d2802015-12-28 06:23:08 +00003338 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003339 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003340 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00003341 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00003342 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003343 ErrorFound = true;
3344 }
Alexey Bataev113438c2015-12-30 12:06:23 +00003345 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
3346 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
3347 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003348 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00003349 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3350 ErrorFound = true;
3351 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003352 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003353 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003354 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003355 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003356 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003357 // Mark all variables in private list clauses as used in inner region.
3358 // Required for proper codegen of combined directives.
3359 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003360 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003361 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003362 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3363 // Find the particular capture region for the clause if the
3364 // directive is a combined one with multiple capture regions.
3365 // If the directive is not a combined one, the capture region
3366 // associated with the clause is OMPD_unknown and is generated
3367 // only once.
3368 if (CaptureRegion == ThisCaptureRegion ||
3369 CaptureRegion == OMPD_unknown) {
3370 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003371 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003372 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3373 }
3374 }
3375 }
3376 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003377 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003378 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003379 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003380}
3381
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003382static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3383 OpenMPDirectiveKind CancelRegion,
3384 SourceLocation StartLoc) {
3385 // CancelRegion is only needed for cancel and cancellation_point.
3386 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3387 return false;
3388
3389 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3390 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3391 return false;
3392
3393 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3394 << getOpenMPDirectiveName(CancelRegion);
3395 return true;
3396}
3397
Alexey Bataeve3727102018-04-18 15:57:46 +00003398static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003399 OpenMPDirectiveKind CurrentRegion,
3400 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003401 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003402 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003403 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003404 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3405 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003406 bool NestingProhibited = false;
3407 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003408 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003409 enum {
3410 NoRecommend,
3411 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003412 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003413 ShouldBeInTargetRegion,
3414 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003415 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003416 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003417 // OpenMP [2.16, Nesting of Regions]
3418 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003419 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003420 // An ordered construct with the simd clause is the only OpenMP
3421 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003422 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003423 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3424 // message.
3425 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3426 ? diag::err_omp_prohibited_region_simd
3427 : diag::warn_omp_nesting_simd);
3428 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003429 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003430 if (ParentRegion == OMPD_atomic) {
3431 // OpenMP [2.16, Nesting of Regions]
3432 // OpenMP constructs may not be nested inside an atomic region.
3433 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3434 return true;
3435 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003436 if (CurrentRegion == OMPD_section) {
3437 // OpenMP [2.7.2, sections Construct, Restrictions]
3438 // Orphaned section directives are prohibited. That is, the section
3439 // directives must appear within the sections construct and must not be
3440 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003441 if (ParentRegion != OMPD_sections &&
3442 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003443 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3444 << (ParentRegion != OMPD_unknown)
3445 << getOpenMPDirectiveName(ParentRegion);
3446 return true;
3447 }
3448 return false;
3449 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003450 // Allow some constructs (except teams and cancellation constructs) to be
3451 // orphaned (they could be used in functions, called from OpenMP regions
3452 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003453 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003454 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3455 CurrentRegion != OMPD_cancellation_point &&
3456 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003457 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003458 if (CurrentRegion == OMPD_cancellation_point ||
3459 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003460 // OpenMP [2.16, Nesting of Regions]
3461 // A cancellation point construct for which construct-type-clause is
3462 // taskgroup must be nested inside a task construct. A cancellation
3463 // point construct for which construct-type-clause is not taskgroup must
3464 // be closely nested inside an OpenMP construct that matches the type
3465 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003466 // A cancel construct for which construct-type-clause is taskgroup must be
3467 // nested inside a task construct. A cancel construct for which
3468 // construct-type-clause is not taskgroup must be closely nested inside an
3469 // OpenMP construct that matches the type specified in
3470 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003471 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003472 !((CancelRegion == OMPD_parallel &&
3473 (ParentRegion == OMPD_parallel ||
3474 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003475 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003476 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003477 ParentRegion == OMPD_target_parallel_for ||
3478 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003479 ParentRegion == OMPD_teams_distribute_parallel_for ||
3480 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003481 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3482 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003483 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3484 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003485 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003486 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003487 // OpenMP [2.16, Nesting of Regions]
3488 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003489 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003490 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003491 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003492 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3493 // OpenMP [2.16, Nesting of Regions]
3494 // A critical region may not be nested (closely or otherwise) inside a
3495 // critical region with the same name. Note that this restriction is not
3496 // sufficient to prevent deadlock.
3497 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003498 bool DeadLock = Stack->hasDirective(
3499 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3500 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003501 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003502 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3503 PreviousCriticalLoc = Loc;
3504 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003505 }
3506 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003507 },
3508 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003509 if (DeadLock) {
3510 SemaRef.Diag(StartLoc,
3511 diag::err_omp_prohibited_region_critical_same_name)
3512 << CurrentName.getName();
3513 if (PreviousCriticalLoc.isValid())
3514 SemaRef.Diag(PreviousCriticalLoc,
3515 diag::note_omp_previous_critical_region);
3516 return true;
3517 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003518 } else if (CurrentRegion == OMPD_barrier) {
3519 // OpenMP [2.16, Nesting of Regions]
3520 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003521 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003522 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3523 isOpenMPTaskingDirective(ParentRegion) ||
3524 ParentRegion == OMPD_master ||
3525 ParentRegion == OMPD_critical ||
3526 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003527 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003528 !isOpenMPParallelDirective(CurrentRegion) &&
3529 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003530 // OpenMP [2.16, Nesting of Regions]
3531 // A worksharing region may not be closely nested inside a worksharing,
3532 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003533 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3534 isOpenMPTaskingDirective(ParentRegion) ||
3535 ParentRegion == OMPD_master ||
3536 ParentRegion == OMPD_critical ||
3537 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003538 Recommend = ShouldBeInParallelRegion;
3539 } else if (CurrentRegion == OMPD_ordered) {
3540 // OpenMP [2.16, Nesting of Regions]
3541 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003542 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003543 // An ordered region must be closely nested inside a loop region (or
3544 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003545 // OpenMP [2.8.1,simd Construct, Restrictions]
3546 // An ordered construct with the simd clause is the only OpenMP construct
3547 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003548 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003549 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003550 !(isOpenMPSimdDirective(ParentRegion) ||
3551 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003552 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003553 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003554 // OpenMP [2.16, Nesting of Regions]
3555 // If specified, a teams construct must be contained within a target
3556 // construct.
3557 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00003558 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003559 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003560 }
Kelvin Libf594a52016-12-17 05:48:59 +00003561 if (!NestingProhibited &&
3562 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3563 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3564 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003565 // OpenMP [2.16, Nesting of Regions]
3566 // distribute, parallel, parallel sections, parallel workshare, and the
3567 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3568 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003569 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3570 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003571 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003572 }
David Majnemer9d168222016-08-05 17:44:54 +00003573 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003574 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003575 // OpenMP 4.5 [2.17 Nesting of Regions]
3576 // The region associated with the distribute construct must be strictly
3577 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003578 NestingProhibited =
3579 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003580 Recommend = ShouldBeInTeamsRegion;
3581 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003582 if (!NestingProhibited &&
3583 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3584 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3585 // OpenMP 4.5 [2.17 Nesting of Regions]
3586 // If a target, target update, target data, target enter data, or
3587 // target exit data construct is encountered during execution of a
3588 // target region, the behavior is unspecified.
3589 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003590 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003591 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003592 if (isOpenMPTargetExecutionDirective(K)) {
3593 OffendingRegion = K;
3594 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003595 }
3596 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003597 },
3598 false /* don't skip top directive */);
3599 CloseNesting = false;
3600 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003601 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003602 if (OrphanSeen) {
3603 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3604 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3605 } else {
3606 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3607 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3608 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3609 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003610 return true;
3611 }
3612 }
3613 return false;
3614}
3615
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003616static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3617 ArrayRef<OMPClause *> Clauses,
3618 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3619 bool ErrorFound = false;
3620 unsigned NamedModifiersNumber = 0;
3621 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3622 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003623 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003624 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003625 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3626 // At most one if clause without a directive-name-modifier can appear on
3627 // the directive.
3628 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3629 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003630 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003631 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3632 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3633 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003634 } else if (CurNM != OMPD_unknown) {
3635 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003636 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003637 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003638 FoundNameModifiers[CurNM] = IC;
3639 if (CurNM == OMPD_unknown)
3640 continue;
3641 // Check if the specified name modifier is allowed for the current
3642 // directive.
3643 // At most one if clause with the particular directive-name-modifier can
3644 // appear on the directive.
3645 bool MatchFound = false;
3646 for (auto NM : AllowedNameModifiers) {
3647 if (CurNM == NM) {
3648 MatchFound = true;
3649 break;
3650 }
3651 }
3652 if (!MatchFound) {
3653 S.Diag(IC->getNameModifierLoc(),
3654 diag::err_omp_wrong_if_directive_name_modifier)
3655 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3656 ErrorFound = true;
3657 }
3658 }
3659 }
3660 // If any if clause on the directive includes a directive-name-modifier then
3661 // all if clauses on the directive must include a directive-name-modifier.
3662 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3663 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003664 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003665 diag::err_omp_no_more_if_clause);
3666 } else {
3667 std::string Values;
3668 std::string Sep(", ");
3669 unsigned AllowedCnt = 0;
3670 unsigned TotalAllowedNum =
3671 AllowedNameModifiers.size() - NamedModifiersNumber;
3672 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3673 ++Cnt) {
3674 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3675 if (!FoundNameModifiers[NM]) {
3676 Values += "'";
3677 Values += getOpenMPDirectiveName(NM);
3678 Values += "'";
3679 if (AllowedCnt + 2 == TotalAllowedNum)
3680 Values += " or ";
3681 else if (AllowedCnt + 1 != TotalAllowedNum)
3682 Values += Sep;
3683 ++AllowedCnt;
3684 }
3685 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003686 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003687 diag::err_omp_unnamed_if_clause)
3688 << (TotalAllowedNum > 1) << Values;
3689 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003690 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00003691 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3692 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003693 ErrorFound = true;
3694 }
3695 return ErrorFound;
3696}
3697
Alexey Bataeve106f252019-04-01 14:25:31 +00003698static std::pair<ValueDecl *, bool>
3699getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
3700 SourceRange &ERange, bool AllowArraySection = false) {
3701 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
3702 RefExpr->containsUnexpandedParameterPack())
3703 return std::make_pair(nullptr, true);
3704
3705 // OpenMP [3.1, C/C++]
3706 // A list item is a variable name.
3707 // OpenMP [2.9.3.3, Restrictions, p.1]
3708 // A variable that is part of another variable (as an array or
3709 // structure element) cannot appear in a private clause.
3710 RefExpr = RefExpr->IgnoreParens();
3711 enum {
3712 NoArrayExpr = -1,
3713 ArraySubscript = 0,
3714 OMPArraySection = 1
3715 } IsArrayExpr = NoArrayExpr;
3716 if (AllowArraySection) {
3717 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
3718 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
3719 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
3720 Base = TempASE->getBase()->IgnoreParenImpCasts();
3721 RefExpr = Base;
3722 IsArrayExpr = ArraySubscript;
3723 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
3724 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
3725 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
3726 Base = TempOASE->getBase()->IgnoreParenImpCasts();
3727 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
3728 Base = TempASE->getBase()->IgnoreParenImpCasts();
3729 RefExpr = Base;
3730 IsArrayExpr = OMPArraySection;
3731 }
3732 }
3733 ELoc = RefExpr->getExprLoc();
3734 ERange = RefExpr->getSourceRange();
3735 RefExpr = RefExpr->IgnoreParenImpCasts();
3736 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
3737 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
3738 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
3739 (S.getCurrentThisType().isNull() || !ME ||
3740 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
3741 !isa<FieldDecl>(ME->getMemberDecl()))) {
3742 if (IsArrayExpr != NoArrayExpr) {
3743 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
3744 << ERange;
3745 } else {
3746 S.Diag(ELoc,
3747 AllowArraySection
3748 ? diag::err_omp_expected_var_name_member_expr_or_array_item
3749 : diag::err_omp_expected_var_name_member_expr)
3750 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
3751 }
3752 return std::make_pair(nullptr, false);
3753 }
3754 return std::make_pair(
3755 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
3756}
3757
3758static void checkAllocateClauses(Sema &S, DSAStackTy *Stack,
Alexey Bataev471171c2019-03-28 19:15:36 +00003759 ArrayRef<OMPClause *> Clauses) {
3760 assert(!S.CurContext->isDependentContext() &&
3761 "Expected non-dependent context.");
Alexey Bataev471171c2019-03-28 19:15:36 +00003762 auto AllocateRange =
3763 llvm::make_filter_range(Clauses, OMPAllocateClause::classof);
Alexey Bataeve106f252019-04-01 14:25:31 +00003764 llvm::DenseMap<CanonicalDeclPtr<Decl>, CanonicalDeclPtr<VarDecl>>
3765 DeclToCopy;
3766 auto PrivateRange = llvm::make_filter_range(Clauses, [](const OMPClause *C) {
3767 return isOpenMPPrivate(C->getClauseKind());
3768 });
3769 for (OMPClause *Cl : PrivateRange) {
3770 MutableArrayRef<Expr *>::iterator I, It, Et;
3771 if (Cl->getClauseKind() == OMPC_private) {
3772 auto *PC = cast<OMPPrivateClause>(Cl);
3773 I = PC->private_copies().begin();
3774 It = PC->varlist_begin();
3775 Et = PC->varlist_end();
3776 } else if (Cl->getClauseKind() == OMPC_firstprivate) {
3777 auto *PC = cast<OMPFirstprivateClause>(Cl);
3778 I = PC->private_copies().begin();
3779 It = PC->varlist_begin();
3780 Et = PC->varlist_end();
3781 } else if (Cl->getClauseKind() == OMPC_lastprivate) {
3782 auto *PC = cast<OMPLastprivateClause>(Cl);
3783 I = PC->private_copies().begin();
3784 It = PC->varlist_begin();
3785 Et = PC->varlist_end();
3786 } else if (Cl->getClauseKind() == OMPC_linear) {
3787 auto *PC = cast<OMPLinearClause>(Cl);
3788 I = PC->privates().begin();
3789 It = PC->varlist_begin();
3790 Et = PC->varlist_end();
3791 } else if (Cl->getClauseKind() == OMPC_reduction) {
3792 auto *PC = cast<OMPReductionClause>(Cl);
3793 I = PC->privates().begin();
3794 It = PC->varlist_begin();
3795 Et = PC->varlist_end();
3796 } else if (Cl->getClauseKind() == OMPC_task_reduction) {
3797 auto *PC = cast<OMPTaskReductionClause>(Cl);
3798 I = PC->privates().begin();
3799 It = PC->varlist_begin();
3800 Et = PC->varlist_end();
3801 } else if (Cl->getClauseKind() == OMPC_in_reduction) {
3802 auto *PC = cast<OMPInReductionClause>(Cl);
3803 I = PC->privates().begin();
3804 It = PC->varlist_begin();
3805 Et = PC->varlist_end();
3806 } else {
3807 llvm_unreachable("Expected private clause.");
3808 }
3809 for (Expr *E : llvm::make_range(It, Et)) {
3810 if (!*I) {
3811 ++I;
3812 continue;
3813 }
3814 SourceLocation ELoc;
3815 SourceRange ERange;
3816 Expr *SimpleRefExpr = E;
3817 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
3818 /*AllowArraySection=*/true);
3819 DeclToCopy.try_emplace(Res.first,
3820 cast<VarDecl>(cast<DeclRefExpr>(*I)->getDecl()));
3821 ++I;
3822 }
3823 }
Alexey Bataev471171c2019-03-28 19:15:36 +00003824 for (OMPClause *C : AllocateRange) {
3825 auto *AC = cast<OMPAllocateClause>(C);
3826 OMPAllocateDeclAttr::AllocatorTypeTy AllocatorKind =
3827 getAllocatorKind(S, Stack, AC->getAllocator());
3828 // OpenMP, 2.11.4 allocate Clause, Restrictions.
3829 // For task, taskloop or target directives, allocation requests to memory
3830 // allocators with the trait access set to thread result in unspecified
3831 // behavior.
3832 if (AllocatorKind == OMPAllocateDeclAttr::OMPThreadMemAlloc &&
3833 (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
3834 isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()))) {
3835 S.Diag(AC->getAllocator()->getExprLoc(),
3836 diag::warn_omp_allocate_thread_on_task_target_directive)
3837 << getOpenMPDirectiveName(Stack->getCurrentDirective());
Alexey Bataeve106f252019-04-01 14:25:31 +00003838 }
3839 for (Expr *E : AC->varlists()) {
3840 SourceLocation ELoc;
3841 SourceRange ERange;
3842 Expr *SimpleRefExpr = E;
3843 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange);
3844 ValueDecl *VD = Res.first;
3845 DSAStackTy::DSAVarData Data = Stack->getTopDSA(VD, /*FromParent=*/false);
3846 if (!isOpenMPPrivate(Data.CKind)) {
3847 S.Diag(E->getExprLoc(),
3848 diag::err_omp_expected_private_copy_for_allocate);
3849 continue;
3850 }
3851 VarDecl *PrivateVD = DeclToCopy[VD];
3852 if (checkPreviousOMPAllocateAttribute(S, Stack, E, PrivateVD,
3853 AllocatorKind, AC->getAllocator()))
3854 continue;
3855 applyOMPAllocateAttribute(S, PrivateVD, AllocatorKind, AC->getAllocator(),
3856 E->getSourceRange());
Alexey Bataev471171c2019-03-28 19:15:36 +00003857 }
3858 }
Alexey Bataev471171c2019-03-28 19:15:36 +00003859}
3860
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003861StmtResult Sema::ActOnOpenMPExecutableDirective(
3862 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3863 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3864 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003865 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003866 // First check CancelRegion which is then used in checkNestingOfRegions.
3867 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3868 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003869 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00003870 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003871
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003872 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00003873 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003874 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003875 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003876 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003877 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3878
3879 // Check default data sharing attributes for referenced variables.
3880 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003881 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3882 Stmt *S = AStmt;
3883 while (--ThisCaptureLevel >= 0)
3884 S = cast<CapturedStmt>(S)->getCapturedStmt();
3885 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003886 if (DSAChecker.isErrorFound())
3887 return StmtError();
3888 // Generate list of implicitly defined firstprivate variables.
3889 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003890
Alexey Bataev88202be2017-07-27 13:20:36 +00003891 SmallVector<Expr *, 4> ImplicitFirstprivates(
3892 DSAChecker.getImplicitFirstprivate().begin(),
3893 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003894 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3895 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003896 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00003897 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003898 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003899 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003900 if (E)
3901 ImplicitFirstprivates.emplace_back(E);
3902 }
3903 }
3904 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003905 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00003906 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3907 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003908 ClausesWithImplicit.push_back(Implicit);
3909 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00003910 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003911 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00003912 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003913 }
Alexey Bataev68446b72014-07-18 07:47:19 +00003914 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003915 if (!ImplicitMaps.empty()) {
Michael Kruse4304e9d2019-02-19 16:38:20 +00003916 CXXScopeSpec MapperIdScopeSpec;
3917 DeclarationNameInfo MapperId;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003918 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Michael Kruse4304e9d2019-02-19 16:38:20 +00003919 llvm::None, llvm::None, MapperIdScopeSpec, MapperId,
3920 OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true, SourceLocation(),
3921 SourceLocation(), ImplicitMaps, OMPVarListLocTy())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003922 ClausesWithImplicit.emplace_back(Implicit);
3923 ErrorFound |=
3924 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003925 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003926 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003927 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003928 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003929 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003930
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003931 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003932 switch (Kind) {
3933 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003934 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3935 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003936 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003937 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003938 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003939 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3940 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003941 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003942 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003943 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3944 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003945 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003946 case OMPD_for_simd:
3947 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3948 EndLoc, VarsWithInheritedDSA);
3949 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003950 case OMPD_sections:
3951 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3952 EndLoc);
3953 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003954 case OMPD_section:
3955 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003956 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003957 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3958 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003959 case OMPD_single:
3960 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3961 EndLoc);
3962 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003963 case OMPD_master:
3964 assert(ClausesWithImplicit.empty() &&
3965 "No clauses are allowed for 'omp master' directive");
3966 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3967 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003968 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003969 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3970 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003971 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003972 case OMPD_parallel_for:
3973 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3974 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003975 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003976 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003977 case OMPD_parallel_for_simd:
3978 Res = ActOnOpenMPParallelForSimdDirective(
3979 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003980 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003981 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003982 case OMPD_parallel_sections:
3983 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3984 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003985 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003986 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003987 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003988 Res =
3989 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003990 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003991 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003992 case OMPD_taskyield:
3993 assert(ClausesWithImplicit.empty() &&
3994 "No clauses are allowed for 'omp taskyield' directive");
3995 assert(AStmt == nullptr &&
3996 "No associated statement allowed for 'omp taskyield' directive");
3997 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3998 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003999 case OMPD_barrier:
4000 assert(ClausesWithImplicit.empty() &&
4001 "No clauses are allowed for 'omp barrier' directive");
4002 assert(AStmt == nullptr &&
4003 "No associated statement allowed for 'omp barrier' directive");
4004 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
4005 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00004006 case OMPD_taskwait:
4007 assert(ClausesWithImplicit.empty() &&
4008 "No clauses are allowed for 'omp taskwait' directive");
4009 assert(AStmt == nullptr &&
4010 "No associated statement allowed for 'omp taskwait' directive");
4011 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
4012 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004013 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00004014 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
4015 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00004016 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00004017 case OMPD_flush:
4018 assert(AStmt == nullptr &&
4019 "No associated statement allowed for 'omp flush' directive");
4020 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
4021 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004022 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00004023 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
4024 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00004025 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00004026 case OMPD_atomic:
4027 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
4028 EndLoc);
4029 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00004030 case OMPD_teams:
4031 Res =
4032 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
4033 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004034 case OMPD_target:
4035 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
4036 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004037 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00004038 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00004039 case OMPD_target_parallel:
4040 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
4041 StartLoc, EndLoc);
4042 AllowedNameModifiers.push_back(OMPD_target);
4043 AllowedNameModifiers.push_back(OMPD_parallel);
4044 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00004045 case OMPD_target_parallel_for:
4046 Res = ActOnOpenMPTargetParallelForDirective(
4047 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4048 AllowedNameModifiers.push_back(OMPD_target);
4049 AllowedNameModifiers.push_back(OMPD_parallel);
4050 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00004051 case OMPD_cancellation_point:
4052 assert(ClausesWithImplicit.empty() &&
4053 "No clauses are allowed for 'omp cancellation point' directive");
4054 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
4055 "cancellation point' directive");
4056 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
4057 break;
Alexey Bataev80909872015-07-02 11:25:17 +00004058 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00004059 assert(AStmt == nullptr &&
4060 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00004061 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
4062 CancelRegion);
4063 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00004064 break;
Michael Wong65f367f2015-07-21 13:44:28 +00004065 case OMPD_target_data:
4066 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
4067 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004068 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00004069 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00004070 case OMPD_target_enter_data:
4071 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004072 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00004073 AllowedNameModifiers.push_back(OMPD_target_enter_data);
4074 break;
Samuel Antao72590762016-01-19 20:04:50 +00004075 case OMPD_target_exit_data:
4076 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00004077 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00004078 AllowedNameModifiers.push_back(OMPD_target_exit_data);
4079 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00004080 case OMPD_taskloop:
4081 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
4082 EndLoc, VarsWithInheritedDSA);
4083 AllowedNameModifiers.push_back(OMPD_taskloop);
4084 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00004085 case OMPD_taskloop_simd:
4086 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4087 EndLoc, VarsWithInheritedDSA);
4088 AllowedNameModifiers.push_back(OMPD_taskloop);
4089 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004090 case OMPD_distribute:
4091 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
4092 EndLoc, VarsWithInheritedDSA);
4093 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00004094 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00004095 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
4096 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00004097 AllowedNameModifiers.push_back(OMPD_target_update);
4098 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00004099 case OMPD_distribute_parallel_for:
4100 Res = ActOnOpenMPDistributeParallelForDirective(
4101 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4102 AllowedNameModifiers.push_back(OMPD_parallel);
4103 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00004104 case OMPD_distribute_parallel_for_simd:
4105 Res = ActOnOpenMPDistributeParallelForSimdDirective(
4106 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4107 AllowedNameModifiers.push_back(OMPD_parallel);
4108 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00004109 case OMPD_distribute_simd:
4110 Res = ActOnOpenMPDistributeSimdDirective(
4111 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4112 break;
Kelvin Lia579b912016-07-14 02:54:56 +00004113 case OMPD_target_parallel_for_simd:
4114 Res = ActOnOpenMPTargetParallelForSimdDirective(
4115 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4116 AllowedNameModifiers.push_back(OMPD_target);
4117 AllowedNameModifiers.push_back(OMPD_parallel);
4118 break;
Kelvin Li986330c2016-07-20 22:57:10 +00004119 case OMPD_target_simd:
4120 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
4121 EndLoc, VarsWithInheritedDSA);
4122 AllowedNameModifiers.push_back(OMPD_target);
4123 break;
Kelvin Li02532872016-08-05 14:37:37 +00004124 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00004125 Res = ActOnOpenMPTeamsDistributeDirective(
4126 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00004127 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00004128 case OMPD_teams_distribute_simd:
4129 Res = ActOnOpenMPTeamsDistributeSimdDirective(
4130 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4131 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00004132 case OMPD_teams_distribute_parallel_for_simd:
4133 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
4134 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4135 AllowedNameModifiers.push_back(OMPD_parallel);
4136 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00004137 case OMPD_teams_distribute_parallel_for:
4138 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
4139 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4140 AllowedNameModifiers.push_back(OMPD_parallel);
4141 break;
Kelvin Libf594a52016-12-17 05:48:59 +00004142 case OMPD_target_teams:
4143 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
4144 EndLoc);
4145 AllowedNameModifiers.push_back(OMPD_target);
4146 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00004147 case OMPD_target_teams_distribute:
4148 Res = ActOnOpenMPTargetTeamsDistributeDirective(
4149 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4150 AllowedNameModifiers.push_back(OMPD_target);
4151 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00004152 case OMPD_target_teams_distribute_parallel_for:
4153 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
4154 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4155 AllowedNameModifiers.push_back(OMPD_target);
4156 AllowedNameModifiers.push_back(OMPD_parallel);
4157 break;
Kelvin Li1851df52017-01-03 05:23:48 +00004158 case OMPD_target_teams_distribute_parallel_for_simd:
4159 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
4160 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4161 AllowedNameModifiers.push_back(OMPD_target);
4162 AllowedNameModifiers.push_back(OMPD_parallel);
4163 break;
Kelvin Lida681182017-01-10 18:08:18 +00004164 case OMPD_target_teams_distribute_simd:
4165 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
4166 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
4167 AllowedNameModifiers.push_back(OMPD_target);
4168 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00004169 case OMPD_declare_target:
4170 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00004171 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00004172 case OMPD_allocate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00004173 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00004174 case OMPD_declare_mapper:
Alexey Bataev587e1de2016-03-30 10:43:55 +00004175 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00004176 case OMPD_requires:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004177 llvm_unreachable("OpenMP Directive is not allowed");
4178 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004179 llvm_unreachable("Unknown OpenMP directive");
4180 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00004181
Roman Lebedevb5700602019-03-20 16:32:36 +00004182 ErrorFound = Res.isInvalid() || ErrorFound;
4183
Alexey Bataeve3727102018-04-18 15:57:46 +00004184 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00004185 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
4186 << P.first << P.second->getSourceRange();
4187 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004188 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
4189
4190 if (!AllowedNameModifiers.empty())
4191 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
4192 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00004193
Alexey Bataeved09d242014-05-28 05:53:51 +00004194 if (ErrorFound)
4195 return StmtError();
Roman Lebedevb5700602019-03-20 16:32:36 +00004196
4197 if (!(Res.getAs<OMPExecutableDirective>()->isStandaloneDirective())) {
4198 Res.getAs<OMPExecutableDirective>()
4199 ->getStructuredBlock()
4200 ->setIsOMPStructuredBlock(true);
4201 }
4202
Gheorghe-Teodor Bercea411a6242019-04-18 19:53:43 +00004203 if (!CurContext->isDependentContext() &&
4204 isOpenMPTargetExecutionDirective(Kind) &&
4205 !(DSAStack->hasRequiresDeclWithClause<OMPUnifiedSharedMemoryClause>() ||
4206 DSAStack->hasRequiresDeclWithClause<OMPUnifiedAddressClause>() ||
4207 DSAStack->hasRequiresDeclWithClause<OMPReverseOffloadClause>() ||
4208 DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())) {
4209 // Register target to DSA Stack.
4210 DSAStack->addTargetDirLocation(StartLoc);
4211 }
4212
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004213 return Res;
4214}
4215
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004216Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
4217 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00004218 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00004219 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
4220 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004221 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00004222 assert(Linears.size() == LinModifiers.size());
4223 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00004224 if (!DG || DG.get().isNull())
4225 return DeclGroupPtrTy();
4226
4227 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00004228 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004229 return DG;
4230 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004231 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00004232 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
4233 ADecl = FTD->getTemplatedDecl();
4234
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004235 auto *FD = dyn_cast<FunctionDecl>(ADecl);
4236 if (!FD) {
4237 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004238 return DeclGroupPtrTy();
4239 }
4240
Alexey Bataev2af33e32016-04-07 12:45:37 +00004241 // OpenMP [2.8.2, declare simd construct, Description]
4242 // The parameter of the simdlen clause must be a constant positive integer
4243 // expression.
4244 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004245 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00004246 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004247 // OpenMP [2.8.2, declare simd construct, Description]
4248 // The special this pointer can be used as if was one of the arguments to the
4249 // function in any of the linear, aligned, or uniform clauses.
4250 // The uniform clause declares one or more arguments to have an invariant
4251 // value for all concurrent invocations of the function in the execution of a
4252 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00004253 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
4254 const Expr *UniformedLinearThis = nullptr;
4255 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004256 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004257 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4258 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004259 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4260 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00004261 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00004262 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004263 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004264 }
4265 if (isa<CXXThisExpr>(E)) {
4266 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004267 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004268 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004269 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4270 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00004271 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00004272 // OpenMP [2.8.2, declare simd construct, Description]
4273 // The aligned clause declares that the object to which each list item points
4274 // is aligned to the number of bytes expressed in the optional parameter of
4275 // the aligned clause.
4276 // The special this pointer can be used as if was one of the arguments to the
4277 // function in any of the linear, aligned, or uniform clauses.
4278 // The type of list items appearing in the aligned clause must be array,
4279 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004280 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
4281 const Expr *AlignedThis = nullptr;
4282 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004283 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004284 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4285 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4286 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00004287 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4288 FD->getParamDecl(PVD->getFunctionScopeIndex())
4289 ->getCanonicalDecl() == CanonPVD) {
4290 // OpenMP [2.8.1, simd construct, Restrictions]
4291 // A list-item cannot appear in more than one aligned clause.
4292 if (AlignedArgs.count(CanonPVD) > 0) {
4293 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4294 << 1 << E->getSourceRange();
4295 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
4296 diag::note_omp_explicit_dsa)
4297 << getOpenMPClauseName(OMPC_aligned);
4298 continue;
4299 }
4300 AlignedArgs[CanonPVD] = E;
4301 QualType QTy = PVD->getType()
4302 .getNonReferenceType()
4303 .getUnqualifiedType()
4304 .getCanonicalType();
4305 const Type *Ty = QTy.getTypePtrOrNull();
4306 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
4307 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
4308 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
4309 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
4310 }
4311 continue;
4312 }
4313 }
4314 if (isa<CXXThisExpr>(E)) {
4315 if (AlignedThis) {
4316 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
4317 << 2 << E->getSourceRange();
4318 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
4319 << getOpenMPClauseName(OMPC_aligned);
4320 }
4321 AlignedThis = E;
4322 continue;
4323 }
4324 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4325 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4326 }
4327 // The optional parameter of the aligned clause, alignment, must be a constant
4328 // positive integer expression. If no optional parameter is specified,
4329 // implementation-defined default alignments for SIMD instructions on the
4330 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00004331 SmallVector<const Expr *, 4> NewAligns;
4332 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00004333 ExprResult Align;
4334 if (E)
4335 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
4336 NewAligns.push_back(Align.get());
4337 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00004338 // OpenMP [2.8.2, declare simd construct, Description]
4339 // The linear clause declares one or more list items to be private to a SIMD
4340 // lane and to have a linear relationship with respect to the iteration space
4341 // of a loop.
4342 // The special this pointer can be used as if was one of the arguments to the
4343 // function in any of the linear, aligned, or uniform clauses.
4344 // When a linear-step expression is specified in a linear clause it must be
4345 // either a constant integer expression or an integer-typed parameter that is
4346 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00004347 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00004348 const bool IsUniformedThis = UniformedLinearThis != nullptr;
4349 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00004350 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004351 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
4352 ++MI;
4353 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004354 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
4355 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4356 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004357 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
4358 FD->getParamDecl(PVD->getFunctionScopeIndex())
4359 ->getCanonicalDecl() == CanonPVD) {
4360 // OpenMP [2.15.3.7, linear Clause, Restrictions]
4361 // A list-item cannot appear in more than one linear clause.
4362 if (LinearArgs.count(CanonPVD) > 0) {
4363 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4364 << getOpenMPClauseName(OMPC_linear)
4365 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
4366 Diag(LinearArgs[CanonPVD]->getExprLoc(),
4367 diag::note_omp_explicit_dsa)
4368 << getOpenMPClauseName(OMPC_linear);
4369 continue;
4370 }
4371 // Each argument can appear in at most one uniform or linear clause.
4372 if (UniformedArgs.count(CanonPVD) > 0) {
4373 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4374 << getOpenMPClauseName(OMPC_linear)
4375 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
4376 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
4377 diag::note_omp_explicit_dsa)
4378 << getOpenMPClauseName(OMPC_uniform);
4379 continue;
4380 }
4381 LinearArgs[CanonPVD] = E;
4382 if (E->isValueDependent() || E->isTypeDependent() ||
4383 E->isInstantiationDependent() ||
4384 E->containsUnexpandedParameterPack())
4385 continue;
4386 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
4387 PVD->getOriginalType());
4388 continue;
4389 }
4390 }
4391 if (isa<CXXThisExpr>(E)) {
4392 if (UniformedLinearThis) {
4393 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
4394 << getOpenMPClauseName(OMPC_linear)
4395 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
4396 << E->getSourceRange();
4397 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
4398 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
4399 : OMPC_linear);
4400 continue;
4401 }
4402 UniformedLinearThis = E;
4403 if (E->isValueDependent() || E->isTypeDependent() ||
4404 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
4405 continue;
4406 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
4407 E->getType());
4408 continue;
4409 }
4410 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
4411 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
4412 }
4413 Expr *Step = nullptr;
4414 Expr *NewStep = nullptr;
4415 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00004416 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004417 // Skip the same step expression, it was checked already.
4418 if (Step == E || !E) {
4419 NewSteps.push_back(E ? NewStep : nullptr);
4420 continue;
4421 }
4422 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00004423 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
4424 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
4425 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00004426 if (UniformedArgs.count(CanonPVD) == 0) {
4427 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
4428 << Step->getSourceRange();
4429 } else if (E->isValueDependent() || E->isTypeDependent() ||
4430 E->isInstantiationDependent() ||
4431 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00004432 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004433 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00004434 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00004435 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
4436 << Step->getSourceRange();
4437 }
4438 continue;
4439 }
4440 NewStep = Step;
4441 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
4442 !Step->isInstantiationDependent() &&
4443 !Step->containsUnexpandedParameterPack()) {
4444 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
4445 .get();
4446 if (NewStep)
4447 NewStep = VerifyIntegerConstantExpression(NewStep).get();
4448 }
4449 NewSteps.push_back(NewStep);
4450 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00004451 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
4452 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00004453 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00004454 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
4455 const_cast<Expr **>(Linears.data()), Linears.size(),
4456 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
4457 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00004458 ADecl->addAttr(NewAttr);
4459 return ConvertDeclToDeclGroup(ADecl);
4460}
4461
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004462StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
4463 Stmt *AStmt,
4464 SourceLocation StartLoc,
4465 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00004466 if (!AStmt)
4467 return StmtError();
4468
Alexey Bataeve3727102018-04-18 15:57:46 +00004469 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00004470 // 1.2.2 OpenMP Language Terminology
4471 // Structured block - An executable statement with a single entry at the
4472 // top and a single exit at the bottom.
4473 // The point of exit cannot be a branch out of the structured block.
4474 // longjmp() and throw() must not violate the entry/exit criteria.
4475 CS->getCapturedDecl()->setNothrow();
4476
Reid Kleckner87a31802018-03-12 21:43:02 +00004477 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004478
Alexey Bataev25e5b442015-09-15 12:52:43 +00004479 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
4480 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00004481}
4482
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004483namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004484/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004485/// extracting iteration space of each loop in the loop nest, that will be used
4486/// for IR generation.
4487class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004488 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004489 Sema &SemaRef;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004490 /// Data-sharing stack.
4491 DSAStackTy &Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004492 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004493 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004494 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004495 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004496 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004497 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004498 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004499 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004500 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004501 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004502 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004503 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004504 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004505 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004506 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004507 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004508 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004509 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004510 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004511 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004512 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004513 /// Var < UB
4514 /// Var <= UB
4515 /// UB > Var
4516 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00004517 /// This will have no value when the condition is !=
4518 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004519 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004520 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004521 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004522 bool SubtractStep = false;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004523 /// The outer loop counter this loop depends on (if any).
4524 const ValueDecl *DepDecl = nullptr;
4525 /// Contains number of loop (starts from 1) on which loop counter init
4526 /// expression of this loop depends on.
4527 Optional<unsigned> InitDependOnLC;
4528 /// Contains number of loop (starts from 1) on which loop counter condition
4529 /// expression of this loop depends on.
4530 Optional<unsigned> CondDependOnLC;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004531 /// Checks if the provide statement depends on the loop counter.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004532 Optional<unsigned> doesDependOnLoopCounter(const Stmt *S, bool IsInitializer);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004533
4534public:
Alexey Bataev622af1d2019-04-24 19:58:30 +00004535 OpenMPIterationSpaceChecker(Sema &SemaRef, DSAStackTy &Stack,
4536 SourceLocation DefaultLoc)
4537 : SemaRef(SemaRef), Stack(Stack), DefaultLoc(DefaultLoc),
4538 ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004539 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004540 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00004541 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004542 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004543 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00004544 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004545 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004546 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00004547 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004548 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004549 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004550 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004551 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004552 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004553 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004554 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00004555 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004556 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004557 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004558 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00004559 bool shouldSubtractStep() const { return SubtractStep; }
Alexey Bataev316ccf62019-01-29 18:51:58 +00004560 /// True, if the compare operator is strict (<, > or !=).
4561 bool isStrictTestOp() const { return TestIsStrictOp; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004562 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004563 Expr *buildNumIterations(
4564 Scope *S, const bool LimitedType,
4565 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004566 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00004567 Expr *
4568 buildPreCond(Scope *S, Expr *Cond,
4569 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004570 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004571 DeclRefExpr *
4572 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4573 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004574 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00004575 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004576 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004577 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004578 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004579 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004580 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004581 /// Build loop data with counter value for depend clauses in ordered
4582 /// directives.
4583 Expr *
4584 buildOrderedLoopData(Scope *S, Expr *Counter,
4585 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4586 SourceLocation Loc, Expr *Inc = nullptr,
4587 OverloadedOperatorKind OOK = OO_Amp);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004588 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00004589 bool dependent() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004590
4591private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004592 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004593 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00004594 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004595 /// Helper to set loop counter variable and its initializer.
Alexey Bataev622af1d2019-04-24 19:58:30 +00004596 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB,
4597 bool EmitDiags);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004598 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00004599 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4600 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004601 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004602 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004603};
4604
Alexey Bataeve3727102018-04-18 15:57:46 +00004605bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004606 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004607 assert(!LB && !UB && !Step);
4608 return false;
4609 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004610 return LCDecl->getType()->isDependentType() ||
4611 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4612 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004613}
4614
Alexey Bataeve3727102018-04-18 15:57:46 +00004615bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004616 Expr *NewLCRefExpr,
Alexey Bataev622af1d2019-04-24 19:58:30 +00004617 Expr *NewLB, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004618 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004619 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00004620 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004621 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004622 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004623 LCDecl = getCanonicalDecl(NewLCDecl);
4624 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004625 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4626 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004627 if ((Ctor->isCopyOrMoveConstructor() ||
4628 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4629 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004630 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004631 LB = NewLB;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004632 if (EmitDiags)
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004633 InitDependOnLC = doesDependOnLoopCounter(LB, /*IsInitializer=*/true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004634 return false;
4635}
4636
Alexey Bataev316ccf62019-01-29 18:51:58 +00004637bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB,
4638 llvm::Optional<bool> LessOp,
Kelvin Liefbe4af2018-11-21 19:10:48 +00004639 bool StrictOp, SourceRange SR,
4640 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004641 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004642 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4643 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004644 if (!NewUB)
4645 return true;
4646 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00004647 if (LessOp)
4648 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004649 TestIsStrictOp = StrictOp;
4650 ConditionSrcRange = SR;
4651 ConditionLoc = SL;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004652 CondDependOnLC = doesDependOnLoopCounter(UB, /*IsInitializer=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004653 return false;
4654}
4655
Alexey Bataeve3727102018-04-18 15:57:46 +00004656bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004657 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004658 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004659 if (!NewStep)
4660 return true;
4661 if (!NewStep->isValueDependent()) {
4662 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004663 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00004664 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4665 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004666 if (Val.isInvalid())
4667 return true;
4668 NewStep = Val.get();
4669
4670 // OpenMP [2.6, Canonical Loop Form, Restrictions]
4671 // If test-expr is of form var relational-op b and relational-op is < or
4672 // <= then incr-expr must cause var to increase on each iteration of the
4673 // loop. If test-expr is of form var relational-op b and relational-op is
4674 // > or >= then incr-expr must cause var to decrease on each iteration of
4675 // the loop.
4676 // If test-expr is of form b relational-op var and relational-op is < or
4677 // <= then incr-expr must cause var to decrease on each iteration of the
4678 // loop. If test-expr is of form b relational-op var and relational-op is
4679 // > or >= then incr-expr must cause var to increase on each iteration of
4680 // the loop.
4681 llvm::APSInt Result;
4682 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4683 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4684 bool IsConstNeg =
4685 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004686 bool IsConstPos =
4687 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004688 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00004689
4690 // != with increment is treated as <; != with decrement is treated as >
4691 if (!TestIsLessOp.hasValue())
4692 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004693 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004694 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004695 (IsConstNeg || (IsUnsigned && Subtract)) :
4696 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004697 SemaRef.Diag(NewStep->getExprLoc(),
4698 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004699 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004700 SemaRef.Diag(ConditionLoc,
4701 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004702 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004703 return true;
4704 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00004705 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00004706 NewStep =
4707 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4708 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004709 Subtract = !Subtract;
4710 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004711 }
4712
4713 Step = NewStep;
4714 SubtractStep = Subtract;
4715 return false;
4716}
4717
Alexey Bataev622af1d2019-04-24 19:58:30 +00004718namespace {
4719/// Checker for the non-rectangular loops. Checks if the initializer or
4720/// condition expression references loop counter variable.
4721class LoopCounterRefChecker final
4722 : public ConstStmtVisitor<LoopCounterRefChecker, bool> {
4723 Sema &SemaRef;
4724 DSAStackTy &Stack;
4725 const ValueDecl *CurLCDecl = nullptr;
Alexey Bataev2f9ef332019-04-25 16:21:13 +00004726 const ValueDecl *DepDecl = nullptr;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004727 const ValueDecl *PrevDepDecl = nullptr;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004728 bool IsInitializer = true;
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004729 unsigned BaseLoopId = 0;
4730 bool checkDecl(const Expr *E, const ValueDecl *VD) {
4731 if (getCanonicalDecl(VD) == getCanonicalDecl(CurLCDecl)) {
4732 SemaRef.Diag(E->getExprLoc(), diag::err_omp_stmt_depends_on_loop_counter)
4733 << (IsInitializer ? 0 : 1);
4734 return false;
4735 }
4736 const auto &&Data = Stack.isLoopControlVariable(VD);
4737 // OpenMP, 2.9.1 Canonical Loop Form, Restrictions.
4738 // The type of the loop iterator on which we depend may not have a random
4739 // access iterator type.
4740 if (Data.first && VD->getType()->isRecordType()) {
4741 SmallString<128> Name;
4742 llvm::raw_svector_ostream OS(Name);
4743 VD->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
4744 /*Qualified=*/true);
4745 SemaRef.Diag(E->getExprLoc(),
4746 diag::err_omp_wrong_dependency_iterator_type)
4747 << OS.str();
4748 SemaRef.Diag(VD->getLocation(), diag::note_previous_decl) << VD;
4749 return false;
4750 }
4751 if (Data.first &&
4752 (DepDecl || (PrevDepDecl &&
4753 getCanonicalDecl(VD) != getCanonicalDecl(PrevDepDecl)))) {
4754 if (!DepDecl && PrevDepDecl)
4755 DepDecl = PrevDepDecl;
4756 SmallString<128> Name;
4757 llvm::raw_svector_ostream OS(Name);
4758 DepDecl->getNameForDiagnostic(OS, SemaRef.getPrintingPolicy(),
4759 /*Qualified=*/true);
4760 SemaRef.Diag(E->getExprLoc(),
4761 diag::err_omp_invariant_or_linear_dependency)
4762 << OS.str();
4763 return false;
4764 }
4765 if (Data.first) {
4766 DepDecl = VD;
4767 BaseLoopId = Data.first;
4768 }
4769 return Data.first;
4770 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00004771
4772public:
4773 bool VisitDeclRefExpr(const DeclRefExpr *E) {
4774 const ValueDecl *VD = E->getDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004775 if (isa<VarDecl>(VD))
4776 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00004777 return false;
4778 }
4779 bool VisitMemberExpr(const MemberExpr *E) {
4780 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
4781 const ValueDecl *VD = E->getMemberDecl();
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004782 return checkDecl(E, VD);
Alexey Bataev622af1d2019-04-24 19:58:30 +00004783 }
4784 return false;
4785 }
4786 bool VisitStmt(const Stmt *S) {
Alexey Bataev2f9ef332019-04-25 16:21:13 +00004787 bool Res = true;
4788 for (const Stmt *Child : S->children())
4789 Res = Child && Visit(Child) && Res;
4790 return Res;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004791 }
4792 explicit LoopCounterRefChecker(Sema &SemaRef, DSAStackTy &Stack,
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004793 const ValueDecl *CurLCDecl, bool IsInitializer,
4794 const ValueDecl *PrevDepDecl = nullptr)
Alexey Bataev622af1d2019-04-24 19:58:30 +00004795 : SemaRef(SemaRef), Stack(Stack), CurLCDecl(CurLCDecl),
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004796 PrevDepDecl(PrevDepDecl), IsInitializer(IsInitializer) {}
4797 unsigned getBaseLoopId() const {
4798 assert(CurLCDecl && "Expected loop dependency.");
4799 return BaseLoopId;
4800 }
4801 const ValueDecl *getDepDecl() const {
4802 assert(CurLCDecl && "Expected loop dependency.");
4803 return DepDecl;
4804 }
Alexey Bataev622af1d2019-04-24 19:58:30 +00004805};
4806} // namespace
4807
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004808Optional<unsigned>
4809OpenMPIterationSpaceChecker::doesDependOnLoopCounter(const Stmt *S,
4810 bool IsInitializer) {
Alexey Bataev622af1d2019-04-24 19:58:30 +00004811 // Check for the non-rectangular loops.
Alexey Bataev5ddc6d12019-04-26 19:28:37 +00004812 LoopCounterRefChecker LoopStmtChecker(SemaRef, Stack, LCDecl, IsInitializer,
4813 DepDecl);
4814 if (LoopStmtChecker.Visit(S)) {
4815 DepDecl = LoopStmtChecker.getDepDecl();
4816 return LoopStmtChecker.getBaseLoopId();
4817 }
4818 return llvm::None;
Alexey Bataev622af1d2019-04-24 19:58:30 +00004819}
4820
Alexey Bataeve3727102018-04-18 15:57:46 +00004821bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004822 // Check init-expr for canonical loop form and save loop counter
4823 // variable - #Var and its initialization value - #LB.
4824 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4825 // var = lb
4826 // integer-type var = lb
4827 // random-access-iterator-type var = lb
4828 // pointer-type var = lb
4829 //
4830 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00004831 if (EmitDiags) {
4832 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4833 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004834 return true;
4835 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004836 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4837 if (!ExprTemp->cleanupsHaveSideEffects())
4838 S = ExprTemp->getSubExpr();
4839
Alexander Musmana5f070a2014-10-01 06:03:56 +00004840 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004841 if (Expr *E = dyn_cast<Expr>(S))
4842 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004843 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004844 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004845 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004846 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4847 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4848 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00004849 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
4850 EmitDiags);
4851 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS(), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004852 }
4853 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4854 if (ME->isArrow() &&
4855 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00004856 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
4857 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004858 }
4859 }
David Majnemer9d168222016-08-05 17:44:54 +00004860 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004861 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00004862 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00004863 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004864 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00004865 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004866 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004867 diag::ext_omp_loop_not_canonical_init)
4868 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00004869 return setLCDeclAndLB(
4870 Var,
4871 buildDeclRefExpr(SemaRef, Var,
4872 Var->getType().getNonReferenceType(),
4873 DS->getBeginLoc()),
Alexey Bataev622af1d2019-04-24 19:58:30 +00004874 Var->getInit(), EmitDiags);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004875 }
4876 }
4877 }
David Majnemer9d168222016-08-05 17:44:54 +00004878 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004879 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004880 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00004881 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004882 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4883 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev622af1d2019-04-24 19:58:30 +00004884 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
4885 EmitDiags);
4886 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1), EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004887 }
4888 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4889 if (ME->isArrow() &&
4890 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataev622af1d2019-04-24 19:58:30 +00004891 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS(),
4892 EmitDiags);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004893 }
4894 }
4895 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004896
Alexey Bataeve3727102018-04-18 15:57:46 +00004897 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004898 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00004899 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004900 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00004901 << S->getSourceRange();
4902 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004903 return true;
4904}
4905
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004906/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004907/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00004908static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004909 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00004910 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004911 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00004912 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004913 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004914 if ((Ctor->isCopyOrMoveConstructor() ||
4915 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4916 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004917 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004918 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4919 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004920 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004921 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004922 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004923 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4924 return getCanonicalDecl(ME->getMemberDecl());
4925 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004926}
4927
Alexey Bataeve3727102018-04-18 15:57:46 +00004928bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004929 // Check test-expr for canonical form, save upper-bound UB, flags for
4930 // less/greater and for strict/non-strict comparison.
4931 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4932 // var relational-op b
4933 // b relational-op var
4934 //
4935 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004936 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004937 return true;
4938 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004939 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004940 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00004941 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004942 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004943 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4944 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004945 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4946 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4947 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004948 if (getInitLCDecl(BO->getRHS()) == LCDecl)
4949 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004950 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4951 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4952 BO->getSourceRange(), BO->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00004953 } else if (BO->getOpcode() == BO_NE)
4954 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
4955 BO->getRHS() : BO->getLHS(),
4956 /*LessOp=*/llvm::None,
4957 /*StrictOp=*/true,
4958 BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00004959 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004960 if (CE->getNumArgs() == 2) {
4961 auto Op = CE->getOperator();
4962 switch (Op) {
4963 case OO_Greater:
4964 case OO_GreaterEqual:
4965 case OO_Less:
4966 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004967 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4968 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004969 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4970 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004971 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4972 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004973 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4974 CE->getOperatorLoc());
4975 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004976 case OO_ExclaimEqual:
Kelvin Liefbe4af2018-11-21 19:10:48 +00004977 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
4978 CE->getArg(1) : CE->getArg(0),
4979 /*LessOp=*/llvm::None,
4980 /*StrictOp=*/true,
4981 CE->getSourceRange(),
4982 CE->getOperatorLoc());
4983 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004984 default:
4985 break;
4986 }
4987 }
4988 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004989 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004990 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004991 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004992 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004993 return true;
4994}
4995
Alexey Bataeve3727102018-04-18 15:57:46 +00004996bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004997 // RHS of canonical loop form increment can be:
4998 // var + incr
4999 // incr + var
5000 // var - incr
5001 //
5002 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00005003 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005004 if (BO->isAdditiveOp()) {
5005 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00005006 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5007 return setStep(BO->getRHS(), !IsAdd);
5008 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
5009 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005010 }
David Majnemer9d168222016-08-05 17:44:54 +00005011 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005012 bool IsAdd = CE->getOperator() == OO_Plus;
5013 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005014 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5015 return setStep(CE->getArg(1), !IsAdd);
5016 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
5017 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005018 }
5019 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005020 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005021 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005022 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005023 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005024 return true;
5025}
5026
Alexey Bataeve3727102018-04-18 15:57:46 +00005027bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005028 // Check incr-expr for canonical loop form and return true if it
5029 // does not conform.
5030 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
5031 // ++var
5032 // var++
5033 // --var
5034 // var--
5035 // var += incr
5036 // var -= incr
5037 // var = var + incr
5038 // var = incr + var
5039 // var = var - incr
5040 //
5041 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005042 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005043 return true;
5044 }
Tim Shen4a05bb82016-06-21 20:29:17 +00005045 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
5046 if (!ExprTemp->cleanupsHaveSideEffects())
5047 S = ExprTemp->getSubExpr();
5048
Alexander Musmana5f070a2014-10-01 06:03:56 +00005049 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005050 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00005051 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005052 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00005053 getInitLCDecl(UO->getSubExpr()) == LCDecl)
5054 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005055 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005056 (UO->isDecrementOp() ? -1 : 1))
5057 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005058 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00005059 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005060 switch (BO->getOpcode()) {
5061 case BO_AddAssign:
5062 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005063 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5064 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005065 break;
5066 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00005067 if (getInitLCDecl(BO->getLHS()) == LCDecl)
5068 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005069 break;
5070 default:
5071 break;
5072 }
David Majnemer9d168222016-08-05 17:44:54 +00005073 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005074 switch (CE->getOperator()) {
5075 case OO_PlusPlus:
5076 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00005077 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5078 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00005079 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005080 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00005081 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
5082 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00005083 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005084 break;
5085 case OO_PlusEqual:
5086 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00005087 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5088 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005089 break;
5090 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00005091 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
5092 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005093 break;
5094 default:
5095 break;
5096 }
5097 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005098 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005099 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005100 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005101 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005102 return true;
5103}
Alexander Musmana5f070a2014-10-01 06:03:56 +00005104
Alexey Bataev5a3af132016-03-29 08:58:54 +00005105static ExprResult
5106tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00005107 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00005108 if (SemaRef.CurContext->isDependentContext())
5109 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005110 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
5111 return SemaRef.PerformImplicitConversion(
5112 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
5113 /*AllowExplicit=*/true);
5114 auto I = Captures.find(Capture);
5115 if (I != Captures.end())
5116 return buildCapture(SemaRef, Capture, I->second);
5117 DeclRefExpr *Ref = nullptr;
5118 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
5119 Captures[Capture] = Ref;
5120 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005121}
5122
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005123/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00005124Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005125 Scope *S, const bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00005126 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005127 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00005128 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005129 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005130 SemaRef.getLangOpts().CPlusPlus) {
5131 // Upper - Lower
Kelvin Liefbe4af2018-11-21 19:10:48 +00005132 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
5133 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00005134 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
5135 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005136 if (!Upper || !Lower)
5137 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005138
5139 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
5140
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005141 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005142 // BuildBinOp already emitted error, this one is to point user to upper
5143 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005144 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00005145 << Upper->getSourceRange() << Lower->getSourceRange();
5146 return nullptr;
5147 }
5148 }
5149
5150 if (!Diff.isUsable())
5151 return nullptr;
5152
5153 // Upper - Lower [- 1]
5154 if (TestIsStrictOp)
5155 Diff = SemaRef.BuildBinOp(
5156 S, DefaultLoc, BO_Sub, Diff.get(),
5157 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5158 if (!Diff.isUsable())
5159 return nullptr;
5160
5161 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00005162 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005163 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005164 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005165 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005166 if (!Diff.isUsable())
5167 return nullptr;
5168
5169 // Parentheses (for dumping/debugging purposes only).
5170 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
5171 if (!Diff.isUsable())
5172 return nullptr;
5173
5174 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005175 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005176 if (!Diff.isUsable())
5177 return nullptr;
5178
Alexander Musman174b3ca2014-10-06 11:16:29 +00005179 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005180 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00005181 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005182 bool UseVarType = VarType->hasIntegerRepresentation() &&
5183 C.getTypeSize(Type) > C.getTypeSize(VarType);
5184 if (!Type->isIntegerType() || UseVarType) {
5185 unsigned NewSize =
5186 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
5187 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
5188 : Type->hasSignedIntegerRepresentation();
5189 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00005190 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
5191 Diff = SemaRef.PerformImplicitConversion(
5192 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
5193 if (!Diff.isUsable())
5194 return nullptr;
5195 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005196 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00005197 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00005198 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
5199 if (NewSize != C.getTypeSize(Type)) {
5200 if (NewSize < C.getTypeSize(Type)) {
5201 assert(NewSize == 64 && "incorrect loop var size");
5202 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
5203 << InitSrcRange << ConditionSrcRange;
5204 }
5205 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005206 NewSize, Type->hasSignedIntegerRepresentation() ||
5207 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00005208 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
5209 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
5210 Sema::AA_Converting, true);
5211 if (!Diff.isUsable())
5212 return nullptr;
5213 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00005214 }
5215 }
5216
Alexander Musmana5f070a2014-10-01 06:03:56 +00005217 return Diff.get();
5218}
5219
Alexey Bataeve3727102018-04-18 15:57:46 +00005220Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005221 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00005222 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00005223 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
5224 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5225 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005226
Alexey Bataeve3727102018-04-18 15:57:46 +00005227 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
5228 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005229 if (!NewLB.isUsable() || !NewUB.isUsable())
5230 return nullptr;
5231
Alexey Bataeve3727102018-04-18 15:57:46 +00005232 ExprResult CondExpr =
5233 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005234 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00005235 (TestIsStrictOp ? BO_LT : BO_LE) :
5236 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00005237 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005238 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005239 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
5240 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00005241 CondExpr = SemaRef.PerformImplicitConversion(
5242 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
5243 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005244 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00005245 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
Sergi Mateo Bellidof3e00fe2019-02-01 08:39:01 +00005246 // Otherwise use original loop condition and evaluate it in runtime.
Alexey Bataev62dbb972015-04-22 11:59:37 +00005247 return CondExpr.isUsable() ? CondExpr.get() : Cond;
5248}
5249
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005250/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005251DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00005252 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
5253 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005254 auto *VD = dyn_cast<VarDecl>(LCDecl);
5255 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005256 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
5257 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005258 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00005259 const DSAStackTy::DSAVarData Data =
5260 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005261 // If the loop control decl is explicitly marked as private, do not mark it
5262 // as captured again.
5263 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
5264 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005265 return Ref;
5266 }
Alexey Bataev0d8fcdf2019-03-14 20:36:00 +00005267 return cast<DeclRefExpr>(LCRef);
Alexey Bataeva8899172015-08-06 12:30:57 +00005268}
5269
Alexey Bataeve3727102018-04-18 15:57:46 +00005270Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005271 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005272 QualType Type = LCDecl->getType().getNonReferenceType();
5273 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00005274 SemaRef, DefaultLoc, Type, LCDecl->getName(),
5275 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
5276 isa<VarDecl>(LCDecl)
5277 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
5278 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00005279 if (PrivateVar->isInvalidDecl())
5280 return nullptr;
5281 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
5282 }
5283 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005284}
5285
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005286/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005287Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005288
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005289/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005290Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005291
Alexey Bataevf138fda2018-08-13 19:04:24 +00005292Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
5293 Scope *S, Expr *Counter,
5294 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
5295 Expr *Inc, OverloadedOperatorKind OOK) {
5296 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
5297 if (!Cnt)
5298 return nullptr;
5299 if (Inc) {
5300 assert((OOK == OO_Plus || OOK == OO_Minus) &&
5301 "Expected only + or - operations for depend clauses.");
5302 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
5303 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
5304 if (!Cnt)
5305 return nullptr;
5306 }
5307 ExprResult Diff;
5308 QualType VarType = LCDecl->getType().getNonReferenceType();
5309 if (VarType->isIntegerType() || VarType->isPointerType() ||
5310 SemaRef.getLangOpts().CPlusPlus) {
5311 // Upper - Lower
Alexey Bataev316ccf62019-01-29 18:51:58 +00005312 Expr *Upper = TestIsLessOp.getValue()
5313 ? Cnt
5314 : tryBuildCapture(SemaRef, UB, Captures).get();
5315 Expr *Lower = TestIsLessOp.getValue()
5316 ? tryBuildCapture(SemaRef, LB, Captures).get()
5317 : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005318 if (!Upper || !Lower)
5319 return nullptr;
5320
5321 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
5322
5323 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
5324 // BuildBinOp already emitted error, this one is to point user to upper
5325 // and lower bound, and to tell what is passed to 'operator-'.
5326 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
5327 << Upper->getSourceRange() << Lower->getSourceRange();
5328 return nullptr;
5329 }
5330 }
5331
5332 if (!Diff.isUsable())
5333 return nullptr;
5334
5335 // Parentheses (for dumping/debugging purposes only).
5336 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
5337 if (!Diff.isUsable())
5338 return nullptr;
5339
5340 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
5341 if (!NewStep.isUsable())
5342 return nullptr;
5343 // (Upper - Lower) / Step
5344 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
5345 if (!Diff.isUsable())
5346 return nullptr;
5347
5348 return Diff.get();
5349}
5350
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005351/// Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00005352struct LoopIterationSpace final {
Alexey Bataev316ccf62019-01-29 18:51:58 +00005353 /// True if the condition operator is the strict compare operator (<, > or
5354 /// !=).
5355 bool IsStrictCompare = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005356 /// Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00005357 Expr *PreCond = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005358 /// This expression calculates the number of iterations in the loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005359 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00005360 Expr *NumIterations = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005361 /// The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00005362 Expr *CounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005363 /// Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00005364 Expr *PrivateCounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005365 /// This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00005366 Expr *CounterInit = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005367 /// This is step for the #CounterVar used to generate its update:
Alexander Musmana5f070a2014-10-01 06:03:56 +00005368 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00005369 Expr *CounterStep = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005370 /// Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00005371 bool Subtract = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005372 /// Source range of the loop init.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005373 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005374 /// Source range of the loop condition.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005375 SourceRange CondSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005376 /// Source range of the loop increment.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005377 SourceRange IncSrcRange;
5378};
5379
Alexey Bataev23b69422014-06-18 07:08:49 +00005380} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005381
Alexey Bataev9c821032015-04-30 04:23:23 +00005382void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
5383 assert(getLangOpts().OpenMP && "OpenMP is not active.");
5384 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005385 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
5386 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00005387 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00005388 DSAStack->loopStart();
Alexey Bataev622af1d2019-04-24 19:58:30 +00005389 OpenMPIterationSpaceChecker ISC(*this, *DSAStack, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00005390 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
5391 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005392 auto *VD = dyn_cast<VarDecl>(D);
5393 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005394 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005395 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00005396 } else {
5397 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
5398 /*WithInit=*/false);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005399 VD = cast<VarDecl>(Ref->getDecl());
5400 }
5401 }
5402 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00005403 const Decl *LD = DSAStack->getPossiblyLoopCunter();
5404 if (LD != D->getCanonicalDecl()) {
5405 DSAStack->resetPossibleLoopCounter();
5406 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
5407 MarkDeclarationsReferencedInExpr(
5408 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
5409 Var->getType().getNonLValueExprType(Context),
5410 ForLoc, /*RefersToCapture=*/true));
5411 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005412 }
5413 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005414 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00005415 }
5416}
5417
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005418/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005419/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00005420static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00005421 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
5422 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00005423 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
5424 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00005425 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005426 LoopIterationSpace &ResultIterSpace,
Alexey Bataeve3727102018-04-18 15:57:46 +00005427 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005428 // OpenMP [2.6, Canonical Loop Form]
5429 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00005430 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005431 if (!For) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005432 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005433 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00005434 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00005435 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005436 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00005437 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
5438 SemaRef.Diag(DSA.getConstructLoc(),
5439 diag::note_omp_collapse_ordered_expr)
5440 << 2 << CollapseLoopCountExpr->getSourceRange()
5441 << OrderedLoopCountExpr->getSourceRange();
5442 else if (CollapseLoopCountExpr)
5443 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5444 diag::note_omp_collapse_ordered_expr)
5445 << 0 << CollapseLoopCountExpr->getSourceRange();
5446 else
5447 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5448 diag::note_omp_collapse_ordered_expr)
5449 << 1 << OrderedLoopCountExpr->getSourceRange();
5450 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005451 return true;
5452 }
5453 assert(For->getBody());
5454
Alexey Bataev622af1d2019-04-24 19:58:30 +00005455 OpenMPIterationSpaceChecker ISC(SemaRef, DSA, For->getForLoc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005456
5457 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00005458 Stmt *Init = For->getInit();
5459 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005460 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005461
5462 bool HasErrors = false;
5463
5464 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005465 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
5466 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005467
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005468 // OpenMP [2.6, Canonical Loop Form]
5469 // Var is one of the following:
5470 // A variable of signed or unsigned integer type.
5471 // For C++, a variable of a random access iterator type.
5472 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00005473 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005474 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
5475 !VarType->isPointerType() &&
5476 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005477 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005478 << SemaRef.getLangOpts().CPlusPlus;
5479 HasErrors = true;
5480 }
5481
5482 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
5483 // a Construct
5484 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5485 // parallel for construct is (are) private.
5486 // The loop iteration variable in the associated for-loop of a simd
5487 // construct with just one associated for-loop is linear with a
5488 // constant-linear-step that is the increment of the associated for-loop.
5489 // Exclude loop var from the list of variables with implicitly defined data
5490 // sharing attributes.
5491 VarsWithImplicitDSA.erase(LCDecl);
5492
5493 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
5494 // in a Construct, C/C++].
5495 // The loop iteration variable in the associated for-loop of a simd
5496 // construct with just one associated for-loop may be listed in a linear
5497 // clause with a constant-linear-step that is the increment of the
5498 // associated for-loop.
5499 // The loop iteration variable(s) in the associated for-loop(s) of a for or
5500 // parallel for construct may be listed in a private or lastprivate clause.
5501 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
5502 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
5503 // declared in the loop and it is predetermined as a private.
Alexey Bataeve3727102018-04-18 15:57:46 +00005504 OpenMPClauseKind PredeterminedCKind =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005505 isOpenMPSimdDirective(DKind)
5506 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
5507 : OMPC_private;
5508 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5509 DVar.CKind != PredeterminedCKind) ||
5510 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
5511 isOpenMPDistributeDirective(DKind)) &&
5512 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
5513 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
5514 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005515 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005516 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
5517 << getOpenMPClauseName(PredeterminedCKind);
5518 if (DVar.RefExpr == nullptr)
5519 DVar.CKind = PredeterminedCKind;
Alexey Bataeve3727102018-04-18 15:57:46 +00005520 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005521 HasErrors = true;
5522 } else if (LoopDeclRefExpr != nullptr) {
5523 // Make the loop iteration variable private (for worksharing constructs),
5524 // linear (for simd directives with the only one associated loop) or
5525 // lastprivate (for simd directives with several collapsed or ordered
5526 // loops).
5527 if (DVar.CKind == OMPC_unknown)
Alexey Bataevc2cdff62019-01-29 21:12:28 +00005528 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005529 }
5530
5531 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
5532
5533 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005534 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00005535
5536 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00005537 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005538 }
5539
Alexey Bataeve3727102018-04-18 15:57:46 +00005540 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005541 return HasErrors;
5542
Alexander Musmana5f070a2014-10-01 06:03:56 +00005543 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005544 ResultIterSpace.PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00005545 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
5546 ResultIterSpace.NumIterations = ISC.buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005547 DSA.getCurScope(),
5548 (isOpenMPWorksharingDirective(DKind) ||
5549 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
5550 Captures);
Alexey Bataeve3727102018-04-18 15:57:46 +00005551 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
5552 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
5553 ResultIterSpace.CounterInit = ISC.buildCounterInit();
5554 ResultIterSpace.CounterStep = ISC.buildCounterStep();
5555 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
5556 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
5557 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
5558 ResultIterSpace.Subtract = ISC.shouldSubtractStep();
Alexey Bataev316ccf62019-01-29 18:51:58 +00005559 ResultIterSpace.IsStrictCompare = ISC.isStrictTestOp();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005560
Alexey Bataev62dbb972015-04-22 11:59:37 +00005561 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
5562 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005563 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00005564 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00005565 ResultIterSpace.CounterInit == nullptr ||
5566 ResultIterSpace.CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00005567 if (!HasErrors && DSA.isOrderedRegion()) {
5568 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
5569 if (CurrentNestedLoopCount <
5570 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
5571 DSA.getOrderedRegionParam().second->setLoopNumIterations(
5572 CurrentNestedLoopCount, ResultIterSpace.NumIterations);
5573 DSA.getOrderedRegionParam().second->setLoopCounter(
5574 CurrentNestedLoopCount, ResultIterSpace.CounterVar);
5575 }
5576 }
5577 for (auto &Pair : DSA.getDoacrossDependClauses()) {
5578 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
5579 // Erroneous case - clause has some problems.
5580 continue;
5581 }
5582 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
5583 Pair.second.size() <= CurrentNestedLoopCount) {
5584 // Erroneous case - clause has some problems.
5585 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
5586 continue;
5587 }
5588 Expr *CntValue;
5589 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5590 CntValue = ISC.buildOrderedLoopData(
5591 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5592 Pair.first->getDependencyLoc());
5593 else
5594 CntValue = ISC.buildOrderedLoopData(
5595 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
5596 Pair.first->getDependencyLoc(),
5597 Pair.second[CurrentNestedLoopCount].first,
5598 Pair.second[CurrentNestedLoopCount].second);
5599 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
5600 }
5601 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005602
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005603 return HasErrors;
5604}
5605
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005606/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005607static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00005608buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005609 ExprResult Start,
Alexey Bataeve3727102018-04-18 15:57:46 +00005610 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005611 // Build 'VarRef = Start.
Alexey Bataeve3727102018-04-18 15:57:46 +00005612 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00005613 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005614 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00005615 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00005616 VarRef.get()->getType())) {
5617 NewStart = SemaRef.PerformImplicitConversion(
5618 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
5619 /*AllowExplicit=*/true);
5620 if (!NewStart.isUsable())
5621 return ExprError();
5622 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005623
Alexey Bataeve3727102018-04-18 15:57:46 +00005624 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005625 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5626 return Init;
5627}
5628
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005629/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00005630static ExprResult buildCounterUpdate(
5631 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
5632 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
5633 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005634 // Add parentheses (for debugging purposes only).
5635 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
5636 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
5637 !Step.isUsable())
5638 return ExprError();
5639
Alexey Bataev5a3af132016-03-29 08:58:54 +00005640 ExprResult NewStep = Step;
5641 if (Captures)
5642 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005643 if (NewStep.isInvalid())
5644 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005645 ExprResult Update =
5646 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005647 if (!Update.isUsable())
5648 return ExprError();
5649
Alexey Bataevc0214e02016-02-16 12:13:49 +00005650 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
5651 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00005652 ExprResult NewStart = Start;
5653 if (Captures)
5654 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005655 if (NewStart.isInvalid())
5656 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005657
Alexey Bataevc0214e02016-02-16 12:13:49 +00005658 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
5659 ExprResult SavedUpdate = Update;
5660 ExprResult UpdateVal;
5661 if (VarRef.get()->getType()->isOverloadableType() ||
5662 NewStart.get()->getType()->isOverloadableType() ||
5663 Update.get()->getType()->isOverloadableType()) {
5664 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5665 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5666 Update =
5667 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5668 if (Update.isUsable()) {
5669 UpdateVal =
5670 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5671 VarRef.get(), SavedUpdate.get());
5672 if (UpdateVal.isUsable()) {
5673 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5674 UpdateVal.get());
5675 }
5676 }
5677 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5678 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005679
Alexey Bataevc0214e02016-02-16 12:13:49 +00005680 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5681 if (!Update.isUsable() || !UpdateVal.isUsable()) {
5682 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5683 NewStart.get(), SavedUpdate.get());
5684 if (!Update.isUsable())
5685 return ExprError();
5686
Alexey Bataev11481f52016-02-17 10:29:05 +00005687 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5688 VarRef.get()->getType())) {
5689 Update = SemaRef.PerformImplicitConversion(
5690 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5691 if (!Update.isUsable())
5692 return ExprError();
5693 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00005694
5695 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5696 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005697 return Update;
5698}
5699
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005700/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005701/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005702static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005703 if (E == nullptr)
5704 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00005705 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005706 QualType OldType = E->getType();
5707 unsigned HasBits = C.getTypeSize(OldType);
5708 if (HasBits >= Bits)
5709 return ExprResult(E);
5710 // OK to convert to signed, because new type has more bits than old.
5711 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5712 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5713 true);
5714}
5715
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005716/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005717/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005718static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005719 if (E == nullptr)
5720 return false;
5721 llvm::APSInt Result;
5722 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5723 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5724 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005725}
5726
Alexey Bataev5a3af132016-03-29 08:58:54 +00005727/// Build preinits statement for the given declarations.
5728static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00005729 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005730 if (!PreInits.empty()) {
5731 return new (Context) DeclStmt(
5732 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5733 SourceLocation(), SourceLocation());
5734 }
5735 return nullptr;
5736}
5737
5738/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00005739static Stmt *
5740buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00005741 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005742 if (!Captures.empty()) {
5743 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00005744 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00005745 PreInits.push_back(Pair.second->getDecl());
5746 return buildPreInits(Context, PreInits);
5747 }
5748 return nullptr;
5749}
5750
5751/// Build postupdate expression for the given list of postupdates expressions.
5752static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5753 Expr *PostUpdate = nullptr;
5754 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005755 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005756 Expr *ConvE = S.BuildCStyleCastExpr(
5757 E->getExprLoc(),
5758 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5759 E->getExprLoc(), E)
5760 .get();
5761 PostUpdate = PostUpdate
5762 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5763 PostUpdate, ConvE)
5764 .get()
5765 : ConvE;
5766 }
5767 }
5768 return PostUpdate;
5769}
5770
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005771/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00005772/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5773/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005774static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00005775checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00005776 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5777 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00005778 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00005779 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005780 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005781 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005782 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005783 Expr::EvalResult Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005784 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Fangrui Song407659a2018-11-30 23:41:18 +00005785 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005786 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005787 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005788 if (OrderedLoopCountExpr) {
5789 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005790 Expr::EvalResult EVResult;
5791 if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5792 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005793 if (Result.getLimitedValue() < NestedLoopCount) {
5794 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5795 diag::err_omp_wrong_ordered_loop_count)
5796 << OrderedLoopCountExpr->getSourceRange();
5797 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5798 diag::note_collapse_loop_count)
5799 << CollapseLoopCountExpr->getSourceRange();
5800 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005801 OrderedLoopCount = Result.getLimitedValue();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005802 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005803 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005804 // This is helper routine for loop directives (e.g., 'for', 'simd',
5805 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00005806 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev316ccf62019-01-29 18:51:58 +00005807 SmallVector<LoopIterationSpace, 4> IterSpaces(
5808 std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00005809 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005810 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005811 if (checkOpenMPIterationSpace(
5812 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5813 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5814 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5815 Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00005816 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005817 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005818 // OpenMP [2.8.1, simd construct, Restrictions]
5819 // All loops associated with the construct must be perfectly nested; that
5820 // is, there must be no intervening code nor any OpenMP directive between
5821 // any two loops.
5822 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005823 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005824 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5825 if (checkOpenMPIterationSpace(
5826 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5827 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5828 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5829 Captures))
5830 return 0;
5831 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5832 // Handle initialization of captured loop iterator variables.
5833 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5834 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5835 Captures[DRE] = DRE;
5836 }
5837 }
5838 // Move on to the next nested for loop, or to the loop body.
5839 // OpenMP [2.8.1, simd construct, Restrictions]
5840 // All loops associated with the construct must be perfectly nested; that
5841 // is, there must be no intervening code nor any OpenMP directive between
5842 // any two loops.
5843 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5844 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005845
Alexander Musmana5f070a2014-10-01 06:03:56 +00005846 Built.clear(/* size */ NestedLoopCount);
5847
5848 if (SemaRef.CurContext->isDependentContext())
5849 return NestedLoopCount;
5850
5851 // An example of what is generated for the following code:
5852 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00005853 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00005854 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005855 // for (k = 0; k < NK; ++k)
5856 // for (j = J0; j < NJ; j+=2) {
5857 // <loop body>
5858 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005859 //
5860 // We generate the code below.
5861 // Note: the loop body may be outlined in CodeGen.
5862 // Note: some counters may be C++ classes, operator- is used to find number of
5863 // iterations and operator+= to calculate counter value.
5864 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5865 // or i64 is currently supported).
5866 //
5867 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5868 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5869 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5870 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5871 // // similar updates for vars in clauses (e.g. 'linear')
5872 // <loop body (using local i and j)>
5873 // }
5874 // i = NI; // assign final values of counters
5875 // j = NJ;
5876 //
5877
5878 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5879 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00005880 // Precondition tests if there is at least one iteration (all conditions are
5881 // true).
5882 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00005883 Expr *N0 = IterSpaces[0].NumIterations;
5884 ExprResult LastIteration32 =
5885 widenIterationCount(/*Bits=*/32,
5886 SemaRef
5887 .PerformImplicitConversion(
5888 N0->IgnoreImpCasts(), N0->getType(),
5889 Sema::AA_Converting, /*AllowExplicit=*/true)
5890 .get(),
5891 SemaRef);
5892 ExprResult LastIteration64 = widenIterationCount(
5893 /*Bits=*/64,
5894 SemaRef
5895 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5896 Sema::AA_Converting,
5897 /*AllowExplicit=*/true)
5898 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005899 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005900
5901 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5902 return NestedLoopCount;
5903
Alexey Bataeve3727102018-04-18 15:57:46 +00005904 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005905 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5906
5907 Scope *CurScope = DSA.getCurScope();
5908 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00005909 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00005910 PreCond =
5911 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5912 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00005913 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005914 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00005915 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005916 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5917 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005918 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005919 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005920 SemaRef
5921 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5922 Sema::AA_Converting,
5923 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005924 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005925 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005926 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005927 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005928 SemaRef
5929 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5930 Sema::AA_Converting,
5931 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005932 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005933 }
5934
5935 // Choose either the 32-bit or 64-bit version.
5936 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005937 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
5938 (LastIteration32.isUsable() &&
5939 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5940 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5941 fitsInto(
5942 /*Bits=*/32,
5943 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5944 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00005945 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00005946 QualType VType = LastIteration.get()->getType();
5947 QualType RealVType = VType;
5948 QualType StrideVType = VType;
5949 if (isOpenMPTaskLoopDirective(DKind)) {
5950 VType =
5951 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5952 StrideVType =
5953 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5954 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005955
5956 if (!LastIteration.isUsable())
5957 return 0;
5958
5959 // Save the number of iterations.
5960 ExprResult NumIterations = LastIteration;
5961 {
5962 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005963 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5964 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005965 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5966 if (!LastIteration.isUsable())
5967 return 0;
5968 }
5969
5970 // Calculate the last iteration number beforehand instead of doing this on
5971 // each iteration. Do not do this if the number of iterations may be kfold-ed.
5972 llvm::APSInt Result;
5973 bool IsConstant =
5974 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5975 ExprResult CalcLastIteration;
5976 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005977 ExprResult SaveRef =
5978 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005979 LastIteration = SaveRef;
5980
5981 // Prepare SaveRef + 1.
5982 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005983 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005984 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5985 if (!NumIterations.isUsable())
5986 return 0;
5987 }
5988
5989 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5990
David Majnemer9d168222016-08-05 17:44:54 +00005991 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005992 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005993 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5994 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005995 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005996 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5997 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005998 SemaRef.AddInitializerToDecl(LBDecl,
5999 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
6000 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006001
6002 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00006003 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
6004 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00006005 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00006006 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006007
6008 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
6009 // This will be used to implement clause 'lastprivate'.
6010 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00006011 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
6012 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00006013 SemaRef.AddInitializerToDecl(ILDecl,
6014 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
6015 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006016
6017 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00006018 VarDecl *STDecl =
6019 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
6020 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00006021 SemaRef.AddInitializerToDecl(STDecl,
6022 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
6023 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006024
6025 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00006026 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00006027 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
6028 UB.get(), LastIteration.get());
6029 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00006030 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
6031 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00006032 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
6033 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006034 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00006035
6036 // If we have a combined directive that combines 'distribute', 'for' or
6037 // 'simd' we need to be able to access the bounds of the schedule of the
6038 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
6039 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
6040 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00006041 // Lower bound variable, initialized with zero.
6042 VarDecl *CombLBDecl =
6043 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
6044 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
6045 SemaRef.AddInitializerToDecl(
6046 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
6047 /*DirectInit*/ false);
6048
6049 // Upper bound variable, initialized with last iteration number.
6050 VarDecl *CombUBDecl =
6051 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
6052 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
6053 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
6054 /*DirectInit*/ false);
6055
6056 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
6057 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
6058 ExprResult CombCondOp =
6059 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
6060 LastIteration.get(), CombUB.get());
6061 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
6062 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006063 CombEUB =
6064 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006065
Alexey Bataeve3727102018-04-18 15:57:46 +00006066 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00006067 // We expect to have at least 2 more parameters than the 'parallel'
6068 // directive does - the lower and upper bounds of the previous schedule.
6069 assert(CD->getNumParams() >= 4 &&
6070 "Unexpected number of parameters in loop combined directive");
6071
6072 // Set the proper type for the bounds given what we learned from the
6073 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00006074 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
6075 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00006076
6077 // Previous lower and upper bounds are obtained from the region
6078 // parameters.
6079 PrevLB =
6080 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
6081 PrevUB =
6082 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
6083 }
Alexander Musmanc6388682014-12-15 07:07:06 +00006084 }
6085
6086 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00006087 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00006088 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006089 {
Alexey Bataev7292c292016-04-25 12:22:29 +00006090 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
6091 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00006092 Expr *RHS =
6093 (isOpenMPWorksharingDirective(DKind) ||
6094 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
6095 ? LB.get()
6096 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00006097 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006098 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006099
6100 if (isOpenMPLoopBoundSharingDirective(DKind)) {
6101 Expr *CombRHS =
6102 (isOpenMPWorksharingDirective(DKind) ||
6103 isOpenMPTaskLoopDirective(DKind) ||
6104 isOpenMPDistributeDirective(DKind))
6105 ? CombLB.get()
6106 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
6107 CombInit =
6108 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006109 CombInit =
6110 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006111 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006112 }
6113
Alexey Bataev316ccf62019-01-29 18:51:58 +00006114 bool UseStrictCompare =
6115 RealVType->hasUnsignedIntegerRepresentation() &&
6116 llvm::all_of(IterSpaces, [](const LoopIterationSpace &LIS) {
6117 return LIS.IsStrictCompare;
6118 });
6119 // Loop condition (IV < NumIterations) or (IV <= UB or IV < UB + 1 (for
6120 // unsigned IV)) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006121 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexey Bataev316ccf62019-01-29 18:51:58 +00006122 Expr *BoundUB = UB.get();
6123 if (UseStrictCompare) {
6124 BoundUB =
6125 SemaRef
6126 .BuildBinOp(CurScope, CondLoc, BO_Add, BoundUB,
6127 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
6128 .get();
6129 BoundUB =
6130 SemaRef.ActOnFinishFullExpr(BoundUB, /*DiscardedValue*/ false).get();
6131 }
Alexander Musmanc6388682014-12-15 07:07:06 +00006132 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006133 (isOpenMPWorksharingDirective(DKind) ||
6134 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexey Bataev316ccf62019-01-29 18:51:58 +00006135 ? SemaRef.BuildBinOp(CurScope, CondLoc,
6136 UseStrictCompare ? BO_LT : BO_LE, IV.get(),
6137 BoundUB)
Alexander Musmanc6388682014-12-15 07:07:06 +00006138 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
6139 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006140 ExprResult CombDistCond;
6141 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00006142 CombDistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
6143 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006144 }
6145
Carlo Bertolliffafe102017-04-20 00:39:39 +00006146 ExprResult CombCond;
6147 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00006148 Expr *BoundCombUB = CombUB.get();
6149 if (UseStrictCompare) {
6150 BoundCombUB =
6151 SemaRef
6152 .BuildBinOp(
6153 CurScope, CondLoc, BO_Add, BoundCombUB,
6154 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
6155 .get();
6156 BoundCombUB =
6157 SemaRef.ActOnFinishFullExpr(BoundCombUB, /*DiscardedValue*/ false)
6158 .get();
6159 }
Carlo Bertolliffafe102017-04-20 00:39:39 +00006160 CombCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00006161 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
6162 IV.get(), BoundCombUB);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006163 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006164 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006165 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006166 ExprResult Inc =
6167 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
6168 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
6169 if (!Inc.isUsable())
6170 return 0;
6171 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006172 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006173 if (!Inc.isUsable())
6174 return 0;
6175
6176 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
6177 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00006178 // In combined construct, add combined version that use CombLB and CombUB
6179 // base variables for the update
6180 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006181 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
6182 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00006183 // LB + ST
6184 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
6185 if (!NextLB.isUsable())
6186 return 0;
6187 // LB = LB + ST
6188 NextLB =
6189 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006190 NextLB =
6191 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006192 if (!NextLB.isUsable())
6193 return 0;
6194 // UB + ST
6195 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
6196 if (!NextUB.isUsable())
6197 return 0;
6198 // UB = UB + ST
6199 NextUB =
6200 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006201 NextUB =
6202 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00006203 if (!NextUB.isUsable())
6204 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00006205 if (isOpenMPLoopBoundSharingDirective(DKind)) {
6206 CombNextLB =
6207 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
6208 if (!NextLB.isUsable())
6209 return 0;
6210 // LB = LB + ST
6211 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
6212 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006213 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
6214 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006215 if (!CombNextLB.isUsable())
6216 return 0;
6217 // UB + ST
6218 CombNextUB =
6219 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
6220 if (!CombNextUB.isUsable())
6221 return 0;
6222 // UB = UB + ST
6223 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
6224 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006225 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
6226 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00006227 if (!CombNextUB.isUsable())
6228 return 0;
6229 }
Alexander Musmanc6388682014-12-15 07:07:06 +00006230 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00006231
Carlo Bertolliffafe102017-04-20 00:39:39 +00006232 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00006233 // directive with for as IV = IV + ST; ensure upper bound expression based
6234 // on PrevUB instead of NumIterations - used to implement 'for' when found
6235 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006236 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006237 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00006238 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Alexey Bataev316ccf62019-01-29 18:51:58 +00006239 DistCond = SemaRef.BuildBinOp(
6240 CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE, IV.get(), BoundUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00006241 assert(DistCond.isUsable() && "distribute cond expr was not built");
6242
6243 DistInc =
6244 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
6245 assert(DistInc.isUsable() && "distribute inc expr was not built");
6246 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
6247 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006248 DistInc =
6249 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00006250 assert(DistInc.isUsable() && "distribute inc expr was not built");
6251
6252 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
6253 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006254 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00006255 ExprResult IsUBGreater =
6256 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
6257 ExprResult CondOp = SemaRef.ActOnConditionalOp(
6258 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
6259 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
6260 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006261 PrevEUB =
6262 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006263
Alexey Bataev316ccf62019-01-29 18:51:58 +00006264 // Build IV <= PrevUB or IV < PrevUB + 1 for unsigned IV to be used in
6265 // parallel for is in combination with a distribute directive with
6266 // schedule(static, 1)
6267 Expr *BoundPrevUB = PrevUB.get();
6268 if (UseStrictCompare) {
6269 BoundPrevUB =
6270 SemaRef
6271 .BuildBinOp(
6272 CurScope, CondLoc, BO_Add, BoundPrevUB,
6273 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get())
6274 .get();
6275 BoundPrevUB =
6276 SemaRef.ActOnFinishFullExpr(BoundPrevUB, /*DiscardedValue*/ false)
6277 .get();
6278 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006279 ParForInDistCond =
Alexey Bataev316ccf62019-01-29 18:51:58 +00006280 SemaRef.BuildBinOp(CurScope, CondLoc, UseStrictCompare ? BO_LT : BO_LE,
6281 IV.get(), BoundPrevUB);
Carlo Bertolli8429d812017-02-17 21:29:13 +00006282 }
6283
Alexander Musmana5f070a2014-10-01 06:03:56 +00006284 // Build updates and final values of the loop counters.
6285 bool HasErrors = false;
6286 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006287 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006288 Built.Updates.resize(NestedLoopCount);
6289 Built.Finals.resize(NestedLoopCount);
6290 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00006291 // We implement the following algorithm for obtaining the
6292 // original loop iteration variable values based on the
6293 // value of the collapsed loop iteration variable IV.
6294 //
6295 // Let n+1 be the number of collapsed loops in the nest.
6296 // Iteration variables (I0, I1, .... In)
6297 // Iteration counts (N0, N1, ... Nn)
6298 //
6299 // Acc = IV;
6300 //
6301 // To compute Ik for loop k, 0 <= k <= n, generate:
6302 // Prod = N(k+1) * N(k+2) * ... * Nn;
6303 // Ik = Acc / Prod;
6304 // Acc -= Ik * Prod;
6305 //
6306 ExprResult Acc = IV;
6307 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00006308 LoopIterationSpace &IS = IterSpaces[Cnt];
6309 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006310 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006311
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00006312 // Compute prod
6313 ExprResult Prod =
6314 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
6315 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
6316 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
6317 IterSpaces[K].NumIterations);
6318
6319 // Iter = Acc / Prod
6320 // If there is at least one more inner loop to avoid
6321 // multiplication by 1.
6322 if (Cnt + 1 < NestedLoopCount)
6323 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
6324 Acc.get(), Prod.get());
6325 else
6326 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00006327 if (!Iter.isUsable()) {
6328 HasErrors = true;
6329 break;
6330 }
6331
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00006332 // Update Acc:
6333 // Acc -= Iter * Prod
6334 // Check if there is at least one more inner loop to avoid
6335 // multiplication by 1.
6336 if (Cnt + 1 < NestedLoopCount)
6337 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
6338 Iter.get(), Prod.get());
6339 else
6340 Prod = Iter;
6341 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
6342 Acc.get(), Prod.get());
6343
Alexey Bataev39f915b82015-05-08 10:41:21 +00006344 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006345 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00006346 DeclRefExpr *CounterVar = buildDeclRefExpr(
6347 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
6348 /*RefersToCapture=*/true);
6349 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00006350 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006351 if (!Init.isUsable()) {
6352 HasErrors = true;
6353 break;
6354 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006355 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00006356 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
6357 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006358 if (!Update.isUsable()) {
6359 HasErrors = true;
6360 break;
6361 }
6362
6363 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataeve3727102018-04-18 15:57:46 +00006364 ExprResult Final = buildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00006365 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00006366 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006367 if (!Final.isUsable()) {
6368 HasErrors = true;
6369 break;
6370 }
6371
Alexander Musmana5f070a2014-10-01 06:03:56 +00006372 if (!Update.isUsable() || !Final.isUsable()) {
6373 HasErrors = true;
6374 break;
6375 }
6376 // Save results
6377 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00006378 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00006379 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006380 Built.Updates[Cnt] = Update.get();
6381 Built.Finals[Cnt] = Final.get();
6382 }
6383 }
6384
6385 if (HasErrors)
6386 return 0;
6387
6388 // Save results
6389 Built.IterationVarRef = IV.get();
6390 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00006391 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00006392 Built.CalcLastIteration = SemaRef
6393 .ActOnFinishFullExpr(CalcLastIteration.get(),
6394 /*DiscardedValue*/ false)
6395 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006396 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00006397 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00006398 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006399 Built.Init = Init.get();
6400 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00006401 Built.LB = LB.get();
6402 Built.UB = UB.get();
6403 Built.IL = IL.get();
6404 Built.ST = ST.get();
6405 Built.EUB = EUB.get();
6406 Built.NLB = NextLB.get();
6407 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00006408 Built.PrevLB = PrevLB.get();
6409 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00006410 Built.DistInc = DistInc.get();
6411 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00006412 Built.DistCombinedFields.LB = CombLB.get();
6413 Built.DistCombinedFields.UB = CombUB.get();
6414 Built.DistCombinedFields.EUB = CombEUB.get();
6415 Built.DistCombinedFields.Init = CombInit.get();
6416 Built.DistCombinedFields.Cond = CombCond.get();
6417 Built.DistCombinedFields.NLB = CombNextLB.get();
6418 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00006419 Built.DistCombinedFields.DistCond = CombDistCond.get();
6420 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006421
Alexey Bataevabfc0692014-06-25 06:52:00 +00006422 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00006423}
6424
Alexey Bataev10e775f2015-07-30 11:36:16 +00006425static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006426 auto CollapseClauses =
6427 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
6428 if (CollapseClauses.begin() != CollapseClauses.end())
6429 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00006430 return nullptr;
6431}
6432
Alexey Bataev10e775f2015-07-30 11:36:16 +00006433static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00006434 auto OrderedClauses =
6435 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
6436 if (OrderedClauses.begin() != OrderedClauses.end())
6437 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00006438 return nullptr;
6439}
6440
Kelvin Lic5609492016-07-15 04:39:07 +00006441static bool checkSimdlenSafelenSpecified(Sema &S,
6442 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006443 const OMPSafelenClause *Safelen = nullptr;
6444 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00006445
Alexey Bataeve3727102018-04-18 15:57:46 +00006446 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00006447 if (Clause->getClauseKind() == OMPC_safelen)
6448 Safelen = cast<OMPSafelenClause>(Clause);
6449 else if (Clause->getClauseKind() == OMPC_simdlen)
6450 Simdlen = cast<OMPSimdlenClause>(Clause);
6451 if (Safelen && Simdlen)
6452 break;
6453 }
6454
6455 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006456 const Expr *SimdlenLength = Simdlen->getSimdlen();
6457 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00006458 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
6459 SimdlenLength->isInstantiationDependent() ||
6460 SimdlenLength->containsUnexpandedParameterPack())
6461 return false;
6462 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
6463 SafelenLength->isInstantiationDependent() ||
6464 SafelenLength->containsUnexpandedParameterPack())
6465 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00006466 Expr::EvalResult SimdlenResult, SafelenResult;
6467 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
6468 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
6469 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
6470 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00006471 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
6472 // If both simdlen and safelen clauses are specified, the value of the
6473 // simdlen parameter must be less than or equal to the value of the safelen
6474 // parameter.
6475 if (SimdlenRes > SafelenRes) {
6476 S.Diag(SimdlenLength->getExprLoc(),
6477 diag::err_omp_wrong_simdlen_safelen_values)
6478 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
6479 return true;
6480 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00006481 }
6482 return false;
6483}
6484
Alexey Bataeve3727102018-04-18 15:57:46 +00006485StmtResult
6486Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6487 SourceLocation StartLoc, SourceLocation EndLoc,
6488 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006489 if (!AStmt)
6490 return StmtError();
6491
6492 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006493 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006494 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6495 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006496 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006497 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6498 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006499 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006500 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006501
Alexander Musmana5f070a2014-10-01 06:03:56 +00006502 assert((CurContext->isDependentContext() || B.builtAll()) &&
6503 "omp simd loop exprs were not built");
6504
Alexander Musman3276a272015-03-21 10:12:56 +00006505 if (!CurContext->isDependentContext()) {
6506 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006507 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006508 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00006509 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006510 B.NumIterations, *this, CurScope,
6511 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00006512 return StmtError();
6513 }
6514 }
6515
Kelvin Lic5609492016-07-15 04:39:07 +00006516 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006517 return StmtError();
6518
Reid Kleckner87a31802018-03-12 21:43:02 +00006519 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006520 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6521 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00006522}
6523
Alexey Bataeve3727102018-04-18 15:57:46 +00006524StmtResult
6525Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
6526 SourceLocation StartLoc, SourceLocation EndLoc,
6527 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006528 if (!AStmt)
6529 return StmtError();
6530
6531 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006532 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006533 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6534 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00006535 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00006536 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
6537 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00006538 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00006539 return StmtError();
6540
Alexander Musmana5f070a2014-10-01 06:03:56 +00006541 assert((CurContext->isDependentContext() || B.builtAll()) &&
6542 "omp for loop exprs were not built");
6543
Alexey Bataev54acd402015-08-04 11:18:19 +00006544 if (!CurContext->isDependentContext()) {
6545 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006546 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006547 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006548 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006549 B.NumIterations, *this, CurScope,
6550 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006551 return StmtError();
6552 }
6553 }
6554
Reid Kleckner87a31802018-03-12 21:43:02 +00006555 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006556 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006557 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00006558}
6559
Alexander Musmanf82886e2014-09-18 05:12:34 +00006560StmtResult Sema::ActOnOpenMPForSimdDirective(
6561 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006562 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006563 if (!AStmt)
6564 return StmtError();
6565
6566 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00006567 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006568 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6569 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00006570 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006571 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006572 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6573 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006574 if (NestedLoopCount == 0)
6575 return StmtError();
6576
Alexander Musmanc6388682014-12-15 07:07:06 +00006577 assert((CurContext->isDependentContext() || B.builtAll()) &&
6578 "omp for simd loop exprs were not built");
6579
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006580 if (!CurContext->isDependentContext()) {
6581 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006582 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006583 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006584 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006585 B.NumIterations, *this, CurScope,
6586 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00006587 return StmtError();
6588 }
6589 }
6590
Kelvin Lic5609492016-07-15 04:39:07 +00006591 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006592 return StmtError();
6593
Reid Kleckner87a31802018-03-12 21:43:02 +00006594 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006595 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
6596 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00006597}
6598
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006599StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
6600 Stmt *AStmt,
6601 SourceLocation StartLoc,
6602 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006603 if (!AStmt)
6604 return StmtError();
6605
6606 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006607 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006608 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006609 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006610 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006611 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006612 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006613 return StmtError();
6614 // All associated statements must be '#pragma omp section' except for
6615 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006616 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006617 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6618 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006619 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006620 diag::err_omp_sections_substmt_not_section);
6621 return StmtError();
6622 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006623 cast<OMPSectionDirective>(SectionStmt)
6624 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006625 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006626 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006627 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006628 return StmtError();
6629 }
6630
Reid Kleckner87a31802018-03-12 21:43:02 +00006631 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006632
Alexey Bataev25e5b442015-09-15 12:52:43 +00006633 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6634 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00006635}
6636
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006637StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
6638 SourceLocation StartLoc,
6639 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006640 if (!AStmt)
6641 return StmtError();
6642
6643 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006644
Reid Kleckner87a31802018-03-12 21:43:02 +00006645 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00006646 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006647
Alexey Bataev25e5b442015-09-15 12:52:43 +00006648 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
6649 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00006650}
6651
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006652StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
6653 Stmt *AStmt,
6654 SourceLocation StartLoc,
6655 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006656 if (!AStmt)
6657 return StmtError();
6658
6659 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00006660
Reid Kleckner87a31802018-03-12 21:43:02 +00006661 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00006662
Alexey Bataev3255bf32015-01-19 05:20:46 +00006663 // OpenMP [2.7.3, single Construct, Restrictions]
6664 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00006665 const OMPClause *Nowait = nullptr;
6666 const OMPClause *Copyprivate = nullptr;
6667 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00006668 if (Clause->getClauseKind() == OMPC_nowait)
6669 Nowait = Clause;
6670 else if (Clause->getClauseKind() == OMPC_copyprivate)
6671 Copyprivate = Clause;
6672 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006673 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00006674 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006675 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00006676 return StmtError();
6677 }
6678 }
6679
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00006680 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6681}
6682
Alexander Musman80c22892014-07-17 08:54:58 +00006683StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
6684 SourceLocation StartLoc,
6685 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006686 if (!AStmt)
6687 return StmtError();
6688
6689 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00006690
Reid Kleckner87a31802018-03-12 21:43:02 +00006691 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00006692
6693 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
6694}
6695
Alexey Bataev28c75412015-12-15 08:19:24 +00006696StmtResult Sema::ActOnOpenMPCriticalDirective(
6697 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
6698 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006699 if (!AStmt)
6700 return StmtError();
6701
6702 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006703
Alexey Bataev28c75412015-12-15 08:19:24 +00006704 bool ErrorFound = false;
6705 llvm::APSInt Hint;
6706 SourceLocation HintLoc;
6707 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006708 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006709 if (C->getClauseKind() == OMPC_hint) {
6710 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006711 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00006712 ErrorFound = true;
6713 }
6714 Expr *E = cast<OMPHintClause>(C)->getHint();
6715 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00006716 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006717 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006718 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00006719 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006720 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00006721 }
6722 }
6723 }
6724 if (ErrorFound)
6725 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006726 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00006727 if (Pair.first && DirName.getName() && !DependentHint) {
6728 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6729 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00006730 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00006731 Diag(HintLoc, diag::note_omp_critical_hint_here)
6732 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006733 else
Alexey Bataev28c75412015-12-15 08:19:24 +00006734 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00006735 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006736 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00006737 << 1
6738 << C->getHint()->EvaluateKnownConstInt(Context).toString(
6739 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006740 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006741 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00006742 }
Alexey Bataev28c75412015-12-15 08:19:24 +00006743 }
6744 }
6745
Reid Kleckner87a31802018-03-12 21:43:02 +00006746 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006747
Alexey Bataev28c75412015-12-15 08:19:24 +00006748 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6749 Clauses, AStmt);
6750 if (!Pair.first && DirName.getName() && !DependentHint)
6751 DSAStack->addCriticalWithHint(Dir, Hint);
6752 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006753}
6754
Alexey Bataev4acb8592014-07-07 13:01:15 +00006755StmtResult Sema::ActOnOpenMPParallelForDirective(
6756 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006757 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006758 if (!AStmt)
6759 return StmtError();
6760
Alexey Bataeve3727102018-04-18 15:57:46 +00006761 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006762 // 1.2.2 OpenMP Language Terminology
6763 // Structured block - An executable statement with a single entry at the
6764 // top and a single exit at the bottom.
6765 // The point of exit cannot be a branch out of the structured block.
6766 // longjmp() and throw() must not violate the entry/exit criteria.
6767 CS->getCapturedDecl()->setNothrow();
6768
Alexander Musmanc6388682014-12-15 07:07:06 +00006769 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006770 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6771 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006772 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006773 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006774 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6775 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006776 if (NestedLoopCount == 0)
6777 return StmtError();
6778
Alexander Musmana5f070a2014-10-01 06:03:56 +00006779 assert((CurContext->isDependentContext() || B.builtAll()) &&
6780 "omp parallel for loop exprs were not built");
6781
Alexey Bataev54acd402015-08-04 11:18:19 +00006782 if (!CurContext->isDependentContext()) {
6783 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006784 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006785 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006786 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006787 B.NumIterations, *this, CurScope,
6788 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006789 return StmtError();
6790 }
6791 }
6792
Reid Kleckner87a31802018-03-12 21:43:02 +00006793 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006794 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006795 NestedLoopCount, Clauses, AStmt, B,
6796 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00006797}
6798
Alexander Musmane4e893b2014-09-23 09:33:00 +00006799StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6800 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006801 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006802 if (!AStmt)
6803 return StmtError();
6804
Alexey Bataeve3727102018-04-18 15:57:46 +00006805 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006806 // 1.2.2 OpenMP Language Terminology
6807 // Structured block - An executable statement with a single entry at the
6808 // top and a single exit at the bottom.
6809 // The point of exit cannot be a branch out of the structured block.
6810 // longjmp() and throw() must not violate the entry/exit criteria.
6811 CS->getCapturedDecl()->setNothrow();
6812
Alexander Musmanc6388682014-12-15 07:07:06 +00006813 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006814 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6815 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00006816 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006817 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006818 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6819 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006820 if (NestedLoopCount == 0)
6821 return StmtError();
6822
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006823 if (!CurContext->isDependentContext()) {
6824 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006825 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006826 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006827 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006828 B.NumIterations, *this, CurScope,
6829 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006830 return StmtError();
6831 }
6832 }
6833
Kelvin Lic5609492016-07-15 04:39:07 +00006834 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006835 return StmtError();
6836
Reid Kleckner87a31802018-03-12 21:43:02 +00006837 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006838 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00006839 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006840}
6841
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006842StmtResult
6843Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6844 Stmt *AStmt, SourceLocation StartLoc,
6845 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006846 if (!AStmt)
6847 return StmtError();
6848
6849 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006850 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006851 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006852 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006853 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006854 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006855 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006856 return StmtError();
6857 // All associated statements must be '#pragma omp section' except for
6858 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006859 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006860 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6861 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006862 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006863 diag::err_omp_parallel_sections_substmt_not_section);
6864 return StmtError();
6865 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006866 cast<OMPSectionDirective>(SectionStmt)
6867 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006868 }
6869 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006870 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006871 diag::err_omp_parallel_sections_not_compound_stmt);
6872 return StmtError();
6873 }
6874
Reid Kleckner87a31802018-03-12 21:43:02 +00006875 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006876
Alexey Bataev25e5b442015-09-15 12:52:43 +00006877 return OMPParallelSectionsDirective::Create(
6878 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006879}
6880
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006881StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6882 Stmt *AStmt, SourceLocation StartLoc,
6883 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006884 if (!AStmt)
6885 return StmtError();
6886
David Majnemer9d168222016-08-05 17:44:54 +00006887 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006888 // 1.2.2 OpenMP Language Terminology
6889 // Structured block - An executable statement with a single entry at the
6890 // top and a single exit at the bottom.
6891 // The point of exit cannot be a branch out of the structured block.
6892 // longjmp() and throw() must not violate the entry/exit criteria.
6893 CS->getCapturedDecl()->setNothrow();
6894
Reid Kleckner87a31802018-03-12 21:43:02 +00006895 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006896
Alexey Bataev25e5b442015-09-15 12:52:43 +00006897 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6898 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006899}
6900
Alexey Bataev68446b72014-07-18 07:47:19 +00006901StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6902 SourceLocation EndLoc) {
6903 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6904}
6905
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00006906StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6907 SourceLocation EndLoc) {
6908 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6909}
6910
Alexey Bataev2df347a2014-07-18 10:17:07 +00006911StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6912 SourceLocation EndLoc) {
6913 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6914}
6915
Alexey Bataev169d96a2017-07-18 20:17:46 +00006916StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6917 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006918 SourceLocation StartLoc,
6919 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006920 if (!AStmt)
6921 return StmtError();
6922
6923 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006924
Reid Kleckner87a31802018-03-12 21:43:02 +00006925 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006926
Alexey Bataev169d96a2017-07-18 20:17:46 +00006927 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00006928 AStmt,
6929 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006930}
6931
Alexey Bataev6125da92014-07-21 11:26:11 +00006932StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6933 SourceLocation StartLoc,
6934 SourceLocation EndLoc) {
6935 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6936 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6937}
6938
Alexey Bataev346265e2015-09-25 10:37:12 +00006939StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6940 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006941 SourceLocation StartLoc,
6942 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006943 const OMPClause *DependFound = nullptr;
6944 const OMPClause *DependSourceClause = nullptr;
6945 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00006946 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006947 const OMPThreadsClause *TC = nullptr;
6948 const OMPSIMDClause *SC = nullptr;
6949 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00006950 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6951 DependFound = C;
6952 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6953 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006954 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00006955 << getOpenMPDirectiveName(OMPD_ordered)
6956 << getOpenMPClauseName(OMPC_depend) << 2;
6957 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006958 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00006959 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00006960 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006961 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006962 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006963 << 0;
6964 ErrorFound = true;
6965 }
6966 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6967 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006968 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006969 << 1;
6970 ErrorFound = true;
6971 }
6972 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00006973 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006974 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00006975 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006976 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006977 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006978 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006979 }
Alexey Bataeveb482352015-12-18 05:05:56 +00006980 if (!ErrorFound && !SC &&
6981 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006982 // OpenMP [2.8.1,simd Construct, Restrictions]
6983 // An ordered construct with the simd clause is the only OpenMP construct
6984 // that can appear in the simd region.
6985 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00006986 ErrorFound = true;
6987 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006988 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00006989 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6990 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006991 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006992 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00006993 diag::err_omp_ordered_directive_without_param);
6994 ErrorFound = true;
6995 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006996 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006997 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00006998 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6999 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007000 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00007001 ErrorFound = true;
7002 }
7003 }
7004 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007005 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00007006
7007 if (AStmt) {
7008 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7009
Reid Kleckner87a31802018-03-12 21:43:02 +00007010 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007011 }
Alexey Bataev346265e2015-09-25 10:37:12 +00007012
7013 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00007014}
7015
Alexey Bataev1d160b12015-03-13 12:27:31 +00007016namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007017/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00007018/// construct.
7019class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007020 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007021 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007022 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007023 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007024 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007025 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007026 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007027 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007028 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007029 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007030 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007031 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007032 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007033 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007034 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00007035 /// expression.
7036 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007037 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00007038 /// part.
7039 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007040 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007041 NoError
7042 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007043 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007044 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007045 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00007046 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007047 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007048 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007049 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007050 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007051 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00007052 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
7053 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
7054 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007055 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00007056 /// important for non-associative operations.
7057 bool IsXLHSInRHSPart;
7058 BinaryOperatorKind Op;
7059 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007060 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00007061 /// if it is a prefix unary operation.
7062 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007063
7064public:
7065 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00007066 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00007067 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007068 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00007069 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00007070 /// expression. If DiagId and NoteId == 0, then only check is performed
7071 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007072 /// \param DiagId Diagnostic which should be emitted if error is found.
7073 /// \param NoteId Diagnostic note for the main error message.
7074 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00007075 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007076 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007077 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007078 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00007079 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007080 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00007081 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
7082 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
7083 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007084 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00007085 /// false otherwise.
7086 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
7087
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00007088 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00007089 /// if it is a prefix unary operation.
7090 bool isPostfixUpdate() const { return IsPostfixUpdate; }
7091
Alexey Bataev1d160b12015-03-13 12:27:31 +00007092private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00007093 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
7094 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00007095};
7096} // namespace
7097
7098bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
7099 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
7100 ExprAnalysisErrorCode ErrorFound = NoError;
7101 SourceLocation ErrorLoc, NoteLoc;
7102 SourceRange ErrorRange, NoteRange;
7103 // Allowed constructs are:
7104 // x = x binop expr;
7105 // x = expr binop x;
7106 if (AtomicBinOp->getOpcode() == BO_Assign) {
7107 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00007108 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00007109 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
7110 if (AtomicInnerBinOp->isMultiplicativeOp() ||
7111 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
7112 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00007113 Op = AtomicInnerBinOp->getOpcode();
7114 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00007115 Expr *LHS = AtomicInnerBinOp->getLHS();
7116 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007117 llvm::FoldingSetNodeID XId, LHSId, RHSId;
7118 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
7119 /*Canonical=*/true);
7120 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
7121 /*Canonical=*/true);
7122 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
7123 /*Canonical=*/true);
7124 if (XId == LHSId) {
7125 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00007126 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007127 } else if (XId == RHSId) {
7128 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00007129 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007130 } else {
7131 ErrorLoc = AtomicInnerBinOp->getExprLoc();
7132 ErrorRange = AtomicInnerBinOp->getSourceRange();
7133 NoteLoc = X->getExprLoc();
7134 NoteRange = X->getSourceRange();
7135 ErrorFound = NotAnUpdateExpression;
7136 }
7137 } else {
7138 ErrorLoc = AtomicInnerBinOp->getExprLoc();
7139 ErrorRange = AtomicInnerBinOp->getSourceRange();
7140 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
7141 NoteRange = SourceRange(NoteLoc, NoteLoc);
7142 ErrorFound = NotABinaryOperator;
7143 }
7144 } else {
7145 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
7146 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
7147 ErrorFound = NotABinaryExpression;
7148 }
7149 } else {
7150 ErrorLoc = AtomicBinOp->getExprLoc();
7151 ErrorRange = AtomicBinOp->getSourceRange();
7152 NoteLoc = AtomicBinOp->getOperatorLoc();
7153 NoteRange = SourceRange(NoteLoc, NoteLoc);
7154 ErrorFound = NotAnAssignmentOp;
7155 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007156 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007157 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
7158 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
7159 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007160 }
7161 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00007162 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00007163 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007164}
7165
7166bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
7167 unsigned NoteId) {
7168 ExprAnalysisErrorCode ErrorFound = NoError;
7169 SourceLocation ErrorLoc, NoteLoc;
7170 SourceRange ErrorRange, NoteRange;
7171 // Allowed constructs are:
7172 // x++;
7173 // x--;
7174 // ++x;
7175 // --x;
7176 // x binop= expr;
7177 // x = x binop expr;
7178 // x = expr binop x;
7179 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
7180 AtomicBody = AtomicBody->IgnoreParenImpCasts();
7181 if (AtomicBody->getType()->isScalarType() ||
7182 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007183 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00007184 AtomicBody->IgnoreParenImpCasts())) {
7185 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00007186 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00007187 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00007188 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007189 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00007190 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007191 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007192 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
7193 AtomicBody->IgnoreParenImpCasts())) {
7194 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00007195 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00007196 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007197 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00007198 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007199 // Check for Unary Operation
7200 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007201 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007202 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
7203 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00007204 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007205 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
7206 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007207 } else {
7208 ErrorFound = NotAnUnaryIncDecExpression;
7209 ErrorLoc = AtomicUnaryOp->getExprLoc();
7210 ErrorRange = AtomicUnaryOp->getSourceRange();
7211 NoteLoc = AtomicUnaryOp->getOperatorLoc();
7212 NoteRange = SourceRange(NoteLoc, NoteLoc);
7213 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007214 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007215 ErrorFound = NotABinaryOrUnaryExpression;
7216 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
7217 NoteRange = ErrorRange = AtomicBody->getSourceRange();
7218 }
7219 } else {
7220 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007221 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007222 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7223 }
7224 } else {
7225 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007226 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007227 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
7228 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007229 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007230 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
7231 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
7232 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007233 }
7234 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00007235 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00007236 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00007237 // Build an update expression of form 'OpaqueValueExpr(x) binop
7238 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
7239 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
7240 auto *OVEX = new (SemaRef.getASTContext())
7241 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
7242 auto *OVEExpr = new (SemaRef.getASTContext())
7243 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00007244 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00007245 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
7246 IsXLHSInRHSPart ? OVEExpr : OVEX);
7247 if (Update.isInvalid())
7248 return true;
7249 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
7250 Sema::AA_Casting);
7251 if (Update.isInvalid())
7252 return true;
7253 UpdateExpr = Update.get();
7254 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00007255 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00007256}
7257
Alexey Bataev0162e452014-07-22 10:10:35 +00007258StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
7259 Stmt *AStmt,
7260 SourceLocation StartLoc,
7261 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007262 if (!AStmt)
7263 return StmtError();
7264
David Majnemer9d168222016-08-05 17:44:54 +00007265 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00007266 // 1.2.2 OpenMP Language Terminology
7267 // Structured block - An executable statement with a single entry at the
7268 // top and a single exit at the bottom.
7269 // The point of exit cannot be a branch out of the structured block.
7270 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00007271 OpenMPClauseKind AtomicKind = OMPC_unknown;
7272 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00007273 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00007274 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00007275 C->getClauseKind() == OMPC_update ||
7276 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00007277 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007278 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007279 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00007280 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
7281 << getOpenMPClauseName(AtomicKind);
7282 } else {
7283 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007284 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007285 }
7286 }
7287 }
Alexey Bataev62cec442014-11-18 10:14:22 +00007288
Alexey Bataeve3727102018-04-18 15:57:46 +00007289 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00007290 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
7291 Body = EWC->getSubExpr();
7292
Alexey Bataev62cec442014-11-18 10:14:22 +00007293 Expr *X = nullptr;
7294 Expr *V = nullptr;
7295 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00007296 Expr *UE = nullptr;
7297 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007298 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00007299 // OpenMP [2.12.6, atomic Construct]
7300 // In the next expressions:
7301 // * x and v (as applicable) are both l-value expressions with scalar type.
7302 // * During the execution of an atomic region, multiple syntactic
7303 // occurrences of x must designate the same storage location.
7304 // * Neither of v and expr (as applicable) may access the storage location
7305 // designated by x.
7306 // * Neither of x and expr (as applicable) may access the storage location
7307 // designated by v.
7308 // * expr is an expression with scalar type.
7309 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
7310 // * binop, binop=, ++, and -- are not overloaded operators.
7311 // * The expression x binop expr must be numerically equivalent to x binop
7312 // (expr). This requirement is satisfied if the operators in expr have
7313 // precedence greater than binop, or by using parentheses around expr or
7314 // subexpressions of expr.
7315 // * The expression expr binop x must be numerically equivalent to (expr)
7316 // binop x. This requirement is satisfied if the operators in expr have
7317 // precedence equal to or greater than binop, or by using parentheses around
7318 // expr or subexpressions of expr.
7319 // * For forms that allow multiple occurrences of x, the number of times
7320 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00007321 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007322 enum {
7323 NotAnExpression,
7324 NotAnAssignmentOp,
7325 NotAScalarType,
7326 NotAnLValue,
7327 NoError
7328 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00007329 SourceLocation ErrorLoc, NoteLoc;
7330 SourceRange ErrorRange, NoteRange;
7331 // If clause is read:
7332 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00007333 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7334 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00007335 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7336 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7337 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7338 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
7339 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7340 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
7341 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007342 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00007343 ErrorFound = NotAnLValue;
7344 ErrorLoc = AtomicBinOp->getExprLoc();
7345 ErrorRange = AtomicBinOp->getSourceRange();
7346 NoteLoc = NotLValueExpr->getExprLoc();
7347 NoteRange = NotLValueExpr->getSourceRange();
7348 }
7349 } else if (!X->isInstantiationDependent() ||
7350 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007351 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00007352 (X->isInstantiationDependent() || X->getType()->isScalarType())
7353 ? V
7354 : X;
7355 ErrorFound = NotAScalarType;
7356 ErrorLoc = AtomicBinOp->getExprLoc();
7357 ErrorRange = AtomicBinOp->getSourceRange();
7358 NoteLoc = NotScalarExpr->getExprLoc();
7359 NoteRange = NotScalarExpr->getSourceRange();
7360 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007361 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00007362 ErrorFound = NotAnAssignmentOp;
7363 ErrorLoc = AtomicBody->getExprLoc();
7364 ErrorRange = AtomicBody->getSourceRange();
7365 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7366 : AtomicBody->getExprLoc();
7367 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7368 : AtomicBody->getSourceRange();
7369 }
7370 } else {
7371 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007372 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00007373 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00007374 }
Alexey Bataev62cec442014-11-18 10:14:22 +00007375 if (ErrorFound != NoError) {
7376 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
7377 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00007378 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7379 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00007380 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007381 }
7382 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00007383 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00007384 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007385 enum {
7386 NotAnExpression,
7387 NotAnAssignmentOp,
7388 NotAScalarType,
7389 NotAnLValue,
7390 NoError
7391 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00007392 SourceLocation ErrorLoc, NoteLoc;
7393 SourceRange ErrorRange, NoteRange;
7394 // If clause is write:
7395 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00007396 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
7397 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007398 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7399 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00007400 X = AtomicBinOp->getLHS();
7401 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007402 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
7403 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
7404 if (!X->isLValue()) {
7405 ErrorFound = NotAnLValue;
7406 ErrorLoc = AtomicBinOp->getExprLoc();
7407 ErrorRange = AtomicBinOp->getSourceRange();
7408 NoteLoc = X->getExprLoc();
7409 NoteRange = X->getSourceRange();
7410 }
7411 } else if (!X->isInstantiationDependent() ||
7412 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007413 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00007414 (X->isInstantiationDependent() || X->getType()->isScalarType())
7415 ? E
7416 : X;
7417 ErrorFound = NotAScalarType;
7418 ErrorLoc = AtomicBinOp->getExprLoc();
7419 ErrorRange = AtomicBinOp->getSourceRange();
7420 NoteLoc = NotScalarExpr->getExprLoc();
7421 NoteRange = NotScalarExpr->getSourceRange();
7422 }
Alexey Bataev5a195472015-09-04 12:55:50 +00007423 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00007424 ErrorFound = NotAnAssignmentOp;
7425 ErrorLoc = AtomicBody->getExprLoc();
7426 ErrorRange = AtomicBody->getSourceRange();
7427 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7428 : AtomicBody->getExprLoc();
7429 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7430 : AtomicBody->getSourceRange();
7431 }
7432 } else {
7433 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007434 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00007435 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00007436 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00007437 if (ErrorFound != NoError) {
7438 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
7439 << ErrorRange;
7440 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
7441 << NoteRange;
7442 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00007443 }
7444 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00007445 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00007446 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00007447 // If clause is update:
7448 // x++;
7449 // x--;
7450 // ++x;
7451 // --x;
7452 // x binop= expr;
7453 // x = x binop expr;
7454 // x = expr binop x;
7455 OpenMPAtomicUpdateChecker Checker(*this);
7456 if (Checker.checkStatement(
7457 Body, (AtomicKind == OMPC_update)
7458 ? diag::err_omp_atomic_update_not_expression_statement
7459 : diag::err_omp_atomic_not_expression_statement,
7460 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00007461 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00007462 if (!CurContext->isDependentContext()) {
7463 E = Checker.getExpr();
7464 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00007465 UE = Checker.getUpdateExpr();
7466 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00007467 }
Alexey Bataev459dec02014-07-24 06:46:57 +00007468 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007469 enum {
7470 NotAnAssignmentOp,
7471 NotACompoundStatement,
7472 NotTwoSubstatements,
7473 NotASpecificExpression,
7474 NoError
7475 } ErrorFound = NoError;
7476 SourceLocation ErrorLoc, NoteLoc;
7477 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00007478 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007479 // If clause is a capture:
7480 // v = x++;
7481 // v = x--;
7482 // v = ++x;
7483 // v = --x;
7484 // v = x binop= expr;
7485 // v = x = x binop expr;
7486 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00007487 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00007488 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
7489 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
7490 V = AtomicBinOp->getLHS();
7491 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
7492 OpenMPAtomicUpdateChecker Checker(*this);
7493 if (Checker.checkStatement(
7494 Body, diag::err_omp_atomic_capture_not_expression_statement,
7495 diag::note_omp_atomic_update))
7496 return StmtError();
7497 E = Checker.getExpr();
7498 X = Checker.getX();
7499 UE = Checker.getUpdateExpr();
7500 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
7501 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00007502 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007503 ErrorLoc = AtomicBody->getExprLoc();
7504 ErrorRange = AtomicBody->getSourceRange();
7505 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
7506 : AtomicBody->getExprLoc();
7507 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
7508 : AtomicBody->getSourceRange();
7509 ErrorFound = NotAnAssignmentOp;
7510 }
7511 if (ErrorFound != NoError) {
7512 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
7513 << ErrorRange;
7514 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7515 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007516 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007517 if (CurContext->isDependentContext())
7518 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007519 } else {
7520 // If clause is a capture:
7521 // { v = x; x = expr; }
7522 // { v = x; x++; }
7523 // { v = x; x--; }
7524 // { v = x; ++x; }
7525 // { v = x; --x; }
7526 // { v = x; x binop= expr; }
7527 // { v = x; x = x binop expr; }
7528 // { v = x; x = expr binop x; }
7529 // { x++; v = x; }
7530 // { x--; v = x; }
7531 // { ++x; v = x; }
7532 // { --x; v = x; }
7533 // { x binop= expr; v = x; }
7534 // { x = x binop expr; v = x; }
7535 // { x = expr binop x; v = x; }
7536 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
7537 // Check that this is { expr1; expr2; }
7538 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007539 Stmt *First = CS->body_front();
7540 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007541 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
7542 First = EWC->getSubExpr()->IgnoreParenImpCasts();
7543 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
7544 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
7545 // Need to find what subexpression is 'v' and what is 'x'.
7546 OpenMPAtomicUpdateChecker Checker(*this);
7547 bool IsUpdateExprFound = !Checker.checkStatement(Second);
7548 BinaryOperator *BinOp = nullptr;
7549 if (IsUpdateExprFound) {
7550 BinOp = dyn_cast<BinaryOperator>(First);
7551 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7552 }
7553 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7554 // { v = x; x++; }
7555 // { v = x; x--; }
7556 // { v = x; ++x; }
7557 // { v = x; --x; }
7558 // { v = x; x binop= expr; }
7559 // { v = x; x = x binop expr; }
7560 // { v = x; x = expr binop x; }
7561 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007562 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007563 llvm::FoldingSetNodeID XId, PossibleXId;
7564 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7565 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7566 IsUpdateExprFound = XId == PossibleXId;
7567 if (IsUpdateExprFound) {
7568 V = BinOp->getLHS();
7569 X = Checker.getX();
7570 E = Checker.getExpr();
7571 UE = Checker.getUpdateExpr();
7572 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007573 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007574 }
7575 }
7576 if (!IsUpdateExprFound) {
7577 IsUpdateExprFound = !Checker.checkStatement(First);
7578 BinOp = nullptr;
7579 if (IsUpdateExprFound) {
7580 BinOp = dyn_cast<BinaryOperator>(Second);
7581 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
7582 }
7583 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
7584 // { x++; v = x; }
7585 // { x--; v = x; }
7586 // { ++x; v = x; }
7587 // { --x; v = x; }
7588 // { x binop= expr; v = x; }
7589 // { x = x binop expr; v = x; }
7590 // { x = expr binop x; v = x; }
7591 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00007592 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007593 llvm::FoldingSetNodeID XId, PossibleXId;
7594 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
7595 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
7596 IsUpdateExprFound = XId == PossibleXId;
7597 if (IsUpdateExprFound) {
7598 V = BinOp->getLHS();
7599 X = Checker.getX();
7600 E = Checker.getExpr();
7601 UE = Checker.getUpdateExpr();
7602 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00007603 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00007604 }
7605 }
7606 }
7607 if (!IsUpdateExprFound) {
7608 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00007609 auto *FirstExpr = dyn_cast<Expr>(First);
7610 auto *SecondExpr = dyn_cast<Expr>(Second);
7611 if (!FirstExpr || !SecondExpr ||
7612 !(FirstExpr->isInstantiationDependent() ||
7613 SecondExpr->isInstantiationDependent())) {
7614 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
7615 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00007616 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00007617 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007618 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007619 NoteRange = ErrorRange = FirstBinOp
7620 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00007621 : SourceRange(ErrorLoc, ErrorLoc);
7622 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00007623 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
7624 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
7625 ErrorFound = NotAnAssignmentOp;
7626 NoteLoc = ErrorLoc = SecondBinOp
7627 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007628 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00007629 NoteRange = ErrorRange =
7630 SecondBinOp ? SecondBinOp->getSourceRange()
7631 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00007632 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007633 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00007634 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00007635 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00007636 SecondBinOp->getLHS()->IgnoreParenImpCasts();
7637 llvm::FoldingSetNodeID X1Id, X2Id;
7638 PossibleXRHSInFirst->Profile(X1Id, Context,
7639 /*Canonical=*/true);
7640 PossibleXLHSInSecond->Profile(X2Id, Context,
7641 /*Canonical=*/true);
7642 IsUpdateExprFound = X1Id == X2Id;
7643 if (IsUpdateExprFound) {
7644 V = FirstBinOp->getLHS();
7645 X = SecondBinOp->getLHS();
7646 E = SecondBinOp->getRHS();
7647 UE = nullptr;
7648 IsXLHSInRHSPart = false;
7649 IsPostfixUpdate = true;
7650 } else {
7651 ErrorFound = NotASpecificExpression;
7652 ErrorLoc = FirstBinOp->getExprLoc();
7653 ErrorRange = FirstBinOp->getSourceRange();
7654 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
7655 NoteRange = SecondBinOp->getRHS()->getSourceRange();
7656 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00007657 }
7658 }
7659 }
7660 }
7661 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007662 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007663 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007664 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007665 ErrorFound = NotTwoSubstatements;
7666 }
7667 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007668 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007669 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007670 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00007671 ErrorFound = NotACompoundStatement;
7672 }
7673 if (ErrorFound != NoError) {
7674 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
7675 << ErrorRange;
7676 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
7677 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00007678 }
Alexey Bataeve3727102018-04-18 15:57:46 +00007679 if (CurContext->isDependentContext())
7680 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00007681 }
Alexey Bataevdea47612014-07-23 07:46:59 +00007682 }
Alexey Bataev0162e452014-07-22 10:10:35 +00007683
Reid Kleckner87a31802018-03-12 21:43:02 +00007684 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00007685
Alexey Bataev62cec442014-11-18 10:14:22 +00007686 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00007687 X, V, E, UE, IsXLHSInRHSPart,
7688 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00007689}
7690
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007691StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
7692 Stmt *AStmt,
7693 SourceLocation StartLoc,
7694 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007695 if (!AStmt)
7696 return StmtError();
7697
Alexey Bataeve3727102018-04-18 15:57:46 +00007698 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00007699 // 1.2.2 OpenMP Language Terminology
7700 // Structured block - An executable statement with a single entry at the
7701 // top and a single exit at the bottom.
7702 // The point of exit cannot be a branch out of the structured block.
7703 // longjmp() and throw() must not violate the entry/exit criteria.
7704 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007705 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
7706 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7707 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7708 // 1.2.2 OpenMP Language Terminology
7709 // Structured block - An executable statement with a single entry at the
7710 // top and a single exit at the bottom.
7711 // The point of exit cannot be a branch out of the structured block.
7712 // longjmp() and throw() must not violate the entry/exit criteria.
7713 CS->getCapturedDecl()->setNothrow();
7714 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007715
Alexey Bataev13314bf2014-10-09 04:18:56 +00007716 // OpenMP [2.16, Nesting of Regions]
7717 // If specified, a teams construct must be contained within a target
7718 // construct. That target construct must contain no statements or directives
7719 // outside of the teams construct.
7720 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007721 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007722 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007723 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00007724 auto I = CS->body_begin();
7725 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007726 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Kelvin Li620ba602019-02-05 16:43:00 +00007727 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind()) ||
7728 OMPTeamsFound) {
7729
Alexey Bataev13314bf2014-10-09 04:18:56 +00007730 OMPTeamsFound = false;
7731 break;
7732 }
7733 ++I;
7734 }
7735 assert(I != CS->body_end() && "Not found statement");
7736 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00007737 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007738 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00007739 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00007740 }
7741 if (!OMPTeamsFound) {
7742 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7743 Diag(DSAStack->getInnerTeamsRegionLoc(),
7744 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007745 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00007746 << isa<OMPExecutableDirective>(S);
7747 return StmtError();
7748 }
7749 }
7750
Reid Kleckner87a31802018-03-12 21:43:02 +00007751 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007752
7753 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7754}
7755
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007756StmtResult
7757Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7758 Stmt *AStmt, SourceLocation StartLoc,
7759 SourceLocation EndLoc) {
7760 if (!AStmt)
7761 return StmtError();
7762
Alexey Bataeve3727102018-04-18 15:57:46 +00007763 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007764 // 1.2.2 OpenMP Language Terminology
7765 // Structured block - An executable statement with a single entry at the
7766 // top and a single exit at the bottom.
7767 // The point of exit cannot be a branch out of the structured block.
7768 // longjmp() and throw() must not violate the entry/exit criteria.
7769 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007770 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7771 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7772 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7773 // 1.2.2 OpenMP Language Terminology
7774 // Structured block - An executable statement with a single entry at the
7775 // top and a single exit at the bottom.
7776 // The point of exit cannot be a branch out of the structured block.
7777 // longjmp() and throw() must not violate the entry/exit criteria.
7778 CS->getCapturedDecl()->setNothrow();
7779 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007780
Reid Kleckner87a31802018-03-12 21:43:02 +00007781 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007782
7783 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7784 AStmt);
7785}
7786
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007787StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7788 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007789 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007790 if (!AStmt)
7791 return StmtError();
7792
Alexey Bataeve3727102018-04-18 15:57:46 +00007793 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007794 // 1.2.2 OpenMP Language Terminology
7795 // Structured block - An executable statement with a single entry at the
7796 // top and a single exit at the bottom.
7797 // The point of exit cannot be a branch out of the structured block.
7798 // longjmp() and throw() must not violate the entry/exit criteria.
7799 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007800 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7801 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7802 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7803 // 1.2.2 OpenMP Language Terminology
7804 // Structured block - An executable statement with a single entry at the
7805 // top and a single exit at the bottom.
7806 // The point of exit cannot be a branch out of the structured block.
7807 // longjmp() and throw() must not violate the entry/exit criteria.
7808 CS->getCapturedDecl()->setNothrow();
7809 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007810
7811 OMPLoopDirective::HelperExprs B;
7812 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7813 // define the nested loops number.
7814 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007815 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007816 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007817 VarsWithImplicitDSA, B);
7818 if (NestedLoopCount == 0)
7819 return StmtError();
7820
7821 assert((CurContext->isDependentContext() || B.builtAll()) &&
7822 "omp target parallel for loop exprs were not built");
7823
7824 if (!CurContext->isDependentContext()) {
7825 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007826 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007827 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007828 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007829 B.NumIterations, *this, CurScope,
7830 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007831 return StmtError();
7832 }
7833 }
7834
Reid Kleckner87a31802018-03-12 21:43:02 +00007835 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007836 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7837 NestedLoopCount, Clauses, AStmt,
7838 B, DSAStack->isCancelRegion());
7839}
7840
Alexey Bataev95b64a92017-05-30 16:00:04 +00007841/// Check for existence of a map clause in the list of clauses.
7842static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7843 const OpenMPClauseKind K) {
7844 return llvm::any_of(
7845 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7846}
Samuel Antaodf67fc42016-01-19 19:15:56 +00007847
Alexey Bataev95b64a92017-05-30 16:00:04 +00007848template <typename... Params>
7849static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7850 const Params... ClauseTypes) {
7851 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007852}
7853
Michael Wong65f367f2015-07-21 13:44:28 +00007854StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7855 Stmt *AStmt,
7856 SourceLocation StartLoc,
7857 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007858 if (!AStmt)
7859 return StmtError();
7860
7861 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7862
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007863 // OpenMP [2.10.1, Restrictions, p. 97]
7864 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007865 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7866 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7867 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00007868 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007869 return StmtError();
7870 }
7871
Reid Kleckner87a31802018-03-12 21:43:02 +00007872 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00007873
7874 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7875 AStmt);
7876}
7877
Samuel Antaodf67fc42016-01-19 19:15:56 +00007878StmtResult
7879Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7880 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007881 SourceLocation EndLoc, Stmt *AStmt) {
7882 if (!AStmt)
7883 return StmtError();
7884
Alexey Bataeve3727102018-04-18 15:57:46 +00007885 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007886 // 1.2.2 OpenMP Language Terminology
7887 // Structured block - An executable statement with a single entry at the
7888 // top and a single exit at the bottom.
7889 // The point of exit cannot be a branch out of the structured block.
7890 // longjmp() and throw() must not violate the entry/exit criteria.
7891 CS->getCapturedDecl()->setNothrow();
7892 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7893 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7894 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7895 // 1.2.2 OpenMP Language Terminology
7896 // Structured block - An executable statement with a single entry at the
7897 // top and a single exit at the bottom.
7898 // The point of exit cannot be a branch out of the structured block.
7899 // longjmp() and throw() must not violate the entry/exit criteria.
7900 CS->getCapturedDecl()->setNothrow();
7901 }
7902
Samuel Antaodf67fc42016-01-19 19:15:56 +00007903 // OpenMP [2.10.2, Restrictions, p. 99]
7904 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007905 if (!hasClauses(Clauses, OMPC_map)) {
7906 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7907 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007908 return StmtError();
7909 }
7910
Alexey Bataev7828b252017-11-21 17:08:48 +00007911 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7912 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007913}
7914
Samuel Antao72590762016-01-19 20:04:50 +00007915StmtResult
7916Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7917 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007918 SourceLocation EndLoc, Stmt *AStmt) {
7919 if (!AStmt)
7920 return StmtError();
7921
Alexey Bataeve3727102018-04-18 15:57:46 +00007922 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007923 // 1.2.2 OpenMP Language Terminology
7924 // Structured block - An executable statement with a single entry at the
7925 // top and a single exit at the bottom.
7926 // The point of exit cannot be a branch out of the structured block.
7927 // longjmp() and throw() must not violate the entry/exit criteria.
7928 CS->getCapturedDecl()->setNothrow();
7929 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7930 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7931 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7932 // 1.2.2 OpenMP Language Terminology
7933 // Structured block - An executable statement with a single entry at the
7934 // top and a single exit at the bottom.
7935 // The point of exit cannot be a branch out of the structured block.
7936 // longjmp() and throw() must not violate the entry/exit criteria.
7937 CS->getCapturedDecl()->setNothrow();
7938 }
7939
Samuel Antao72590762016-01-19 20:04:50 +00007940 // OpenMP [2.10.3, Restrictions, p. 102]
7941 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007942 if (!hasClauses(Clauses, OMPC_map)) {
7943 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7944 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00007945 return StmtError();
7946 }
7947
Alexey Bataev7828b252017-11-21 17:08:48 +00007948 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7949 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00007950}
7951
Samuel Antao686c70c2016-05-26 17:30:50 +00007952StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7953 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007954 SourceLocation EndLoc,
7955 Stmt *AStmt) {
7956 if (!AStmt)
7957 return StmtError();
7958
Alexey Bataeve3727102018-04-18 15:57:46 +00007959 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007960 // 1.2.2 OpenMP Language Terminology
7961 // Structured block - An executable statement with a single entry at the
7962 // top and a single exit at the bottom.
7963 // The point of exit cannot be a branch out of the structured block.
7964 // longjmp() and throw() must not violate the entry/exit criteria.
7965 CS->getCapturedDecl()->setNothrow();
7966 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7967 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7968 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7969 // 1.2.2 OpenMP Language Terminology
7970 // Structured block - An executable statement with a single entry at the
7971 // top and a single exit at the bottom.
7972 // The point of exit cannot be a branch out of the structured block.
7973 // longjmp() and throw() must not violate the entry/exit criteria.
7974 CS->getCapturedDecl()->setNothrow();
7975 }
7976
Alexey Bataev95b64a92017-05-30 16:00:04 +00007977 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00007978 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7979 return StmtError();
7980 }
Alexey Bataev7828b252017-11-21 17:08:48 +00007981 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7982 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00007983}
7984
Alexey Bataev13314bf2014-10-09 04:18:56 +00007985StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7986 Stmt *AStmt, SourceLocation StartLoc,
7987 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007988 if (!AStmt)
7989 return StmtError();
7990
Alexey Bataeve3727102018-04-18 15:57:46 +00007991 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007992 // 1.2.2 OpenMP Language Terminology
7993 // Structured block - An executable statement with a single entry at the
7994 // top and a single exit at the bottom.
7995 // The point of exit cannot be a branch out of the structured block.
7996 // longjmp() and throw() must not violate the entry/exit criteria.
7997 CS->getCapturedDecl()->setNothrow();
7998
Reid Kleckner87a31802018-03-12 21:43:02 +00007999 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00008000
Alexey Bataevceabd412017-11-30 18:01:54 +00008001 DSAStack->setParentTeamsRegionLoc(StartLoc);
8002
Alexey Bataev13314bf2014-10-09 04:18:56 +00008003 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
8004}
8005
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008006StmtResult
8007Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
8008 SourceLocation EndLoc,
8009 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008010 if (DSAStack->isParentNowaitRegion()) {
8011 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
8012 return StmtError();
8013 }
8014 if (DSAStack->isParentOrderedRegion()) {
8015 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
8016 return StmtError();
8017 }
8018 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
8019 CancelRegion);
8020}
8021
Alexey Bataev87933c72015-09-18 08:07:34 +00008022StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
8023 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00008024 SourceLocation EndLoc,
8025 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00008026 if (DSAStack->isParentNowaitRegion()) {
8027 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
8028 return StmtError();
8029 }
8030 if (DSAStack->isParentOrderedRegion()) {
8031 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
8032 return StmtError();
8033 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00008034 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00008035 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
8036 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00008037}
8038
Alexey Bataev382967a2015-12-08 12:06:20 +00008039static bool checkGrainsizeNumTasksClauses(Sema &S,
8040 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008041 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00008042 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00008043 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00008044 if (C->getClauseKind() == OMPC_grainsize ||
8045 C->getClauseKind() == OMPC_num_tasks) {
8046 if (!PrevClause)
8047 PrevClause = C;
8048 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008049 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00008050 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
8051 << getOpenMPClauseName(C->getClauseKind())
8052 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008053 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00008054 diag::note_omp_previous_grainsize_num_tasks)
8055 << getOpenMPClauseName(PrevClause->getClauseKind());
8056 ErrorFound = true;
8057 }
8058 }
8059 }
8060 return ErrorFound;
8061}
8062
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008063static bool checkReductionClauseWithNogroup(Sema &S,
8064 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00008065 const OMPClause *ReductionClause = nullptr;
8066 const OMPClause *NogroupClause = nullptr;
8067 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008068 if (C->getClauseKind() == OMPC_reduction) {
8069 ReductionClause = C;
8070 if (NogroupClause)
8071 break;
8072 continue;
8073 }
8074 if (C->getClauseKind() == OMPC_nogroup) {
8075 NogroupClause = C;
8076 if (ReductionClause)
8077 break;
8078 continue;
8079 }
8080 }
8081 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00008082 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
8083 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00008084 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008085 return true;
8086 }
8087 return false;
8088}
8089
Alexey Bataev49f6e782015-12-01 04:18:41 +00008090StmtResult Sema::ActOnOpenMPTaskLoopDirective(
8091 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008092 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00008093 if (!AStmt)
8094 return StmtError();
8095
8096 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8097 OMPLoopDirective::HelperExprs B;
8098 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8099 // define the nested loops number.
8100 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008101 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008102 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00008103 VarsWithImplicitDSA, B);
8104 if (NestedLoopCount == 0)
8105 return StmtError();
8106
8107 assert((CurContext->isDependentContext() || B.builtAll()) &&
8108 "omp for loop exprs were not built");
8109
Alexey Bataev382967a2015-12-08 12:06:20 +00008110 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8111 // The grainsize clause and num_tasks clause are mutually exclusive and may
8112 // not appear on the same taskloop directive.
8113 if (checkGrainsizeNumTasksClauses(*this, Clauses))
8114 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008115 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8116 // If a reduction clause is present on the taskloop directive, the nogroup
8117 // clause must not be specified.
8118 if (checkReductionClauseWithNogroup(*this, Clauses))
8119 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00008120
Reid Kleckner87a31802018-03-12 21:43:02 +00008121 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00008122 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
8123 NestedLoopCount, Clauses, AStmt, B);
8124}
8125
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008126StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
8127 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008128 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008129 if (!AStmt)
8130 return StmtError();
8131
8132 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8133 OMPLoopDirective::HelperExprs B;
8134 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8135 // define the nested loops number.
8136 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008137 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008138 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
8139 VarsWithImplicitDSA, B);
8140 if (NestedLoopCount == 0)
8141 return StmtError();
8142
8143 assert((CurContext->isDependentContext() || B.builtAll()) &&
8144 "omp for loop exprs were not built");
8145
Alexey Bataev5a3af132016-03-29 08:58:54 +00008146 if (!CurContext->isDependentContext()) {
8147 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008148 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008149 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00008150 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00008151 B.NumIterations, *this, CurScope,
8152 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00008153 return StmtError();
8154 }
8155 }
8156
Alexey Bataev382967a2015-12-08 12:06:20 +00008157 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8158 // The grainsize clause and num_tasks clause are mutually exclusive and may
8159 // not appear on the same taskloop directive.
8160 if (checkGrainsizeNumTasksClauses(*this, Clauses))
8161 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00008162 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
8163 // If a reduction clause is present on the taskloop directive, the nogroup
8164 // clause must not be specified.
8165 if (checkReductionClauseWithNogroup(*this, Clauses))
8166 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00008167 if (checkSimdlenSafelenSpecified(*this, Clauses))
8168 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00008169
Reid Kleckner87a31802018-03-12 21:43:02 +00008170 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00008171 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
8172 NestedLoopCount, Clauses, AStmt, B);
8173}
8174
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008175StmtResult Sema::ActOnOpenMPDistributeDirective(
8176 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008177 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008178 if (!AStmt)
8179 return StmtError();
8180
8181 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
8182 OMPLoopDirective::HelperExprs B;
8183 // In presence of clause 'collapse' with number of loops, it will
8184 // define the nested loops number.
8185 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008186 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008187 nullptr /*ordered not a clause on distribute*/, AStmt,
8188 *this, *DSAStack, VarsWithImplicitDSA, B);
8189 if (NestedLoopCount == 0)
8190 return StmtError();
8191
8192 assert((CurContext->isDependentContext() || B.builtAll()) &&
8193 "omp for loop exprs were not built");
8194
Reid Kleckner87a31802018-03-12 21:43:02 +00008195 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00008196 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
8197 NestedLoopCount, Clauses, AStmt, B);
8198}
8199
Carlo Bertolli9925f152016-06-27 14:55:37 +00008200StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
8201 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008202 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00008203 if (!AStmt)
8204 return StmtError();
8205
Alexey Bataeve3727102018-04-18 15:57:46 +00008206 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00008207 // 1.2.2 OpenMP Language Terminology
8208 // Structured block - An executable statement with a single entry at the
8209 // top and a single exit at the bottom.
8210 // The point of exit cannot be a branch out of the structured block.
8211 // longjmp() and throw() must not violate the entry/exit criteria.
8212 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00008213 for (int ThisCaptureLevel =
8214 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
8215 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8216 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8217 // 1.2.2 OpenMP Language Terminology
8218 // Structured block - An executable statement with a single entry at the
8219 // top and a single exit at the bottom.
8220 // The point of exit cannot be a branch out of the structured block.
8221 // longjmp() and throw() must not violate the entry/exit criteria.
8222 CS->getCapturedDecl()->setNothrow();
8223 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00008224
8225 OMPLoopDirective::HelperExprs B;
8226 // In presence of clause 'collapse' with number of loops, it will
8227 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008228 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00008229 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00008230 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00008231 VarsWithImplicitDSA, B);
8232 if (NestedLoopCount == 0)
8233 return StmtError();
8234
8235 assert((CurContext->isDependentContext() || B.builtAll()) &&
8236 "omp for loop exprs were not built");
8237
Reid Kleckner87a31802018-03-12 21:43:02 +00008238 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00008239 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008240 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8241 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00008242}
8243
Kelvin Li4a39add2016-07-05 05:00:15 +00008244StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
8245 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008246 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00008247 if (!AStmt)
8248 return StmtError();
8249
Alexey Bataeve3727102018-04-18 15:57:46 +00008250 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00008251 // 1.2.2 OpenMP Language Terminology
8252 // Structured block - An executable statement with a single entry at the
8253 // top and a single exit at the bottom.
8254 // The point of exit cannot be a branch out of the structured block.
8255 // longjmp() and throw() must not violate the entry/exit criteria.
8256 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00008257 for (int ThisCaptureLevel =
8258 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
8259 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8260 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8261 // 1.2.2 OpenMP Language Terminology
8262 // Structured block - An executable statement with a single entry at the
8263 // top and a single exit at the bottom.
8264 // The point of exit cannot be a branch out of the structured block.
8265 // longjmp() and throw() must not violate the entry/exit criteria.
8266 CS->getCapturedDecl()->setNothrow();
8267 }
Kelvin Li4a39add2016-07-05 05:00:15 +00008268
8269 OMPLoopDirective::HelperExprs B;
8270 // In presence of clause 'collapse' with number of loops, it will
8271 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008272 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00008273 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00008274 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00008275 VarsWithImplicitDSA, B);
8276 if (NestedLoopCount == 0)
8277 return StmtError();
8278
8279 assert((CurContext->isDependentContext() || B.builtAll()) &&
8280 "omp for loop exprs were not built");
8281
Alexey Bataev438388c2017-11-22 18:34:02 +00008282 if (!CurContext->isDependentContext()) {
8283 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008284 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008285 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8286 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8287 B.NumIterations, *this, CurScope,
8288 DSAStack))
8289 return StmtError();
8290 }
8291 }
8292
Kelvin Lic5609492016-07-15 04:39:07 +00008293 if (checkSimdlenSafelenSpecified(*this, Clauses))
8294 return StmtError();
8295
Reid Kleckner87a31802018-03-12 21:43:02 +00008296 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00008297 return OMPDistributeParallelForSimdDirective::Create(
8298 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8299}
8300
Kelvin Li787f3fc2016-07-06 04:45:38 +00008301StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
8302 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008303 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00008304 if (!AStmt)
8305 return StmtError();
8306
Alexey Bataeve3727102018-04-18 15:57:46 +00008307 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00008308 // 1.2.2 OpenMP Language Terminology
8309 // Structured block - An executable statement with a single entry at the
8310 // top and a single exit at the bottom.
8311 // The point of exit cannot be a branch out of the structured block.
8312 // longjmp() and throw() must not violate the entry/exit criteria.
8313 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00008314 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
8315 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8316 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8317 // 1.2.2 OpenMP Language Terminology
8318 // Structured block - An executable statement with a single entry at the
8319 // top and a single exit at the bottom.
8320 // The point of exit cannot be a branch out of the structured block.
8321 // longjmp() and throw() must not violate the entry/exit criteria.
8322 CS->getCapturedDecl()->setNothrow();
8323 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00008324
8325 OMPLoopDirective::HelperExprs B;
8326 // In presence of clause 'collapse' with number of loops, it will
8327 // define the nested loops number.
8328 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008329 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00008330 nullptr /*ordered not a clause on distribute*/, CS, *this,
8331 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00008332 if (NestedLoopCount == 0)
8333 return StmtError();
8334
8335 assert((CurContext->isDependentContext() || B.builtAll()) &&
8336 "omp for loop exprs were not built");
8337
Alexey Bataev438388c2017-11-22 18:34:02 +00008338 if (!CurContext->isDependentContext()) {
8339 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008340 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008341 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8342 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8343 B.NumIterations, *this, CurScope,
8344 DSAStack))
8345 return StmtError();
8346 }
8347 }
8348
Kelvin Lic5609492016-07-15 04:39:07 +00008349 if (checkSimdlenSafelenSpecified(*this, Clauses))
8350 return StmtError();
8351
Reid Kleckner87a31802018-03-12 21:43:02 +00008352 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00008353 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
8354 NestedLoopCount, Clauses, AStmt, B);
8355}
8356
Kelvin Lia579b912016-07-14 02:54:56 +00008357StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
8358 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008359 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00008360 if (!AStmt)
8361 return StmtError();
8362
Alexey Bataeve3727102018-04-18 15:57:46 +00008363 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00008364 // 1.2.2 OpenMP Language Terminology
8365 // Structured block - An executable statement with a single entry at the
8366 // top and a single exit at the bottom.
8367 // The point of exit cannot be a branch out of the structured block.
8368 // longjmp() and throw() must not violate the entry/exit criteria.
8369 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008370 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
8371 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8372 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8373 // 1.2.2 OpenMP Language Terminology
8374 // Structured block - An executable statement with a single entry at the
8375 // top and a single exit at the bottom.
8376 // The point of exit cannot be a branch out of the structured block.
8377 // longjmp() and throw() must not violate the entry/exit criteria.
8378 CS->getCapturedDecl()->setNothrow();
8379 }
Kelvin Lia579b912016-07-14 02:54:56 +00008380
8381 OMPLoopDirective::HelperExprs B;
8382 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
8383 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008384 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00008385 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008386 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00008387 VarsWithImplicitDSA, B);
8388 if (NestedLoopCount == 0)
8389 return StmtError();
8390
8391 assert((CurContext->isDependentContext() || B.builtAll()) &&
8392 "omp target parallel for simd loop exprs were not built");
8393
8394 if (!CurContext->isDependentContext()) {
8395 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008396 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008397 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00008398 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8399 B.NumIterations, *this, CurScope,
8400 DSAStack))
8401 return StmtError();
8402 }
8403 }
Kelvin Lic5609492016-07-15 04:39:07 +00008404 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00008405 return StmtError();
8406
Reid Kleckner87a31802018-03-12 21:43:02 +00008407 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00008408 return OMPTargetParallelForSimdDirective::Create(
8409 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8410}
8411
Kelvin Li986330c2016-07-20 22:57:10 +00008412StmtResult Sema::ActOnOpenMPTargetSimdDirective(
8413 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008414 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00008415 if (!AStmt)
8416 return StmtError();
8417
Alexey Bataeve3727102018-04-18 15:57:46 +00008418 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00008419 // 1.2.2 OpenMP Language Terminology
8420 // Structured block - An executable statement with a single entry at the
8421 // top and a single exit at the bottom.
8422 // The point of exit cannot be a branch out of the structured block.
8423 // longjmp() and throw() must not violate the entry/exit criteria.
8424 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00008425 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
8426 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8427 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8428 // 1.2.2 OpenMP Language Terminology
8429 // Structured block - An executable statement with a single entry at the
8430 // top and a single exit at the bottom.
8431 // The point of exit cannot be a branch out of the structured block.
8432 // longjmp() and throw() must not violate the entry/exit criteria.
8433 CS->getCapturedDecl()->setNothrow();
8434 }
8435
Kelvin Li986330c2016-07-20 22:57:10 +00008436 OMPLoopDirective::HelperExprs B;
8437 // In presence of clause 'collapse' with number of loops, it will define the
8438 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00008439 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008440 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00008441 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00008442 VarsWithImplicitDSA, B);
8443 if (NestedLoopCount == 0)
8444 return StmtError();
8445
8446 assert((CurContext->isDependentContext() || B.builtAll()) &&
8447 "omp target simd loop exprs were not built");
8448
8449 if (!CurContext->isDependentContext()) {
8450 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008451 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00008452 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00008453 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8454 B.NumIterations, *this, CurScope,
8455 DSAStack))
8456 return StmtError();
8457 }
8458 }
8459
8460 if (checkSimdlenSafelenSpecified(*this, Clauses))
8461 return StmtError();
8462
Reid Kleckner87a31802018-03-12 21:43:02 +00008463 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00008464 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
8465 NestedLoopCount, Clauses, AStmt, B);
8466}
8467
Kelvin Li02532872016-08-05 14:37:37 +00008468StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
8469 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008470 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00008471 if (!AStmt)
8472 return StmtError();
8473
Alexey Bataeve3727102018-04-18 15:57:46 +00008474 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00008475 // 1.2.2 OpenMP Language Terminology
8476 // Structured block - An executable statement with a single entry at the
8477 // top and a single exit at the bottom.
8478 // The point of exit cannot be a branch out of the structured block.
8479 // longjmp() and throw() must not violate the entry/exit criteria.
8480 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008481 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
8482 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8483 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8484 // 1.2.2 OpenMP Language Terminology
8485 // Structured block - An executable statement with a single entry at the
8486 // top and a single exit at the bottom.
8487 // The point of exit cannot be a branch out of the structured block.
8488 // longjmp() and throw() must not violate the entry/exit criteria.
8489 CS->getCapturedDecl()->setNothrow();
8490 }
Kelvin Li02532872016-08-05 14:37:37 +00008491
8492 OMPLoopDirective::HelperExprs B;
8493 // In presence of clause 'collapse' with number of loops, it will
8494 // define the nested loops number.
8495 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00008496 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00008497 nullptr /*ordered not a clause on distribute*/, CS, *this,
8498 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00008499 if (NestedLoopCount == 0)
8500 return StmtError();
8501
8502 assert((CurContext->isDependentContext() || B.builtAll()) &&
8503 "omp teams distribute loop exprs were not built");
8504
Reid Kleckner87a31802018-03-12 21:43:02 +00008505 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008506
8507 DSAStack->setParentTeamsRegionLoc(StartLoc);
8508
David Majnemer9d168222016-08-05 17:44:54 +00008509 return OMPTeamsDistributeDirective::Create(
8510 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00008511}
8512
Kelvin Li4e325f72016-10-25 12:50:55 +00008513StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
8514 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008515 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008516 if (!AStmt)
8517 return StmtError();
8518
Alexey Bataeve3727102018-04-18 15:57:46 +00008519 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00008520 // 1.2.2 OpenMP Language Terminology
8521 // Structured block - An executable statement with a single entry at the
8522 // top and a single exit at the bottom.
8523 // The point of exit cannot be a branch out of the structured block.
8524 // longjmp() and throw() must not violate the entry/exit criteria.
8525 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00008526 for (int ThisCaptureLevel =
8527 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
8528 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8529 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8530 // 1.2.2 OpenMP Language Terminology
8531 // Structured block - An executable statement with a single entry at the
8532 // top and a single exit at the bottom.
8533 // The point of exit cannot be a branch out of the structured block.
8534 // longjmp() and throw() must not violate the entry/exit criteria.
8535 CS->getCapturedDecl()->setNothrow();
8536 }
8537
Kelvin Li4e325f72016-10-25 12:50:55 +00008538
8539 OMPLoopDirective::HelperExprs B;
8540 // In presence of clause 'collapse' with number of loops, it will
8541 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008542 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00008543 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00008544 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00008545 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00008546
8547 if (NestedLoopCount == 0)
8548 return StmtError();
8549
8550 assert((CurContext->isDependentContext() || B.builtAll()) &&
8551 "omp teams distribute simd loop exprs were not built");
8552
8553 if (!CurContext->isDependentContext()) {
8554 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008555 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00008556 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8557 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8558 B.NumIterations, *this, CurScope,
8559 DSAStack))
8560 return StmtError();
8561 }
8562 }
8563
8564 if (checkSimdlenSafelenSpecified(*this, Clauses))
8565 return StmtError();
8566
Reid Kleckner87a31802018-03-12 21:43:02 +00008567 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008568
8569 DSAStack->setParentTeamsRegionLoc(StartLoc);
8570
Kelvin Li4e325f72016-10-25 12:50:55 +00008571 return OMPTeamsDistributeSimdDirective::Create(
8572 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8573}
8574
Kelvin Li579e41c2016-11-30 23:51:03 +00008575StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
8576 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008577 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008578 if (!AStmt)
8579 return StmtError();
8580
Alexey Bataeve3727102018-04-18 15:57:46 +00008581 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00008582 // 1.2.2 OpenMP Language Terminology
8583 // Structured block - An executable statement with a single entry at the
8584 // top and a single exit at the bottom.
8585 // The point of exit cannot be a branch out of the structured block.
8586 // longjmp() and throw() must not violate the entry/exit criteria.
8587 CS->getCapturedDecl()->setNothrow();
8588
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008589 for (int ThisCaptureLevel =
8590 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
8591 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8592 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8593 // 1.2.2 OpenMP Language Terminology
8594 // Structured block - An executable statement with a single entry at the
8595 // top and a single exit at the bottom.
8596 // The point of exit cannot be a branch out of the structured block.
8597 // longjmp() and throw() must not violate the entry/exit criteria.
8598 CS->getCapturedDecl()->setNothrow();
8599 }
8600
Kelvin Li579e41c2016-11-30 23:51:03 +00008601 OMPLoopDirective::HelperExprs B;
8602 // In presence of clause 'collapse' with number of loops, it will
8603 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008604 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00008605 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00008606 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00008607 VarsWithImplicitDSA, B);
8608
8609 if (NestedLoopCount == 0)
8610 return StmtError();
8611
8612 assert((CurContext->isDependentContext() || B.builtAll()) &&
8613 "omp for loop exprs were not built");
8614
8615 if (!CurContext->isDependentContext()) {
8616 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008617 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00008618 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8619 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8620 B.NumIterations, *this, CurScope,
8621 DSAStack))
8622 return StmtError();
8623 }
8624 }
8625
8626 if (checkSimdlenSafelenSpecified(*this, Clauses))
8627 return StmtError();
8628
Reid Kleckner87a31802018-03-12 21:43:02 +00008629 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008630
8631 DSAStack->setParentTeamsRegionLoc(StartLoc);
8632
Kelvin Li579e41c2016-11-30 23:51:03 +00008633 return OMPTeamsDistributeParallelForSimdDirective::Create(
8634 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8635}
8636
Kelvin Li7ade93f2016-12-09 03:24:30 +00008637StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
8638 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008639 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00008640 if (!AStmt)
8641 return StmtError();
8642
Alexey Bataeve3727102018-04-18 15:57:46 +00008643 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00008644 // 1.2.2 OpenMP Language Terminology
8645 // Structured block - An executable statement with a single entry at the
8646 // top and a single exit at the bottom.
8647 // The point of exit cannot be a branch out of the structured block.
8648 // longjmp() and throw() must not violate the entry/exit criteria.
8649 CS->getCapturedDecl()->setNothrow();
8650
Carlo Bertolli62fae152017-11-20 20:46:39 +00008651 for (int ThisCaptureLevel =
8652 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
8653 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8654 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8655 // 1.2.2 OpenMP Language Terminology
8656 // Structured block - An executable statement with a single entry at the
8657 // top and a single exit at the bottom.
8658 // The point of exit cannot be a branch out of the structured block.
8659 // longjmp() and throw() must not violate the entry/exit criteria.
8660 CS->getCapturedDecl()->setNothrow();
8661 }
8662
Kelvin Li7ade93f2016-12-09 03:24:30 +00008663 OMPLoopDirective::HelperExprs B;
8664 // In presence of clause 'collapse' with number of loops, it will
8665 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008666 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00008667 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00008668 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00008669 VarsWithImplicitDSA, B);
8670
8671 if (NestedLoopCount == 0)
8672 return StmtError();
8673
8674 assert((CurContext->isDependentContext() || B.builtAll()) &&
8675 "omp for loop exprs were not built");
8676
Reid Kleckner87a31802018-03-12 21:43:02 +00008677 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00008678
8679 DSAStack->setParentTeamsRegionLoc(StartLoc);
8680
Kelvin Li7ade93f2016-12-09 03:24:30 +00008681 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00008682 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8683 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00008684}
8685
Kelvin Libf594a52016-12-17 05:48:59 +00008686StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
8687 Stmt *AStmt,
8688 SourceLocation StartLoc,
8689 SourceLocation EndLoc) {
8690 if (!AStmt)
8691 return StmtError();
8692
Alexey Bataeve3727102018-04-18 15:57:46 +00008693 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00008694 // 1.2.2 OpenMP Language Terminology
8695 // Structured block - An executable statement with a single entry at the
8696 // top and a single exit at the bottom.
8697 // The point of exit cannot be a branch out of the structured block.
8698 // longjmp() and throw() must not violate the entry/exit criteria.
8699 CS->getCapturedDecl()->setNothrow();
8700
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00008701 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
8702 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8703 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8704 // 1.2.2 OpenMP Language Terminology
8705 // Structured block - An executable statement with a single entry at the
8706 // top and a single exit at the bottom.
8707 // The point of exit cannot be a branch out of the structured block.
8708 // longjmp() and throw() must not violate the entry/exit criteria.
8709 CS->getCapturedDecl()->setNothrow();
8710 }
Reid Kleckner87a31802018-03-12 21:43:02 +00008711 setFunctionHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00008712
8713 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8714 AStmt);
8715}
8716
Kelvin Li83c451e2016-12-25 04:52:54 +00008717StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8718 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008719 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00008720 if (!AStmt)
8721 return StmtError();
8722
Alexey Bataeve3727102018-04-18 15:57:46 +00008723 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00008724 // 1.2.2 OpenMP Language Terminology
8725 // Structured block - An executable statement with a single entry at the
8726 // top and a single exit at the bottom.
8727 // The point of exit cannot be a branch out of the structured block.
8728 // longjmp() and throw() must not violate the entry/exit criteria.
8729 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008730 for (int ThisCaptureLevel =
8731 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8732 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8733 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8734 // 1.2.2 OpenMP Language Terminology
8735 // Structured block - An executable statement with a single entry at the
8736 // top and a single exit at the bottom.
8737 // The point of exit cannot be a branch out of the structured block.
8738 // longjmp() and throw() must not violate the entry/exit criteria.
8739 CS->getCapturedDecl()->setNothrow();
8740 }
Kelvin Li83c451e2016-12-25 04:52:54 +00008741
8742 OMPLoopDirective::HelperExprs B;
8743 // In presence of clause 'collapse' with number of loops, it will
8744 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008745 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008746 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8747 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00008748 VarsWithImplicitDSA, B);
8749 if (NestedLoopCount == 0)
8750 return StmtError();
8751
8752 assert((CurContext->isDependentContext() || B.builtAll()) &&
8753 "omp target teams distribute loop exprs were not built");
8754
Reid Kleckner87a31802018-03-12 21:43:02 +00008755 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00008756 return OMPTargetTeamsDistributeDirective::Create(
8757 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8758}
8759
Kelvin Li80e8f562016-12-29 22:16:30 +00008760StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8761 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008762 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00008763 if (!AStmt)
8764 return StmtError();
8765
Alexey Bataeve3727102018-04-18 15:57:46 +00008766 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00008767 // 1.2.2 OpenMP Language Terminology
8768 // Structured block - An executable statement with a single entry at the
8769 // top and a single exit at the bottom.
8770 // The point of exit cannot be a branch out of the structured block.
8771 // longjmp() and throw() must not violate the entry/exit criteria.
8772 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00008773 for (int ThisCaptureLevel =
8774 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8775 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8776 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8777 // 1.2.2 OpenMP Language Terminology
8778 // Structured block - An executable statement with a single entry at the
8779 // top and a single exit at the bottom.
8780 // The point of exit cannot be a branch out of the structured block.
8781 // longjmp() and throw() must not violate the entry/exit criteria.
8782 CS->getCapturedDecl()->setNothrow();
8783 }
8784
Kelvin Li80e8f562016-12-29 22:16:30 +00008785 OMPLoopDirective::HelperExprs B;
8786 // In presence of clause 'collapse' with number of loops, it will
8787 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008788 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00008789 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8790 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00008791 VarsWithImplicitDSA, B);
8792 if (NestedLoopCount == 0)
8793 return StmtError();
8794
8795 assert((CurContext->isDependentContext() || B.builtAll()) &&
8796 "omp target teams distribute parallel for loop exprs were not built");
8797
Alexey Bataev647dd842018-01-15 20:59:40 +00008798 if (!CurContext->isDependentContext()) {
8799 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008800 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00008801 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8802 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8803 B.NumIterations, *this, CurScope,
8804 DSAStack))
8805 return StmtError();
8806 }
8807 }
8808
Reid Kleckner87a31802018-03-12 21:43:02 +00008809 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00008810 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00008811 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8812 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00008813}
8814
Kelvin Li1851df52017-01-03 05:23:48 +00008815StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8816 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008817 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00008818 if (!AStmt)
8819 return StmtError();
8820
Alexey Bataeve3727102018-04-18 15:57:46 +00008821 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00008822 // 1.2.2 OpenMP Language Terminology
8823 // Structured block - An executable statement with a single entry at the
8824 // top and a single exit at the bottom.
8825 // The point of exit cannot be a branch out of the structured block.
8826 // longjmp() and throw() must not violate the entry/exit criteria.
8827 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00008828 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8829 OMPD_target_teams_distribute_parallel_for_simd);
8830 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8831 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8832 // 1.2.2 OpenMP Language Terminology
8833 // Structured block - An executable statement with a single entry at the
8834 // top and a single exit at the bottom.
8835 // The point of exit cannot be a branch out of the structured block.
8836 // longjmp() and throw() must not violate the entry/exit criteria.
8837 CS->getCapturedDecl()->setNothrow();
8838 }
Kelvin Li1851df52017-01-03 05:23:48 +00008839
8840 OMPLoopDirective::HelperExprs B;
8841 // In presence of clause 'collapse' with number of loops, it will
8842 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008843 unsigned NestedLoopCount =
8844 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00008845 getCollapseNumberExpr(Clauses),
8846 nullptr /*ordered not a clause on distribute*/, CS, *this,
8847 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00008848 if (NestedLoopCount == 0)
8849 return StmtError();
8850
8851 assert((CurContext->isDependentContext() || B.builtAll()) &&
8852 "omp target teams distribute parallel for simd loop exprs were not "
8853 "built");
8854
8855 if (!CurContext->isDependentContext()) {
8856 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008857 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00008858 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8859 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8860 B.NumIterations, *this, CurScope,
8861 DSAStack))
8862 return StmtError();
8863 }
8864 }
8865
Alexey Bataev438388c2017-11-22 18:34:02 +00008866 if (checkSimdlenSafelenSpecified(*this, Clauses))
8867 return StmtError();
8868
Reid Kleckner87a31802018-03-12 21:43:02 +00008869 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00008870 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8871 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8872}
8873
Kelvin Lida681182017-01-10 18:08:18 +00008874StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8875 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008876 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00008877 if (!AStmt)
8878 return StmtError();
8879
8880 auto *CS = cast<CapturedStmt>(AStmt);
8881 // 1.2.2 OpenMP Language Terminology
8882 // Structured block - An executable statement with a single entry at the
8883 // top and a single exit at the bottom.
8884 // The point of exit cannot be a branch out of the structured block.
8885 // longjmp() and throw() must not violate the entry/exit criteria.
8886 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008887 for (int ThisCaptureLevel =
8888 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
8889 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8890 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8891 // 1.2.2 OpenMP Language Terminology
8892 // Structured block - An executable statement with a single entry at the
8893 // top and a single exit at the bottom.
8894 // The point of exit cannot be a branch out of the structured block.
8895 // longjmp() and throw() must not violate the entry/exit criteria.
8896 CS->getCapturedDecl()->setNothrow();
8897 }
Kelvin Lida681182017-01-10 18:08:18 +00008898
8899 OMPLoopDirective::HelperExprs B;
8900 // In presence of clause 'collapse' with number of loops, it will
8901 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008902 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00008903 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008904 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00008905 VarsWithImplicitDSA, B);
8906 if (NestedLoopCount == 0)
8907 return StmtError();
8908
8909 assert((CurContext->isDependentContext() || B.builtAll()) &&
8910 "omp target teams distribute simd loop exprs were not built");
8911
Alexey Bataev438388c2017-11-22 18:34:02 +00008912 if (!CurContext->isDependentContext()) {
8913 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008914 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008915 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8916 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8917 B.NumIterations, *this, CurScope,
8918 DSAStack))
8919 return StmtError();
8920 }
8921 }
8922
8923 if (checkSimdlenSafelenSpecified(*this, Clauses))
8924 return StmtError();
8925
Reid Kleckner87a31802018-03-12 21:43:02 +00008926 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00008927 return OMPTargetTeamsDistributeSimdDirective::Create(
8928 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8929}
8930
Alexey Bataeved09d242014-05-28 05:53:51 +00008931OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008932 SourceLocation StartLoc,
8933 SourceLocation LParenLoc,
8934 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008935 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008936 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00008937 case OMPC_final:
8938 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8939 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00008940 case OMPC_num_threads:
8941 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8942 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008943 case OMPC_safelen:
8944 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8945 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00008946 case OMPC_simdlen:
8947 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8948 break;
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00008949 case OMPC_allocator:
8950 Res = ActOnOpenMPAllocatorClause(Expr, StartLoc, LParenLoc, EndLoc);
8951 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00008952 case OMPC_collapse:
8953 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8954 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008955 case OMPC_ordered:
8956 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8957 break;
Michael Wonge710d542015-08-07 16:16:36 +00008958 case OMPC_device:
8959 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8960 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00008961 case OMPC_num_teams:
8962 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8963 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008964 case OMPC_thread_limit:
8965 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8966 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00008967 case OMPC_priority:
8968 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8969 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008970 case OMPC_grainsize:
8971 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8972 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00008973 case OMPC_num_tasks:
8974 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8975 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00008976 case OMPC_hint:
8977 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8978 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008979 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008980 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008981 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008982 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008983 case OMPC_private:
8984 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008985 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008986 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008987 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008988 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008989 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008990 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008991 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008992 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008993 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00008994 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008995 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008996 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008997 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00008998 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008999 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009000 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009001 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009002 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009003 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009004 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009005 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00009006 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009007 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009008 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00009009 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009010 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009011 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009012 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009013 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009014 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009015 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009016 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009017 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009018 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009019 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009020 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009021 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009022 case OMPC_atomic_default_mem_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009023 llvm_unreachable("Clause is not allowed.");
9024 }
9025 return Res;
9026}
9027
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009028// An OpenMP directive such as 'target parallel' has two captured regions:
9029// for the 'target' and 'parallel' respectively. This function returns
9030// the region in which to capture expressions associated with a clause.
9031// A return value of OMPD_unknown signifies that the expression should not
9032// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009033static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
9034 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
9035 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009036 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009037 switch (CKind) {
9038 case OMPC_if:
9039 switch (DKind) {
9040 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009041 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009042 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009043 // If this clause applies to the nested 'parallel' region, capture within
9044 // the 'target' region, otherwise do not capture.
9045 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
9046 CaptureRegion = OMPD_target;
9047 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00009048 case OMPD_target_teams_distribute_parallel_for:
9049 case OMPD_target_teams_distribute_parallel_for_simd:
9050 // If this clause applies to the nested 'parallel' region, capture within
9051 // the 'teams' region, otherwise do not capture.
9052 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
9053 CaptureRegion = OMPD_teams;
9054 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00009055 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009056 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009057 CaptureRegion = OMPD_teams;
9058 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009059 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00009060 case OMPD_target_enter_data:
9061 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009062 CaptureRegion = OMPD_task;
9063 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009064 case OMPD_cancel:
9065 case OMPD_parallel:
9066 case OMPD_parallel_sections:
9067 case OMPD_parallel_for:
9068 case OMPD_parallel_for_simd:
9069 case OMPD_target:
9070 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009071 case OMPD_target_teams:
9072 case OMPD_target_teams_distribute:
9073 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009074 case OMPD_distribute_parallel_for:
9075 case OMPD_distribute_parallel_for_simd:
9076 case OMPD_task:
9077 case OMPD_taskloop:
9078 case OMPD_taskloop_simd:
9079 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009080 // Do not capture if-clause expressions.
9081 break;
9082 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009083 case OMPD_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009084 case OMPD_taskyield:
9085 case OMPD_barrier:
9086 case OMPD_taskwait:
9087 case OMPD_cancellation_point:
9088 case OMPD_flush:
9089 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009090 case OMPD_declare_mapper:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009091 case OMPD_declare_simd:
9092 case OMPD_declare_target:
9093 case OMPD_end_declare_target:
9094 case OMPD_teams:
9095 case OMPD_simd:
9096 case OMPD_for:
9097 case OMPD_for_simd:
9098 case OMPD_sections:
9099 case OMPD_section:
9100 case OMPD_single:
9101 case OMPD_master:
9102 case OMPD_critical:
9103 case OMPD_taskgroup:
9104 case OMPD_distribute:
9105 case OMPD_ordered:
9106 case OMPD_atomic:
9107 case OMPD_distribute_simd:
9108 case OMPD_teams_distribute:
9109 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009110 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009111 llvm_unreachable("Unexpected OpenMP directive with if-clause");
9112 case OMPD_unknown:
9113 llvm_unreachable("Unknown OpenMP directive");
9114 }
9115 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009116 case OMPC_num_threads:
9117 switch (DKind) {
9118 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009119 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00009120 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009121 CaptureRegion = OMPD_target;
9122 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00009123 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009124 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00009125 case OMPD_target_teams_distribute_parallel_for:
9126 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009127 CaptureRegion = OMPD_teams;
9128 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009129 case OMPD_parallel:
9130 case OMPD_parallel_sections:
9131 case OMPD_parallel_for:
9132 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009133 case OMPD_distribute_parallel_for:
9134 case OMPD_distribute_parallel_for_simd:
9135 // Do not capture num_threads-clause expressions.
9136 break;
9137 case OMPD_target_data:
9138 case OMPD_target_enter_data:
9139 case OMPD_target_exit_data:
9140 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009141 case OMPD_target:
9142 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009143 case OMPD_target_teams:
9144 case OMPD_target_teams_distribute:
9145 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009146 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009147 case OMPD_task:
9148 case OMPD_taskloop:
9149 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009150 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009151 case OMPD_allocate:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009152 case OMPD_taskyield:
9153 case OMPD_barrier:
9154 case OMPD_taskwait:
9155 case OMPD_cancellation_point:
9156 case OMPD_flush:
9157 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009158 case OMPD_declare_mapper:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009159 case OMPD_declare_simd:
9160 case OMPD_declare_target:
9161 case OMPD_end_declare_target:
9162 case OMPD_teams:
9163 case OMPD_simd:
9164 case OMPD_for:
9165 case OMPD_for_simd:
9166 case OMPD_sections:
9167 case OMPD_section:
9168 case OMPD_single:
9169 case OMPD_master:
9170 case OMPD_critical:
9171 case OMPD_taskgroup:
9172 case OMPD_distribute:
9173 case OMPD_ordered:
9174 case OMPD_atomic:
9175 case OMPD_distribute_simd:
9176 case OMPD_teams_distribute:
9177 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009178 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009179 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
9180 case OMPD_unknown:
9181 llvm_unreachable("Unknown OpenMP directive");
9182 }
9183 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009184 case OMPC_num_teams:
9185 switch (DKind) {
9186 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009187 case OMPD_target_teams_distribute:
9188 case OMPD_target_teams_distribute_simd:
9189 case OMPD_target_teams_distribute_parallel_for:
9190 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009191 CaptureRegion = OMPD_target;
9192 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009193 case OMPD_teams_distribute_parallel_for:
9194 case OMPD_teams_distribute_parallel_for_simd:
9195 case OMPD_teams:
9196 case OMPD_teams_distribute:
9197 case OMPD_teams_distribute_simd:
9198 // Do not capture num_teams-clause expressions.
9199 break;
9200 case OMPD_distribute_parallel_for:
9201 case OMPD_distribute_parallel_for_simd:
9202 case OMPD_task:
9203 case OMPD_taskloop:
9204 case OMPD_taskloop_simd:
9205 case OMPD_target_data:
9206 case OMPD_target_enter_data:
9207 case OMPD_target_exit_data:
9208 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009209 case OMPD_cancel:
9210 case OMPD_parallel:
9211 case OMPD_parallel_sections:
9212 case OMPD_parallel_for:
9213 case OMPD_parallel_for_simd:
9214 case OMPD_target:
9215 case OMPD_target_simd:
9216 case OMPD_target_parallel:
9217 case OMPD_target_parallel_for:
9218 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009219 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009220 case OMPD_allocate:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009221 case OMPD_taskyield:
9222 case OMPD_barrier:
9223 case OMPD_taskwait:
9224 case OMPD_cancellation_point:
9225 case OMPD_flush:
9226 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009227 case OMPD_declare_mapper:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009228 case OMPD_declare_simd:
9229 case OMPD_declare_target:
9230 case OMPD_end_declare_target:
9231 case OMPD_simd:
9232 case OMPD_for:
9233 case OMPD_for_simd:
9234 case OMPD_sections:
9235 case OMPD_section:
9236 case OMPD_single:
9237 case OMPD_master:
9238 case OMPD_critical:
9239 case OMPD_taskgroup:
9240 case OMPD_distribute:
9241 case OMPD_ordered:
9242 case OMPD_atomic:
9243 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009244 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00009245 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
9246 case OMPD_unknown:
9247 llvm_unreachable("Unknown OpenMP directive");
9248 }
9249 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009250 case OMPC_thread_limit:
9251 switch (DKind) {
9252 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009253 case OMPD_target_teams_distribute:
9254 case OMPD_target_teams_distribute_simd:
9255 case OMPD_target_teams_distribute_parallel_for:
9256 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009257 CaptureRegion = OMPD_target;
9258 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009259 case OMPD_teams_distribute_parallel_for:
9260 case OMPD_teams_distribute_parallel_for_simd:
9261 case OMPD_teams:
9262 case OMPD_teams_distribute:
9263 case OMPD_teams_distribute_simd:
9264 // Do not capture thread_limit-clause expressions.
9265 break;
9266 case OMPD_distribute_parallel_for:
9267 case OMPD_distribute_parallel_for_simd:
9268 case OMPD_task:
9269 case OMPD_taskloop:
9270 case OMPD_taskloop_simd:
9271 case OMPD_target_data:
9272 case OMPD_target_enter_data:
9273 case OMPD_target_exit_data:
9274 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009275 case OMPD_cancel:
9276 case OMPD_parallel:
9277 case OMPD_parallel_sections:
9278 case OMPD_parallel_for:
9279 case OMPD_parallel_for_simd:
9280 case OMPD_target:
9281 case OMPD_target_simd:
9282 case OMPD_target_parallel:
9283 case OMPD_target_parallel_for:
9284 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009285 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009286 case OMPD_allocate:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009287 case OMPD_taskyield:
9288 case OMPD_barrier:
9289 case OMPD_taskwait:
9290 case OMPD_cancellation_point:
9291 case OMPD_flush:
9292 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009293 case OMPD_declare_mapper:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009294 case OMPD_declare_simd:
9295 case OMPD_declare_target:
9296 case OMPD_end_declare_target:
9297 case OMPD_simd:
9298 case OMPD_for:
9299 case OMPD_for_simd:
9300 case OMPD_sections:
9301 case OMPD_section:
9302 case OMPD_single:
9303 case OMPD_master:
9304 case OMPD_critical:
9305 case OMPD_taskgroup:
9306 case OMPD_distribute:
9307 case OMPD_ordered:
9308 case OMPD_atomic:
9309 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009310 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00009311 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
9312 case OMPD_unknown:
9313 llvm_unreachable("Unknown OpenMP directive");
9314 }
9315 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009316 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009317 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00009318 case OMPD_parallel_for:
9319 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00009320 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00009321 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00009322 case OMPD_teams_distribute_parallel_for:
9323 case OMPD_teams_distribute_parallel_for_simd:
9324 case OMPD_target_parallel_for:
9325 case OMPD_target_parallel_for_simd:
9326 case OMPD_target_teams_distribute_parallel_for:
9327 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00009328 CaptureRegion = OMPD_parallel;
9329 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009330 case OMPD_for:
9331 case OMPD_for_simd:
9332 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009333 break;
9334 case OMPD_task:
9335 case OMPD_taskloop:
9336 case OMPD_taskloop_simd:
9337 case OMPD_target_data:
9338 case OMPD_target_enter_data:
9339 case OMPD_target_exit_data:
9340 case OMPD_target_update:
9341 case OMPD_teams:
9342 case OMPD_teams_distribute:
9343 case OMPD_teams_distribute_simd:
9344 case OMPD_target_teams_distribute:
9345 case OMPD_target_teams_distribute_simd:
9346 case OMPD_target:
9347 case OMPD_target_simd:
9348 case OMPD_target_parallel:
9349 case OMPD_cancel:
9350 case OMPD_parallel:
9351 case OMPD_parallel_sections:
9352 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009353 case OMPD_allocate:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009354 case OMPD_taskyield:
9355 case OMPD_barrier:
9356 case OMPD_taskwait:
9357 case OMPD_cancellation_point:
9358 case OMPD_flush:
9359 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009360 case OMPD_declare_mapper:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009361 case OMPD_declare_simd:
9362 case OMPD_declare_target:
9363 case OMPD_end_declare_target:
9364 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009365 case OMPD_sections:
9366 case OMPD_section:
9367 case OMPD_single:
9368 case OMPD_master:
9369 case OMPD_critical:
9370 case OMPD_taskgroup:
9371 case OMPD_distribute:
9372 case OMPD_ordered:
9373 case OMPD_atomic:
9374 case OMPD_distribute_simd:
9375 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00009376 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00009377 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9378 case OMPD_unknown:
9379 llvm_unreachable("Unknown OpenMP directive");
9380 }
9381 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009382 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009383 switch (DKind) {
9384 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009385 case OMPD_teams_distribute_parallel_for_simd:
9386 case OMPD_teams_distribute:
9387 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009388 case OMPD_target_teams_distribute_parallel_for:
9389 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009390 case OMPD_target_teams_distribute:
9391 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00009392 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009393 break;
9394 case OMPD_distribute_parallel_for:
9395 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009396 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009397 case OMPD_distribute_simd:
9398 // Do not capture thread_limit-clause expressions.
9399 break;
9400 case OMPD_parallel_for:
9401 case OMPD_parallel_for_simd:
9402 case OMPD_target_parallel_for_simd:
9403 case OMPD_target_parallel_for:
9404 case OMPD_task:
9405 case OMPD_taskloop:
9406 case OMPD_taskloop_simd:
9407 case OMPD_target_data:
9408 case OMPD_target_enter_data:
9409 case OMPD_target_exit_data:
9410 case OMPD_target_update:
9411 case OMPD_teams:
9412 case OMPD_target:
9413 case OMPD_target_simd:
9414 case OMPD_target_parallel:
9415 case OMPD_cancel:
9416 case OMPD_parallel:
9417 case OMPD_parallel_sections:
9418 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009419 case OMPD_allocate:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009420 case OMPD_taskyield:
9421 case OMPD_barrier:
9422 case OMPD_taskwait:
9423 case OMPD_cancellation_point:
9424 case OMPD_flush:
9425 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009426 case OMPD_declare_mapper:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009427 case OMPD_declare_simd:
9428 case OMPD_declare_target:
9429 case OMPD_end_declare_target:
9430 case OMPD_simd:
9431 case OMPD_for:
9432 case OMPD_for_simd:
9433 case OMPD_sections:
9434 case OMPD_section:
9435 case OMPD_single:
9436 case OMPD_master:
9437 case OMPD_critical:
9438 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009439 case OMPD_ordered:
9440 case OMPD_atomic:
9441 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00009442 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +00009443 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
9444 case OMPD_unknown:
9445 llvm_unreachable("Unknown OpenMP directive");
9446 }
9447 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009448 case OMPC_device:
9449 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009450 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00009451 case OMPD_target_enter_data:
9452 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00009453 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00009454 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00009455 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00009456 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00009457 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00009458 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00009459 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00009460 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00009461 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00009462 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00009463 CaptureRegion = OMPD_task;
9464 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00009465 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009466 // Do not capture device-clause expressions.
9467 break;
9468 case OMPD_teams_distribute_parallel_for:
9469 case OMPD_teams_distribute_parallel_for_simd:
9470 case OMPD_teams:
9471 case OMPD_teams_distribute:
9472 case OMPD_teams_distribute_simd:
9473 case OMPD_distribute_parallel_for:
9474 case OMPD_distribute_parallel_for_simd:
9475 case OMPD_task:
9476 case OMPD_taskloop:
9477 case OMPD_taskloop_simd:
9478 case OMPD_cancel:
9479 case OMPD_parallel:
9480 case OMPD_parallel_sections:
9481 case OMPD_parallel_for:
9482 case OMPD_parallel_for_simd:
9483 case OMPD_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009484 case OMPD_allocate:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009485 case OMPD_taskyield:
9486 case OMPD_barrier:
9487 case OMPD_taskwait:
9488 case OMPD_cancellation_point:
9489 case OMPD_flush:
9490 case OMPD_declare_reduction:
Michael Kruse251e1482019-02-01 20:25:04 +00009491 case OMPD_declare_mapper:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009492 case OMPD_declare_simd:
9493 case OMPD_declare_target:
9494 case OMPD_end_declare_target:
9495 case OMPD_simd:
9496 case OMPD_for:
9497 case OMPD_for_simd:
9498 case OMPD_sections:
9499 case OMPD_section:
9500 case OMPD_single:
9501 case OMPD_master:
9502 case OMPD_critical:
9503 case OMPD_taskgroup:
9504 case OMPD_distribute:
9505 case OMPD_ordered:
9506 case OMPD_atomic:
9507 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00009508 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +00009509 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
9510 case OMPD_unknown:
9511 llvm_unreachable("Unknown OpenMP directive");
9512 }
9513 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009514 case OMPC_firstprivate:
9515 case OMPC_lastprivate:
9516 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009517 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009518 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009519 case OMPC_linear:
9520 case OMPC_default:
9521 case OMPC_proc_bind:
9522 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009523 case OMPC_safelen:
9524 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009525 case OMPC_allocator:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009526 case OMPC_collapse:
9527 case OMPC_private:
9528 case OMPC_shared:
9529 case OMPC_aligned:
9530 case OMPC_copyin:
9531 case OMPC_copyprivate:
9532 case OMPC_ordered:
9533 case OMPC_nowait:
9534 case OMPC_untied:
9535 case OMPC_mergeable:
9536 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009537 case OMPC_allocate:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009538 case OMPC_flush:
9539 case OMPC_read:
9540 case OMPC_write:
9541 case OMPC_update:
9542 case OMPC_capture:
9543 case OMPC_seq_cst:
9544 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009545 case OMPC_threads:
9546 case OMPC_simd:
9547 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009548 case OMPC_priority:
9549 case OMPC_grainsize:
9550 case OMPC_nogroup:
9551 case OMPC_num_tasks:
9552 case OMPC_hint:
9553 case OMPC_defaultmap:
9554 case OMPC_unknown:
9555 case OMPC_uniform:
9556 case OMPC_to:
9557 case OMPC_from:
9558 case OMPC_use_device_ptr:
9559 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009560 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009561 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009562 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009563 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009564 case OMPC_atomic_default_mem_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009565 llvm_unreachable("Unexpected OpenMP clause.");
9566 }
9567 return CaptureRegion;
9568}
9569
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009570OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
9571 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009572 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009573 SourceLocation NameModifierLoc,
9574 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009575 SourceLocation EndLoc) {
9576 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009577 Stmt *HelperValStmt = nullptr;
9578 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009579 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9580 !Condition->isInstantiationDependent() &&
9581 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009582 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009583 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009584 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009585
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009586 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009587
9588 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
9589 CaptureRegion =
9590 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00009591 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009592 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009593 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009594 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9595 HelperValStmt = buildPreInits(Context, Captures);
9596 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009597 }
9598
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00009599 return new (Context)
9600 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
9601 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009602}
9603
Alexey Bataev3778b602014-07-17 07:32:53 +00009604OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
9605 SourceLocation StartLoc,
9606 SourceLocation LParenLoc,
9607 SourceLocation EndLoc) {
9608 Expr *ValExpr = Condition;
9609 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
9610 !Condition->isInstantiationDependent() &&
9611 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00009612 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00009613 if (Val.isInvalid())
9614 return nullptr;
9615
Richard Smith03a4aa32016-06-23 19:02:52 +00009616 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00009617 }
9618
9619 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
9620}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00009621ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
9622 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00009623 if (!Op)
9624 return ExprError();
9625
9626 class IntConvertDiagnoser : public ICEConvertDiagnoser {
9627 public:
9628 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00009629 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00009630 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
9631 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009632 return S.Diag(Loc, diag::err_omp_not_integral) << T;
9633 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009634 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
9635 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009636 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
9637 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009638 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
9639 QualType T,
9640 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009641 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
9642 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009643 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
9644 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009645 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009646 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009647 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009648 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
9649 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009650 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
9651 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009652 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
9653 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009654 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00009655 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00009656 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009657 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
9658 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00009659 llvm_unreachable("conversion functions are permitted");
9660 }
9661 } ConvertDiagnoser;
9662 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
9663}
9664
Alexey Bataeve3727102018-04-18 15:57:46 +00009665static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00009666 OpenMPClauseKind CKind,
9667 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009668 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
9669 !ValExpr->isInstantiationDependent()) {
9670 SourceLocation Loc = ValExpr->getExprLoc();
9671 ExprResult Value =
9672 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
9673 if (Value.isInvalid())
9674 return false;
9675
9676 ValExpr = Value.get();
9677 // The expression must evaluate to a non-negative integer value.
9678 llvm::APSInt Result;
9679 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00009680 Result.isSigned() &&
9681 !((!StrictlyPositive && Result.isNonNegative()) ||
9682 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009683 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009684 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9685 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009686 return false;
9687 }
9688 }
9689 return true;
9690}
9691
Alexey Bataev568a8332014-03-06 06:15:19 +00009692OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
9693 SourceLocation StartLoc,
9694 SourceLocation LParenLoc,
9695 SourceLocation EndLoc) {
9696 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009697 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009698
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009699 // OpenMP [2.5, Restrictions]
9700 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +00009701 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +00009702 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009703 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00009704
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009705 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00009706 OpenMPDirectiveKind CaptureRegion =
9707 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
9708 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009709 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009710 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00009711 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9712 HelperValStmt = buildPreInits(Context, Captures);
9713 }
9714
9715 return new (Context) OMPNumThreadsClause(
9716 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00009717}
9718
Alexey Bataev62c87d22014-03-21 04:51:18 +00009719ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009720 OpenMPClauseKind CKind,
9721 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009722 if (!E)
9723 return ExprError();
9724 if (E->isValueDependent() || E->isTypeDependent() ||
9725 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00009726 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009727 llvm::APSInt Result;
9728 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
9729 if (ICE.isInvalid())
9730 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009731 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9732 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009733 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009734 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9735 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00009736 return ExprError();
9737 }
Alexander Musman09184fe2014-09-30 05:29:28 +00009738 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9739 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9740 << E->getSourceRange();
9741 return ExprError();
9742 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009743 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9744 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00009745 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009746 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00009747 return ICE;
9748}
9749
9750OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9751 SourceLocation LParenLoc,
9752 SourceLocation EndLoc) {
9753 // OpenMP [2.8.1, simd construct, Description]
9754 // The parameter of the safelen clause must be a constant
9755 // positive integer expression.
9756 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9757 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009758 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009759 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009760 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00009761}
9762
Alexey Bataev66b15b52015-08-21 11:14:16 +00009763OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9764 SourceLocation LParenLoc,
9765 SourceLocation EndLoc) {
9766 // OpenMP [2.8.1, simd construct, Description]
9767 // The parameter of the simdlen clause must be a constant
9768 // positive integer expression.
9769 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9770 if (Simdlen.isInvalid())
9771 return nullptr;
9772 return new (Context)
9773 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9774}
9775
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009776/// Tries to find omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +00009777static bool findOMPAllocatorHandleT(Sema &S, SourceLocation Loc,
9778 DSAStackTy *Stack) {
9779 QualType OMPAllocatorHandleT = Stack->getOMPAllocatorHandleT();
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009780 if (!OMPAllocatorHandleT.isNull())
9781 return true;
Alexey Bataev27ef9512019-03-20 20:14:22 +00009782 // Build the predefined allocator expressions.
9783 bool ErrorFound = false;
9784 for (int I = OMPAllocateDeclAttr::OMPDefaultMemAlloc;
9785 I < OMPAllocateDeclAttr::OMPUserDefinedMemAlloc; ++I) {
9786 auto AllocatorKind = static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(I);
9787 StringRef Allocator =
9788 OMPAllocateDeclAttr::ConvertAllocatorTypeTyToStr(AllocatorKind);
9789 DeclarationName AllocatorName = &S.getASTContext().Idents.get(Allocator);
9790 auto *VD = dyn_cast_or_null<ValueDecl>(
9791 S.LookupSingleName(S.TUScope, AllocatorName, Loc, Sema::LookupAnyName));
9792 if (!VD) {
9793 ErrorFound = true;
9794 break;
9795 }
9796 QualType AllocatorType =
9797 VD->getType().getNonLValueExprType(S.getASTContext());
9798 ExprResult Res = S.BuildDeclRefExpr(VD, AllocatorType, VK_LValue, Loc);
9799 if (!Res.isUsable()) {
9800 ErrorFound = true;
9801 break;
9802 }
9803 if (OMPAllocatorHandleT.isNull())
9804 OMPAllocatorHandleT = AllocatorType;
9805 if (!S.getASTContext().hasSameType(OMPAllocatorHandleT, AllocatorType)) {
9806 ErrorFound = true;
9807 break;
9808 }
9809 Stack->setAllocator(AllocatorKind, Res.get());
9810 }
9811 if (ErrorFound) {
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009812 S.Diag(Loc, diag::err_implied_omp_allocator_handle_t_not_found);
9813 return false;
9814 }
Alexey Bataev27ef9512019-03-20 20:14:22 +00009815 OMPAllocatorHandleT.addConst();
9816 Stack->setOMPAllocatorHandleT(OMPAllocatorHandleT);
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009817 return true;
9818}
9819
9820OMPClause *Sema::ActOnOpenMPAllocatorClause(Expr *A, SourceLocation StartLoc,
9821 SourceLocation LParenLoc,
9822 SourceLocation EndLoc) {
9823 // OpenMP [2.11.3, allocate Directive, Description]
9824 // allocator is an expression of omp_allocator_handle_t type.
Alexey Bataev27ef9512019-03-20 20:14:22 +00009825 if (!findOMPAllocatorHandleT(*this, A->getExprLoc(), DSAStack))
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009826 return nullptr;
9827
9828 ExprResult Allocator = DefaultLvalueConversion(A);
9829 if (Allocator.isInvalid())
9830 return nullptr;
Alexey Bataev27ef9512019-03-20 20:14:22 +00009831 Allocator = PerformImplicitConversion(Allocator.get(),
9832 DSAStack->getOMPAllocatorHandleT(),
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009833 Sema::AA_Initializing,
9834 /*AllowExplicit=*/true);
9835 if (Allocator.isInvalid())
9836 return nullptr;
9837 return new (Context)
9838 OMPAllocatorClause(Allocator.get(), StartLoc, LParenLoc, EndLoc);
9839}
9840
Alexander Musman64d33f12014-06-04 07:53:32 +00009841OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
9842 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00009843 SourceLocation LParenLoc,
9844 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00009845 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009846 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00009847 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009848 // The parameter of the collapse clause must be a constant
9849 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00009850 ExprResult NumForLoopsResult =
9851 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
9852 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00009853 return nullptr;
9854 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00009855 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00009856}
9857
Alexey Bataev10e775f2015-07-30 11:36:16 +00009858OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
9859 SourceLocation EndLoc,
9860 SourceLocation LParenLoc,
9861 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00009862 // OpenMP [2.7.1, loop construct, Description]
9863 // OpenMP [2.8.1, simd construct, Description]
9864 // OpenMP [2.9.6, distribute construct, Description]
9865 // The parameter of the ordered clause must be a constant
9866 // positive integer expression if any.
9867 if (NumForLoops && LParenLoc.isValid()) {
9868 ExprResult NumForLoopsResult =
9869 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
9870 if (NumForLoopsResult.isInvalid())
9871 return nullptr;
9872 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009873 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +00009874 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00009875 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009876 auto *Clause = OMPOrderedClause::Create(
9877 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
9878 StartLoc, LParenLoc, EndLoc);
9879 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
9880 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +00009881}
9882
Alexey Bataeved09d242014-05-28 05:53:51 +00009883OMPClause *Sema::ActOnOpenMPSimpleClause(
9884 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
9885 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009886 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009887 switch (Kind) {
9888 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009889 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00009890 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
9891 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009892 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009893 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00009894 Res = ActOnOpenMPProcBindClause(
9895 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
9896 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009897 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009898 case OMPC_atomic_default_mem_order:
9899 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
9900 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
9901 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9902 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009903 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009904 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009905 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009906 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009907 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +00009908 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009909 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009910 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009911 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009912 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00009913 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009914 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00009915 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009916 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009917 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00009918 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009919 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009920 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009921 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009922 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009923 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009924 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009925 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009926 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +00009927 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009928 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009929 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009930 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009931 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009932 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009933 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009934 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009935 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009936 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009937 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009938 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009939 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009940 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009941 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009942 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009943 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009944 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009945 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009946 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009947 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009948 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009949 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009950 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009951 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009952 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009953 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009954 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009955 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009956 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009957 case OMPC_dynamic_allocators:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009958 llvm_unreachable("Clause is not allowed.");
9959 }
9960 return Res;
9961}
9962
Alexey Bataev6402bca2015-12-28 07:25:51 +00009963static std::string
9964getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
9965 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009966 SmallString<256> Buffer;
9967 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +00009968 unsigned Bound = Last >= 2 ? Last - 2 : 0;
9969 unsigned Skipped = Exclude.size();
9970 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +00009971 for (unsigned I = First; I < Last; ++I) {
9972 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009973 --Skipped;
9974 continue;
9975 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009976 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
9977 if (I == Bound - Skipped)
9978 Out << " or ";
9979 else if (I != Bound + 1 - Skipped)
9980 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +00009981 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009982 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +00009983}
9984
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009985OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9986 SourceLocation KindKwLoc,
9987 SourceLocation StartLoc,
9988 SourceLocation LParenLoc,
9989 SourceLocation EndLoc) {
9990 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00009991 static_assert(OMPC_DEFAULT_unknown > 0,
9992 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009993 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009994 << getListOfPossibleValues(OMPC_default, /*First=*/0,
9995 /*Last=*/OMPC_DEFAULT_unknown)
9996 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009997 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009998 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00009999 switch (Kind) {
10000 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010001 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010002 break;
10003 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010004 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010005 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010006 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010007 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +000010008 break;
10009 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010010 return new (Context)
10011 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010012}
10013
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010014OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
10015 SourceLocation KindKwLoc,
10016 SourceLocation StartLoc,
10017 SourceLocation LParenLoc,
10018 SourceLocation EndLoc) {
10019 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010020 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000010021 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
10022 /*Last=*/OMPC_PROC_BIND_unknown)
10023 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010024 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010025 }
Alexey Bataeved09d242014-05-28 05:53:51 +000010026 return new (Context)
10027 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010028}
10029
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010030OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
10031 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
10032 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
10033 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
10034 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
10035 << getListOfPossibleValues(
10036 OMPC_atomic_default_mem_order, /*First=*/0,
10037 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
10038 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
10039 return nullptr;
10040 }
10041 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
10042 LParenLoc, EndLoc);
10043}
10044
Alexey Bataev56dafe82014-06-20 07:16:17 +000010045OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000010046 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +000010047 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000010048 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +000010049 SourceLocation EndLoc) {
10050 OMPClause *Res = nullptr;
10051 switch (Kind) {
10052 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +000010053 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
10054 assert(Argument.size() == NumberOfElements &&
10055 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010056 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000010057 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
10058 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
10059 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
10060 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
10061 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010062 break;
10063 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +000010064 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
10065 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
10066 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
10067 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010068 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +000010069 case OMPC_dist_schedule:
10070 Res = ActOnOpenMPDistScheduleClause(
10071 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
10072 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
10073 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010074 case OMPC_defaultmap:
10075 enum { Modifier, DefaultmapKind };
10076 Res = ActOnOpenMPDefaultmapClause(
10077 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
10078 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +000010079 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
10080 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010081 break;
Alexey Bataev3778b602014-07-17 07:32:53 +000010082 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010083 case OMPC_num_threads:
10084 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010085 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010086 case OMPC_allocator:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010087 case OMPC_collapse:
10088 case OMPC_default:
10089 case OMPC_proc_bind:
10090 case OMPC_private:
10091 case OMPC_firstprivate:
10092 case OMPC_lastprivate:
10093 case OMPC_shared:
10094 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010095 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010096 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010097 case OMPC_linear:
10098 case OMPC_aligned:
10099 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010100 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010101 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010102 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010103 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010104 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010105 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010106 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010107 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010108 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010109 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010110 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010111 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010112 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010113 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000010114 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010115 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010116 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010117 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010118 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010119 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010120 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010121 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000010122 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000010123 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010124 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010125 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010126 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010127 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010128 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010129 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010130 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +000010131 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010132 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010133 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010134 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010135 case OMPC_atomic_default_mem_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010136 llvm_unreachable("Clause is not allowed.");
10137 }
10138 return Res;
10139}
10140
Alexey Bataev6402bca2015-12-28 07:25:51 +000010141static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
10142 OpenMPScheduleClauseModifier M2,
10143 SourceLocation M1Loc, SourceLocation M2Loc) {
10144 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
10145 SmallVector<unsigned, 2> Excluded;
10146 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
10147 Excluded.push_back(M2);
10148 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
10149 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
10150 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
10151 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
10152 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
10153 << getListOfPossibleValues(OMPC_schedule,
10154 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
10155 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
10156 Excluded)
10157 << getOpenMPClauseName(OMPC_schedule);
10158 return true;
10159 }
10160 return false;
10161}
10162
Alexey Bataev56dafe82014-06-20 07:16:17 +000010163OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +000010164 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +000010165 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +000010166 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
10167 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
10168 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
10169 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
10170 return nullptr;
10171 // OpenMP, 2.7.1, Loop Construct, Restrictions
10172 // Either the monotonic modifier or the nonmonotonic modifier can be specified
10173 // but not both.
10174 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
10175 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
10176 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
10177 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
10178 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
10179 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
10180 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
10181 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
10182 return nullptr;
10183 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000010184 if (Kind == OMPC_SCHEDULE_unknown) {
10185 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +000010186 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
10187 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
10188 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
10189 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
10190 Exclude);
10191 } else {
10192 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
10193 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010194 }
10195 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
10196 << Values << getOpenMPClauseName(OMPC_schedule);
10197 return nullptr;
10198 }
Alexey Bataev6402bca2015-12-28 07:25:51 +000010199 // OpenMP, 2.7.1, Loop Construct, Restrictions
10200 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
10201 // schedule(guided).
10202 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
10203 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
10204 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
10205 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
10206 diag::err_omp_schedule_nonmonotonic_static);
10207 return nullptr;
10208 }
Alexey Bataev56dafe82014-06-20 07:16:17 +000010209 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000010210 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +000010211 if (ChunkSize) {
10212 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
10213 !ChunkSize->isInstantiationDependent() &&
10214 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000010215 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +000010216 ExprResult Val =
10217 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
10218 if (Val.isInvalid())
10219 return nullptr;
10220
10221 ValExpr = Val.get();
10222
10223 // OpenMP [2.7.1, Restrictions]
10224 // chunk_size must be a loop invariant integer expression with a positive
10225 // value.
10226 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +000010227 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
10228 if (Result.isSigned() && !Result.isStrictlyPositive()) {
10229 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +000010230 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +000010231 return nullptr;
10232 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000010233 } else if (getOpenMPCaptureRegionForClause(
10234 DSAStack->getCurrentDirective(), OMPC_schedule) !=
10235 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000010236 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000010237 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000010238 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000010239 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
10240 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010241 }
10242 }
10243 }
10244
Alexey Bataev6402bca2015-12-28 07:25:51 +000010245 return new (Context)
10246 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +000010247 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +000010248}
10249
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010250OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
10251 SourceLocation StartLoc,
10252 SourceLocation EndLoc) {
10253 OMPClause *Res = nullptr;
10254 switch (Kind) {
10255 case OMPC_ordered:
10256 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
10257 break;
Alexey Bataev236070f2014-06-20 11:19:47 +000010258 case OMPC_nowait:
10259 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
10260 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010261 case OMPC_untied:
10262 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
10263 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010264 case OMPC_mergeable:
10265 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
10266 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010267 case OMPC_read:
10268 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
10269 break;
Alexey Bataevdea47612014-07-23 07:46:59 +000010270 case OMPC_write:
10271 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
10272 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +000010273 case OMPC_update:
10274 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
10275 break;
Alexey Bataev459dec02014-07-24 06:46:57 +000010276 case OMPC_capture:
10277 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
10278 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010279 case OMPC_seq_cst:
10280 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
10281 break;
Alexey Bataev346265e2015-09-25 10:37:12 +000010282 case OMPC_threads:
10283 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
10284 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010285 case OMPC_simd:
10286 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
10287 break;
Alexey Bataevb825de12015-12-07 10:51:44 +000010288 case OMPC_nogroup:
10289 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
10290 break;
Kelvin Li1408f912018-09-26 04:28:39 +000010291 case OMPC_unified_address:
10292 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
10293 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +000010294 case OMPC_unified_shared_memory:
10295 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10296 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010297 case OMPC_reverse_offload:
10298 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
10299 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010300 case OMPC_dynamic_allocators:
10301 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
10302 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010303 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010304 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010305 case OMPC_num_threads:
10306 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010307 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010308 case OMPC_allocator:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010309 case OMPC_collapse:
10310 case OMPC_schedule:
10311 case OMPC_private:
10312 case OMPC_firstprivate:
10313 case OMPC_lastprivate:
10314 case OMPC_shared:
10315 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +000010316 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +000010317 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010318 case OMPC_linear:
10319 case OMPC_aligned:
10320 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +000010321 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010322 case OMPC_default:
10323 case OMPC_proc_bind:
10324 case OMPC_threadprivate:
Alexey Bataev25ed0c02019-03-07 17:54:44 +000010325 case OMPC_allocate:
Alexey Bataev6125da92014-07-21 11:26:11 +000010326 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010327 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +000010328 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +000010329 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010330 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010331 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010332 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010333 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +000010334 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010335 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010336 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010337 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010338 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010339 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +000010340 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +000010341 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +000010342 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +000010343 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010344 case OMPC_atomic_default_mem_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010345 llvm_unreachable("Clause is not allowed.");
10346 }
10347 return Res;
10348}
10349
Alexey Bataev236070f2014-06-20 11:19:47 +000010350OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
10351 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +000010352 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +000010353 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
10354}
10355
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010356OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
10357 SourceLocation EndLoc) {
10358 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
10359}
10360
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010361OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
10362 SourceLocation EndLoc) {
10363 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
10364}
10365
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010366OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
10367 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010368 return new (Context) OMPReadClause(StartLoc, EndLoc);
10369}
10370
Alexey Bataevdea47612014-07-23 07:46:59 +000010371OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
10372 SourceLocation EndLoc) {
10373 return new (Context) OMPWriteClause(StartLoc, EndLoc);
10374}
10375
Alexey Bataev67a4f222014-07-23 10:25:33 +000010376OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
10377 SourceLocation EndLoc) {
10378 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
10379}
10380
Alexey Bataev459dec02014-07-24 06:46:57 +000010381OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
10382 SourceLocation EndLoc) {
10383 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
10384}
10385
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010386OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
10387 SourceLocation EndLoc) {
10388 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
10389}
10390
Alexey Bataev346265e2015-09-25 10:37:12 +000010391OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
10392 SourceLocation EndLoc) {
10393 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
10394}
10395
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010396OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
10397 SourceLocation EndLoc) {
10398 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
10399}
10400
Alexey Bataevb825de12015-12-07 10:51:44 +000010401OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
10402 SourceLocation EndLoc) {
10403 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
10404}
10405
Kelvin Li1408f912018-09-26 04:28:39 +000010406OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
10407 SourceLocation EndLoc) {
10408 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
10409}
10410
Patrick Lyster4a370b92018-10-01 13:47:43 +000010411OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
10412 SourceLocation EndLoc) {
10413 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
10414}
10415
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010416OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
10417 SourceLocation EndLoc) {
10418 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
10419}
10420
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010421OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
10422 SourceLocation EndLoc) {
10423 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
10424}
10425
Alexey Bataevc5e02582014-06-16 07:08:35 +000010426OMPClause *Sema::ActOnOpenMPVarListClause(
10427 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010428 const OMPVarListLocTy &Locs, SourceLocation ColonLoc,
10429 CXXScopeSpec &ReductionOrMapperIdScopeSpec,
10430 DeclarationNameInfo &ReductionOrMapperId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +000010431 OpenMPLinearClauseKind LinKind,
10432 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010433 ArrayRef<SourceLocation> MapTypeModifiersLoc, OpenMPMapClauseKind MapType,
10434 bool IsMapTypeImplicit, SourceLocation DepLinMapLoc) {
10435 SourceLocation StartLoc = Locs.StartLoc;
10436 SourceLocation LParenLoc = Locs.LParenLoc;
10437 SourceLocation EndLoc = Locs.EndLoc;
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010438 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010439 switch (Kind) {
10440 case OMPC_private:
10441 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10442 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010443 case OMPC_firstprivate:
10444 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10445 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010446 case OMPC_lastprivate:
10447 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10448 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010449 case OMPC_shared:
10450 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
10451 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010452 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +000010453 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010454 EndLoc, ReductionOrMapperIdScopeSpec,
10455 ReductionOrMapperId);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010456 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +000010457 case OMPC_task_reduction:
10458 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
Michael Kruse4304e9d2019-02-19 16:38:20 +000010459 EndLoc, ReductionOrMapperIdScopeSpec,
10460 ReductionOrMapperId);
Alexey Bataev169d96a2017-07-18 20:17:46 +000010461 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +000010462 case OMPC_in_reduction:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010463 Res = ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
10464 EndLoc, ReductionOrMapperIdScopeSpec,
10465 ReductionOrMapperId);
Alexey Bataevfa312f32017-07-21 18:48:21 +000010466 break;
Alexander Musman8dba6642014-04-22 13:09:42 +000010467 case OMPC_linear:
10468 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010469 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +000010470 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000010471 case OMPC_aligned:
10472 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
10473 ColonLoc, EndLoc);
10474 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000010475 case OMPC_copyin:
10476 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
10477 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +000010478 case OMPC_copyprivate:
10479 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
10480 break;
Alexey Bataev6125da92014-07-21 11:26:11 +000010481 case OMPC_flush:
10482 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
10483 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010484 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +000010485 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +000010486 StartLoc, LParenLoc, EndLoc);
10487 break;
10488 case OMPC_map:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010489 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc,
10490 ReductionOrMapperIdScopeSpec,
10491 ReductionOrMapperId, MapType, IsMapTypeImplicit,
10492 DepLinMapLoc, ColonLoc, VarList, Locs);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000010493 break;
Samuel Antao661c0902016-05-26 17:39:58 +000010494 case OMPC_to:
Michael Kruse01f670d2019-02-22 22:29:42 +000010495 Res = ActOnOpenMPToClause(VarList, ReductionOrMapperIdScopeSpec,
10496 ReductionOrMapperId, Locs);
Samuel Antao661c0902016-05-26 17:39:58 +000010497 break;
Samuel Antaoec172c62016-05-26 17:49:04 +000010498 case OMPC_from:
Michael Kruse0336c752019-02-25 20:34:15 +000010499 Res = ActOnOpenMPFromClause(VarList, ReductionOrMapperIdScopeSpec,
10500 ReductionOrMapperId, Locs);
Samuel Antaoec172c62016-05-26 17:49:04 +000010501 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +000010502 case OMPC_use_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010503 Res = ActOnOpenMPUseDevicePtrClause(VarList, Locs);
Carlo Bertolli2404b172016-07-13 15:37:16 +000010504 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +000010505 case OMPC_is_device_ptr:
Michael Kruse4304e9d2019-02-19 16:38:20 +000010506 Res = ActOnOpenMPIsDevicePtrClause(VarList, Locs);
Carlo Bertolli70594e92016-07-13 17:16:49 +000010507 break;
Alexey Bataeve04483e2019-03-27 14:14:31 +000010508 case OMPC_allocate:
10509 Res = ActOnOpenMPAllocateClause(TailExpr, VarList, StartLoc, LParenLoc,
10510 ColonLoc, EndLoc);
10511 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +000010512 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +000010513 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +000010514 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +000010515 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +000010516 case OMPC_simdlen:
Alexey Bataev9cc10fc2019-03-12 18:52:33 +000010517 case OMPC_allocator:
Alexander Musman8bd31e62014-05-27 15:12:19 +000010518 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010519 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +000010520 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +000010521 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +000010522 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +000010523 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +000010524 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +000010525 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010526 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +000010527 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +000010528 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +000010529 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +000010530 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +000010531 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +000010532 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +000010533 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +000010534 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +000010535 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +000010536 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +000010537 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000010538 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +000010539 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +000010540 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +000010541 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +000010542 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000010543 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010544 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +000010545 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +000010546 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +000010547 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +000010548 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +000010549 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +000010550 case OMPC_atomic_default_mem_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010551 llvm_unreachable("Clause is not allowed.");
10552 }
10553 return Res;
10554}
10555
Alexey Bataev90c228f2016-02-08 09:29:13 +000010556ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +000010557 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +000010558 ExprResult Res = BuildDeclRefExpr(
10559 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
10560 if (!Res.isUsable())
10561 return ExprError();
10562 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
10563 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
10564 if (!Res.isUsable())
10565 return ExprError();
10566 }
10567 if (VK != VK_LValue && Res.get()->isGLValue()) {
10568 Res = DefaultLvalueConversion(Res.get());
10569 if (!Res.isUsable())
10570 return ExprError();
10571 }
10572 return Res;
10573}
10574
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010575OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
10576 SourceLocation StartLoc,
10577 SourceLocation LParenLoc,
10578 SourceLocation EndLoc) {
10579 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +000010580 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +000010581 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010582 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010583 SourceLocation ELoc;
10584 SourceRange ERange;
10585 Expr *SimpleRefExpr = RefExpr;
10586 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010587 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010588 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010589 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010590 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010591 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010592 ValueDecl *D = Res.first;
10593 if (!D)
10594 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010595
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010596 QualType Type = D->getType();
10597 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010598
10599 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10600 // A variable that appears in a private clause must not have an incomplete
10601 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010602 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010603 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010604 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010605
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010606 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10607 // A variable that is privatized must not have a const-qualified type
10608 // unless it is of class type with a mutable member. This restriction does
10609 // not apply to the firstprivate clause.
10610 //
10611 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
10612 // A variable that appears in a private clause must not have a
10613 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010614 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010615 continue;
10616
Alexey Bataev758e55e2013-09-06 18:03:48 +000010617 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10618 // in a Construct]
10619 // Variables with the predetermined data-sharing attributes may not be
10620 // listed in data-sharing attributes clauses, except for the cases
10621 // listed below. For these exceptions only, listing a predetermined
10622 // variable in a data-sharing attribute clause is allowed and overrides
10623 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010624 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010625 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010626 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10627 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +000010628 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010629 continue;
10630 }
10631
Alexey Bataeve3727102018-04-18 15:57:46 +000010632 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010633 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010634 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +000010635 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010636 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10637 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +000010638 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010639 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010640 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010641 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010642 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010643 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010644 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010645 continue;
10646 }
10647
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010648 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10649 // A list item cannot appear in both a map clause and a data-sharing
10650 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000010651 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010652 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010653 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010654 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000010655 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
10656 OpenMPClauseKind WhereFoundClauseKind) -> bool {
10657 ConflictKind = WhereFoundClauseKind;
10658 return true;
10659 })) {
10660 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010661 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +000010662 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +000010663 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +000010664 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010665 continue;
10666 }
10667 }
10668
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010669 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
10670 // A variable of class type (or array thereof) that appears in a private
10671 // clause requires an accessible, unambiguous default constructor for the
10672 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +000010673 // Generate helper private variable and initialize it with the default
10674 // value. The address of the original variable is replaced by the address of
10675 // the new private variable in CodeGen. This new variable is not added to
10676 // IdResolver, so the code in the OpenMP region uses original variable for
10677 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010678 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010679 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010680 buildVarDecl(*this, ELoc, Type, D->getName(),
10681 D->hasAttrs() ? &D->getAttrs() : nullptr,
10682 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +000010683 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010684 if (VDPrivate->isInvalidDecl())
10685 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +000010686 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000010687 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010688
Alexey Bataev90c228f2016-02-08 09:29:13 +000010689 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010690 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010691 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +000010692 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010693 Vars.push_back((VD || CurContext->isDependentContext())
10694 ? RefExpr->IgnoreParens()
10695 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +000010696 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010697 }
10698
Alexey Bataeved09d242014-05-28 05:53:51 +000010699 if (Vars.empty())
10700 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010701
Alexey Bataev03b340a2014-10-21 03:16:40 +000010702 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
10703 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000010704}
10705
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010706namespace {
10707class DiagsUninitializedSeveretyRAII {
10708private:
10709 DiagnosticsEngine &Diags;
10710 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +000010711 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010712
10713public:
10714 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
10715 bool IsIgnored)
10716 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
10717 if (!IsIgnored) {
10718 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
10719 /*Map*/ diag::Severity::Ignored, Loc);
10720 }
10721 }
10722 ~DiagsUninitializedSeveretyRAII() {
10723 if (!IsIgnored)
10724 Diags.popMappings(SavedLoc);
10725 }
10726};
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010727}
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010728
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010729OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
10730 SourceLocation StartLoc,
10731 SourceLocation LParenLoc,
10732 SourceLocation EndLoc) {
10733 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010734 SmallVector<Expr *, 8> PrivateCopies;
10735 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +000010736 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010737 bool IsImplicitClause =
10738 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +000010739 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010740
Alexey Bataeve3727102018-04-18 15:57:46 +000010741 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000010742 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010743 SourceLocation ELoc;
10744 SourceRange ERange;
10745 Expr *SimpleRefExpr = RefExpr;
10746 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +000010747 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010748 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010749 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010750 PrivateCopies.push_back(nullptr);
10751 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010752 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010753 ValueDecl *D = Res.first;
10754 if (!D)
10755 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010756
Alexey Bataev60da77e2016-02-29 05:54:20 +000010757 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010758 QualType Type = D->getType();
10759 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010760
10761 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10762 // A variable that appears in a private clause must not have an incomplete
10763 // type or a reference type.
10764 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000010765 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010766 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010767 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010768
10769 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10770 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000010771 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010772 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000010773 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010774
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010775 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000010776 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010777 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010778 DSAStackTy::DSAVarData DVar =
10779 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000010780 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010781 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010782 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010783 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10784 // A list item that specifies a given variable may not appear in more
10785 // than one clause on the same directive, except that a variable may be
10786 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010787 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10788 // A list item may appear in a firstprivate or lastprivate clause but not
10789 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010790 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010791 (isOpenMPDistributeDirective(CurrDir) ||
10792 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010793 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010794 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010795 << getOpenMPClauseName(DVar.CKind)
10796 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010797 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010798 continue;
10799 }
10800
10801 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10802 // in a Construct]
10803 // Variables with the predetermined data-sharing attributes may not be
10804 // listed in data-sharing attributes clauses, except for the cases
10805 // listed below. For these exceptions only, listing a predetermined
10806 // variable in a data-sharing attribute clause is allowed and overrides
10807 // the variable's predetermined data-sharing attributes.
10808 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10809 // in a Construct, C/C++, p.2]
10810 // Variables with const-qualified type having no mutable member may be
10811 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000010812 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010813 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
10814 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010815 << getOpenMPClauseName(DVar.CKind)
10816 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010817 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010818 continue;
10819 }
10820
10821 // OpenMP [2.9.3.4, Restrictions, p.2]
10822 // A list item that is private within a parallel region must not appear
10823 // in a firstprivate clause on a worksharing construct if any of the
10824 // worksharing regions arising from the worksharing construct ever bind
10825 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010826 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10827 // A list item that is private within a teams region must not appear in a
10828 // firstprivate clause on a distribute construct if any of the distribute
10829 // regions arising from the distribute construct ever bind to any of the
10830 // teams regions arising from the teams construct.
10831 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10832 // A list item that appears in a reduction clause of a teams construct
10833 // must not appear in a firstprivate clause on a distribute construct if
10834 // any of the distribute regions arising from the distribute construct
10835 // ever bind to any of the teams regions arising from the teams construct.
10836 if ((isOpenMPWorksharingDirective(CurrDir) ||
10837 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010838 !isOpenMPParallelDirective(CurrDir) &&
10839 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010840 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010841 if (DVar.CKind != OMPC_shared &&
10842 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010843 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010844 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000010845 Diag(ELoc, diag::err_omp_required_access)
10846 << getOpenMPClauseName(OMPC_firstprivate)
10847 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010848 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010849 continue;
10850 }
10851 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010852 // OpenMP [2.9.3.4, Restrictions, p.3]
10853 // A list item that appears in a reduction clause of a parallel construct
10854 // must not appear in a firstprivate clause on a worksharing or task
10855 // construct if any of the worksharing or task regions arising from the
10856 // worksharing or task construct ever bind to any of the parallel regions
10857 // arising from the parallel construct.
10858 // OpenMP [2.9.3.4, Restrictions, p.4]
10859 // A list item that appears in a reduction clause in worksharing
10860 // construct must not appear in a firstprivate clause in a task construct
10861 // encountered during execution of any of the worksharing regions arising
10862 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000010863 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010864 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010865 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10866 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010867 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010868 isOpenMPWorksharingDirective(K) ||
10869 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010870 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010871 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010872 if (DVar.CKind == OMPC_reduction &&
10873 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010874 isOpenMPWorksharingDirective(DVar.DKind) ||
10875 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010876 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10877 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000010878 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010879 continue;
10880 }
10881 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010882
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010883 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10884 // A list item cannot appear in both a map clause and a data-sharing
10885 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +000010886 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010887 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010888 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010889 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000010890 [&ConflictKind](
10891 OMPClauseMappableExprCommon::MappableExprComponentListRef,
10892 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000010893 ConflictKind = WhereFoundClauseKind;
10894 return true;
10895 })) {
10896 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010897 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000010898 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010899 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000010900 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010901 continue;
10902 }
10903 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010904 }
10905
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010906 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010907 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000010908 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010909 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10910 << getOpenMPClauseName(OMPC_firstprivate) << Type
10911 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10912 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010913 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010914 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010915 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010916 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000010917 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010918 continue;
10919 }
10920
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010921 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010922 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010923 buildVarDecl(*this, ELoc, Type, D->getName(),
10924 D->hasAttrs() ? &D->getAttrs() : nullptr,
10925 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010926 // Generate helper private variable and initialize it with the value of the
10927 // original variable. The address of the original variable is replaced by
10928 // the address of the new private variable in the CodeGen. This new variable
10929 // is not added to IdResolver, so the code in the OpenMP region uses
10930 // original variable for proper diagnostics and variable capturing.
10931 Expr *VDInitRefExpr = nullptr;
10932 // For arrays generate initializer for single element and replace it by the
10933 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010934 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010935 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010936 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010937 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010938 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010939 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010940 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
10941 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000010942 InitializedEntity Entity =
10943 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010944 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
10945
10946 InitializationSequence InitSeq(*this, Entity, Kind, Init);
10947 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
10948 if (Result.isInvalid())
10949 VDPrivate->setInvalidDecl();
10950 else
10951 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010952 // Remove temp variable declaration.
10953 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010954 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000010955 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
10956 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000010957 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10958 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000010959 AddInitializerToDecl(VDPrivate,
10960 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010961 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010962 }
10963 if (VDPrivate->isInvalidDecl()) {
10964 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010965 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010966 diag::note_omp_task_predetermined_firstprivate_here);
10967 }
10968 continue;
10969 }
10970 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010971 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000010972 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10973 RefExpr->getExprLoc());
10974 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010975 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010976 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010977 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010978 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010979 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010980 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010981 ExprCaptures.push_back(Ref->getDecl());
10982 }
Alexey Bataev417089f2016-02-17 13:19:37 +000010983 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010984 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010985 Vars.push_back((VD || CurContext->isDependentContext())
10986 ? RefExpr->IgnoreParens()
10987 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010988 PrivateCopies.push_back(VDPrivateRefExpr);
10989 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010990 }
10991
Alexey Bataeved09d242014-05-28 05:53:51 +000010992 if (Vars.empty())
10993 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010994
10995 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010996 Vars, PrivateCopies, Inits,
10997 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010998}
10999
Alexander Musman1bb328c2014-06-04 13:06:39 +000011000OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
11001 SourceLocation StartLoc,
11002 SourceLocation LParenLoc,
11003 SourceLocation EndLoc) {
11004 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000011005 SmallVector<Expr *, 8> SrcExprs;
11006 SmallVector<Expr *, 8> DstExprs;
11007 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000011008 SmallVector<Decl *, 4> ExprCaptures;
11009 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000011010 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000011011 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000011012 SourceLocation ELoc;
11013 SourceRange ERange;
11014 Expr *SimpleRefExpr = RefExpr;
11015 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000011016 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000011017 // It will be analyzed later.
11018 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000011019 SrcExprs.push_back(nullptr);
11020 DstExprs.push_back(nullptr);
11021 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000011022 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000011023 ValueDecl *D = Res.first;
11024 if (!D)
11025 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000011026
Alexey Bataev74caaf22016-02-20 04:09:36 +000011027 QualType Type = D->getType();
11028 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000011029
11030 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
11031 // A variable that appears in a lastprivate clause must not have an
11032 // incomplete type or a reference type.
11033 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000011034 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000011035 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011036 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000011037
Joel E. Dennye6234d1422019-01-04 22:11:31 +000011038 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11039 // A variable that is privatized must not have a const-qualified type
11040 // unless it is of class type with a mutable member. This restriction does
11041 // not apply to the firstprivate clause.
11042 //
11043 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
11044 // A variable that appears in a lastprivate clause must not have a
11045 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011046 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000011047 continue;
11048
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011049 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000011050 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11051 // in a Construct]
11052 // Variables with the predetermined data-sharing attributes may not be
11053 // listed in data-sharing attributes clauses, except for the cases
11054 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011055 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
11056 // A list item may appear in a firstprivate or lastprivate clause but not
11057 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000011058 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000011059 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000011060 (isOpenMPDistributeDirective(CurrDir) ||
11061 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000011062 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
11063 Diag(ELoc, diag::err_omp_wrong_dsa)
11064 << getOpenMPClauseName(DVar.CKind)
11065 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000011066 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000011067 continue;
11068 }
11069
Alexey Bataevf29276e2014-06-18 04:14:57 +000011070 // OpenMP [2.14.3.5, Restrictions, p.2]
11071 // A list item that is private within a parallel region, or that appears in
11072 // the reduction clause of a parallel construct, must not appear in a
11073 // lastprivate clause on a worksharing construct if any of the corresponding
11074 // worksharing regions ever binds to any of the corresponding parallel
11075 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000011076 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000011077 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000011078 !isOpenMPParallelDirective(CurrDir) &&
11079 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000011080 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000011081 if (DVar.CKind != OMPC_shared) {
11082 Diag(ELoc, diag::err_omp_required_access)
11083 << getOpenMPClauseName(OMPC_lastprivate)
11084 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000011085 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000011086 continue;
11087 }
11088 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000011089
Alexander Musman1bb328c2014-06-04 13:06:39 +000011090 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000011091 // A variable of class type (or array thereof) that appears in a
11092 // lastprivate clause requires an accessible, unambiguous default
11093 // constructor for the class type, unless the list item is also specified
11094 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000011095 // A variable of class type (or array thereof) that appears in a
11096 // lastprivate clause requires an accessible, unambiguous copy assignment
11097 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000011098 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011099 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
11100 Type.getUnqualifiedType(), ".lastprivate.src",
11101 D->hasAttrs() ? &D->getAttrs() : nullptr);
11102 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000011103 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000011104 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000011105 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000011106 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000011107 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000011108 // For arrays generate assignment operation for single element and replace
11109 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000011110 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
11111 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000011112 if (AssignmentOp.isInvalid())
11113 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011114 AssignmentOp =
11115 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000011116 if (AssignmentOp.isInvalid())
11117 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000011118
Alexey Bataev74caaf22016-02-20 04:09:36 +000011119 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011120 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011121 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000011122 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000011123 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000011124 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011125 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000011126 ExprCaptures.push_back(Ref->getDecl());
11127 }
11128 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000011129 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011130 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000011131 ExprResult RefRes = DefaultLvalueConversion(Ref);
11132 if (!RefRes.isUsable())
11133 continue;
11134 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000011135 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11136 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000011137 if (!PostUpdateRes.isUsable())
11138 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000011139 ExprPostUpdates.push_back(
11140 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000011141 }
11142 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011143 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011144 Vars.push_back((VD || CurContext->isDependentContext())
11145 ? RefExpr->IgnoreParens()
11146 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000011147 SrcExprs.push_back(PseudoSrcExpr);
11148 DstExprs.push_back(PseudoDstExpr);
11149 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000011150 }
11151
11152 if (Vars.empty())
11153 return nullptr;
11154
11155 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000011156 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000011157 buildPreInits(Context, ExprCaptures),
11158 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000011159}
11160
Alexey Bataev758e55e2013-09-06 18:03:48 +000011161OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
11162 SourceLocation StartLoc,
11163 SourceLocation LParenLoc,
11164 SourceLocation EndLoc) {
11165 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000011166 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011167 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000011168 SourceLocation ELoc;
11169 SourceRange ERange;
11170 Expr *SimpleRefExpr = RefExpr;
11171 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011172 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000011173 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011174 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011175 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011176 ValueDecl *D = Res.first;
11177 if (!D)
11178 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000011179
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011180 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011181 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
11182 // in a Construct]
11183 // Variables with the predetermined data-sharing attributes may not be
11184 // listed in data-sharing attributes clauses, except for the cases
11185 // listed below. For these exceptions only, listing a predetermined
11186 // variable in a data-sharing attribute clause is allowed and overrides
11187 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000011188 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000011189 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
11190 DVar.RefExpr) {
11191 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11192 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000011193 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011194 continue;
11195 }
11196
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011197 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011198 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000011199 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000011200 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011201 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
11202 ? RefExpr->IgnoreParens()
11203 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000011204 }
11205
Alexey Bataeved09d242014-05-28 05:53:51 +000011206 if (Vars.empty())
11207 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000011208
11209 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
11210}
11211
Alexey Bataevc5e02582014-06-16 07:08:35 +000011212namespace {
11213class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
11214 DSAStackTy *Stack;
11215
11216public:
11217 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011218 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
11219 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011220 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
11221 return false;
11222 if (DVar.CKind != OMPC_unknown)
11223 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000011224 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000011225 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000011226 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000011227 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011228 }
11229 return false;
11230 }
11231 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011232 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011233 if (Child && Visit(Child))
11234 return true;
11235 }
11236 return false;
11237 }
Alexey Bataev23b69422014-06-18 07:08:49 +000011238 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000011239};
Alexey Bataev23b69422014-06-18 07:08:49 +000011240} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000011241
Alexey Bataev60da77e2016-02-29 05:54:20 +000011242namespace {
11243// Transform MemberExpression for specified FieldDecl of current class to
11244// DeclRefExpr to specified OMPCapturedExprDecl.
11245class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
11246 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000011247 ValueDecl *Field = nullptr;
11248 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011249
11250public:
11251 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
11252 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
11253
11254 ExprResult TransformMemberExpr(MemberExpr *E) {
11255 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
11256 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000011257 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000011258 return CapturedExpr;
11259 }
11260 return BaseTransform::TransformMemberExpr(E);
11261 }
11262 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
11263};
11264} // namespace
11265
Alexey Bataev97d18bf2018-04-11 19:21:00 +000011266template <typename T, typename U>
Michael Kruse4304e9d2019-02-19 16:38:20 +000011267static T filterLookupForUDReductionAndMapper(
11268 SmallVectorImpl<U> &Lookups, const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011269 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011270 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011271 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011272 return Res;
11273 }
11274 }
11275 return T();
11276}
11277
Alexey Bataev43b90b72018-09-12 16:31:59 +000011278static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
11279 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
11280
11281 for (auto RD : D->redecls()) {
11282 // Don't bother with extra checks if we already know this one isn't visible.
11283 if (RD == D)
11284 continue;
11285
11286 auto ND = cast<NamedDecl>(RD);
11287 if (LookupResult::isVisible(SemaRef, ND))
11288 return ND;
11289 }
11290
11291 return nullptr;
11292}
11293
11294static void
Michael Kruse4304e9d2019-02-19 16:38:20 +000011295argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &Id,
Alexey Bataev43b90b72018-09-12 16:31:59 +000011296 SourceLocation Loc, QualType Ty,
11297 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
11298 // Find all of the associated namespaces and classes based on the
11299 // arguments we have.
11300 Sema::AssociatedNamespaceSet AssociatedNamespaces;
11301 Sema::AssociatedClassSet AssociatedClasses;
11302 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
11303 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
11304 AssociatedClasses);
11305
11306 // C++ [basic.lookup.argdep]p3:
11307 // Let X be the lookup set produced by unqualified lookup (3.4.1)
11308 // and let Y be the lookup set produced by argument dependent
11309 // lookup (defined as follows). If X contains [...] then Y is
11310 // empty. Otherwise Y is the set of declarations found in the
11311 // namespaces associated with the argument types as described
11312 // below. The set of declarations found by the lookup of the name
11313 // is the union of X and Y.
11314 //
11315 // Here, we compute Y and add its members to the overloaded
11316 // candidate set.
11317 for (auto *NS : AssociatedNamespaces) {
11318 // When considering an associated namespace, the lookup is the
11319 // same as the lookup performed when the associated namespace is
11320 // used as a qualifier (3.4.3.2) except that:
11321 //
11322 // -- Any using-directives in the associated namespace are
11323 // ignored.
11324 //
11325 // -- Any namespace-scope friend functions declared in
11326 // associated classes are visible within their respective
11327 // namespaces even if they are not visible during an ordinary
11328 // lookup (11.4).
Michael Kruse4304e9d2019-02-19 16:38:20 +000011329 DeclContext::lookup_result R = NS->lookup(Id.getName());
Alexey Bataev43b90b72018-09-12 16:31:59 +000011330 for (auto *D : R) {
11331 auto *Underlying = D;
11332 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11333 Underlying = USD->getTargetDecl();
11334
Michael Kruse4304e9d2019-02-19 16:38:20 +000011335 if (!isa<OMPDeclareReductionDecl>(Underlying) &&
11336 !isa<OMPDeclareMapperDecl>(Underlying))
Alexey Bataev43b90b72018-09-12 16:31:59 +000011337 continue;
11338
11339 if (!SemaRef.isVisible(D)) {
11340 D = findAcceptableDecl(SemaRef, D);
11341 if (!D)
11342 continue;
11343 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
11344 Underlying = USD->getTargetDecl();
11345 }
11346 Lookups.emplace_back();
11347 Lookups.back().addDecl(Underlying);
11348 }
11349 }
11350}
11351
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011352static ExprResult
11353buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
11354 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
11355 const DeclarationNameInfo &ReductionId, QualType Ty,
11356 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
11357 if (ReductionIdScopeSpec.isInvalid())
11358 return ExprError();
11359 SmallVector<UnresolvedSet<8>, 4> Lookups;
11360 if (S) {
11361 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11362 Lookup.suppressDiagnostics();
11363 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011364 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011365 do {
11366 S = S->getParent();
11367 } while (S && !S->isDeclScope(D));
11368 if (S)
11369 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000011370 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011371 Lookups.back().append(Lookup.begin(), Lookup.end());
11372 Lookup.clear();
11373 }
11374 } else if (auto *ULE =
11375 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
11376 Lookups.push_back(UnresolvedSet<8>());
11377 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011378 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011379 if (D == PrevD)
11380 Lookups.push_back(UnresolvedSet<8>());
Don Hintonf170dff2019-03-19 06:14:14 +000011381 else if (auto *DRD = dyn_cast<OMPDeclareReductionDecl>(D))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011382 Lookups.back().addDecl(DRD);
11383 PrevD = D;
11384 }
11385 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000011386 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
11387 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011388 Ty->containsUnexpandedParameterPack() ||
Michael Kruse4304e9d2019-02-19 16:38:20 +000011389 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011390 return !D->isInvalidDecl() &&
11391 (D->getType()->isDependentType() ||
11392 D->getType()->isInstantiationDependentType() ||
11393 D->getType()->containsUnexpandedParameterPack());
11394 })) {
11395 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000011396 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000011397 if (Set.empty())
11398 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011399 ResSet.append(Set.begin(), Set.end());
11400 // The last item marks the end of all declarations at the specified scope.
11401 ResSet.addDecl(Set[Set.size() - 1]);
11402 }
11403 return UnresolvedLookupExpr::Create(
11404 SemaRef.Context, /*NamingClass=*/nullptr,
11405 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
11406 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
11407 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000011408 // Lookup inside the classes.
11409 // C++ [over.match.oper]p3:
11410 // For a unary operator @ with an operand of a type whose
11411 // cv-unqualified version is T1, and for a binary operator @ with
11412 // a left operand of a type whose cv-unqualified version is T1 and
11413 // a right operand of a type whose cv-unqualified version is T2,
11414 // three sets of candidate functions, designated member
11415 // candidates, non-member candidates and built-in candidates, are
11416 // constructed as follows:
11417 // -- If T1 is a complete class type or a class currently being
11418 // defined, the set of member candidates is the result of the
11419 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
11420 // the set of member candidates is empty.
11421 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
11422 Lookup.suppressDiagnostics();
11423 if (const auto *TyRec = Ty->getAs<RecordType>()) {
11424 // Complete the type if it can be completed.
11425 // If the type is neither complete nor being defined, bail out now.
11426 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
11427 TyRec->getDecl()->getDefinition()) {
11428 Lookup.clear();
11429 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
11430 if (Lookup.empty()) {
11431 Lookups.emplace_back();
11432 Lookups.back().append(Lookup.begin(), Lookup.end());
11433 }
11434 }
11435 }
11436 // Perform ADL.
Alexey Bataev09232662019-04-04 17:28:22 +000011437 if (SemaRef.getLangOpts().CPlusPlus)
Alexey Bataev74a04e82019-03-13 19:31:34 +000011438 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataev09232662019-04-04 17:28:22 +000011439 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11440 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
11441 if (!D->isInvalidDecl() &&
11442 SemaRef.Context.hasSameType(D->getType(), Ty))
11443 return D;
11444 return nullptr;
11445 }))
11446 return SemaRef.BuildDeclRefExpr(VD, VD->getType().getNonReferenceType(),
11447 VK_LValue, Loc);
11448 if (SemaRef.getLangOpts().CPlusPlus) {
Alexey Bataev74a04e82019-03-13 19:31:34 +000011449 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
11450 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
11451 if (!D->isInvalidDecl() &&
11452 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
11453 !Ty.isMoreQualifiedThan(D->getType()))
11454 return D;
11455 return nullptr;
11456 })) {
11457 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
11458 /*DetectVirtual=*/false);
11459 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
11460 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
11461 VD->getType().getUnqualifiedType()))) {
11462 if (SemaRef.CheckBaseClassAccess(
11463 Loc, VD->getType(), Ty, Paths.front(),
11464 /*DiagID=*/0) != Sema::AR_inaccessible) {
11465 SemaRef.BuildBasePathArray(Paths, BasePath);
11466 return SemaRef.BuildDeclRefExpr(
11467 VD, VD->getType().getNonReferenceType(), VK_LValue, Loc);
11468 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011469 }
11470 }
11471 }
11472 }
11473 if (ReductionIdScopeSpec.isSet()) {
11474 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
11475 return ExprError();
11476 }
11477 return ExprEmpty();
11478}
11479
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011480namespace {
11481/// Data for the reduction-based clauses.
11482struct ReductionData {
11483 /// List of original reduction items.
11484 SmallVector<Expr *, 8> Vars;
11485 /// List of private copies of the reduction items.
11486 SmallVector<Expr *, 8> Privates;
11487 /// LHS expressions for the reduction_op expressions.
11488 SmallVector<Expr *, 8> LHSs;
11489 /// RHS expressions for the reduction_op expressions.
11490 SmallVector<Expr *, 8> RHSs;
11491 /// Reduction operation expression.
11492 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000011493 /// Taskgroup descriptors for the corresponding reduction items in
11494 /// in_reduction clauses.
11495 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011496 /// List of captures for clause.
11497 SmallVector<Decl *, 4> ExprCaptures;
11498 /// List of postupdate expressions.
11499 SmallVector<Expr *, 4> ExprPostUpdates;
11500 ReductionData() = delete;
11501 /// Reserves required memory for the reduction data.
11502 ReductionData(unsigned Size) {
11503 Vars.reserve(Size);
11504 Privates.reserve(Size);
11505 LHSs.reserve(Size);
11506 RHSs.reserve(Size);
11507 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000011508 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011509 ExprCaptures.reserve(Size);
11510 ExprPostUpdates.reserve(Size);
11511 }
11512 /// Stores reduction item and reduction operation only (required for dependent
11513 /// reduction item).
11514 void push(Expr *Item, Expr *ReductionOp) {
11515 Vars.emplace_back(Item);
11516 Privates.emplace_back(nullptr);
11517 LHSs.emplace_back(nullptr);
11518 RHSs.emplace_back(nullptr);
11519 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011520 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011521 }
11522 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000011523 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
11524 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011525 Vars.emplace_back(Item);
11526 Privates.emplace_back(Private);
11527 LHSs.emplace_back(LHS);
11528 RHSs.emplace_back(RHS);
11529 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000011530 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011531 }
11532};
11533} // namespace
11534
Alexey Bataeve3727102018-04-18 15:57:46 +000011535static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011536 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
11537 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
11538 const Expr *Length = OASE->getLength();
11539 if (Length == nullptr) {
11540 // For array sections of the form [1:] or [:], we would need to analyze
11541 // the lower bound...
11542 if (OASE->getColonLoc().isValid())
11543 return false;
11544
11545 // This is an array subscript which has implicit length 1!
11546 SingleElement = true;
11547 ArraySizes.push_back(llvm::APSInt::get(1));
11548 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011549 Expr::EvalResult Result;
11550 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011551 return false;
11552
Fangrui Song407659a2018-11-30 23:41:18 +000011553 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011554 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
11555 ArraySizes.push_back(ConstantLengthValue);
11556 }
11557
11558 // Get the base of this array section and walk up from there.
11559 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
11560
11561 // We require length = 1 for all array sections except the right-most to
11562 // guarantee that the memory region is contiguous and has no holes in it.
11563 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
11564 Length = TempOASE->getLength();
11565 if (Length == nullptr) {
11566 // For array sections of the form [1:] or [:], we would need to analyze
11567 // the lower bound...
11568 if (OASE->getColonLoc().isValid())
11569 return false;
11570
11571 // This is an array subscript which has implicit length 1!
11572 ArraySizes.push_back(llvm::APSInt::get(1));
11573 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000011574 Expr::EvalResult Result;
11575 if (!Length->EvaluateAsInt(Result, Context))
11576 return false;
11577
11578 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
11579 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011580 return false;
11581
11582 ArraySizes.push_back(ConstantLengthValue);
11583 }
11584 Base = TempOASE->getBase()->IgnoreParenImpCasts();
11585 }
11586
11587 // If we have a single element, we don't need to add the implicit lengths.
11588 if (!SingleElement) {
11589 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
11590 // Has implicit length 1!
11591 ArraySizes.push_back(llvm::APSInt::get(1));
11592 Base = TempASE->getBase()->IgnoreParenImpCasts();
11593 }
11594 }
11595
11596 // This array section can be privatized as a single value or as a constant
11597 // sized array.
11598 return true;
11599}
11600
Alexey Bataeve3727102018-04-18 15:57:46 +000011601static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000011602 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
11603 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11604 SourceLocation ColonLoc, SourceLocation EndLoc,
11605 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011606 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011607 DeclarationName DN = ReductionId.getName();
11608 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011609 BinaryOperatorKind BOK = BO_Comma;
11610
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011611 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011612 // OpenMP [2.14.3.6, reduction clause]
11613 // C
11614 // reduction-identifier is either an identifier or one of the following
11615 // operators: +, -, *, &, |, ^, && and ||
11616 // C++
11617 // reduction-identifier is either an id-expression or one of the following
11618 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000011619 switch (OOK) {
11620 case OO_Plus:
11621 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011622 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011623 break;
11624 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011625 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011626 break;
11627 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011628 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011629 break;
11630 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011631 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011632 break;
11633 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011634 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011635 break;
11636 case OO_AmpAmp:
11637 BOK = BO_LAnd;
11638 break;
11639 case OO_PipePipe:
11640 BOK = BO_LOr;
11641 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011642 case OO_New:
11643 case OO_Delete:
11644 case OO_Array_New:
11645 case OO_Array_Delete:
11646 case OO_Slash:
11647 case OO_Percent:
11648 case OO_Tilde:
11649 case OO_Exclaim:
11650 case OO_Equal:
11651 case OO_Less:
11652 case OO_Greater:
11653 case OO_LessEqual:
11654 case OO_GreaterEqual:
11655 case OO_PlusEqual:
11656 case OO_MinusEqual:
11657 case OO_StarEqual:
11658 case OO_SlashEqual:
11659 case OO_PercentEqual:
11660 case OO_CaretEqual:
11661 case OO_AmpEqual:
11662 case OO_PipeEqual:
11663 case OO_LessLess:
11664 case OO_GreaterGreater:
11665 case OO_LessLessEqual:
11666 case OO_GreaterGreaterEqual:
11667 case OO_EqualEqual:
11668 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000011669 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011670 case OO_PlusPlus:
11671 case OO_MinusMinus:
11672 case OO_Comma:
11673 case OO_ArrowStar:
11674 case OO_Arrow:
11675 case OO_Call:
11676 case OO_Subscript:
11677 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000011678 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011679 case NUM_OVERLOADED_OPERATORS:
11680 llvm_unreachable("Unexpected reduction identifier");
11681 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000011682 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011683 if (II->isStr("max"))
11684 BOK = BO_GT;
11685 else if (II->isStr("min"))
11686 BOK = BO_LT;
11687 }
11688 break;
11689 }
11690 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011691 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000011692 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011693 else
11694 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011695 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000011696
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011697 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
11698 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000011699 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000011700 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000011701 // OpenMP [2.1, C/C++]
11702 // A list item is a variable or array section, subject to the restrictions
11703 // specified in Section 2.4 on page 42 and in each of the sections
11704 // describing clauses and directives for which a list appears.
11705 // OpenMP [2.14.3.3, Restrictions, p.1]
11706 // A variable that is part of another variable (as an array or
11707 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011708 if (!FirstIter && IR != ER)
11709 ++IR;
11710 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011711 SourceLocation ELoc;
11712 SourceRange ERange;
11713 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011714 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000011715 /*AllowArraySection=*/true);
11716 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011717 // Try to find 'declare reduction' corresponding construct before using
11718 // builtin/overloaded operators.
11719 QualType Type = Context.DependentTy;
11720 CXXCastPath BasePath;
11721 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011722 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011723 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011724 Expr *ReductionOp = nullptr;
11725 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011726 (DeclareReductionRef.isUnset() ||
11727 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011728 ReductionOp = DeclareReductionRef.get();
11729 // It will be analyzed later.
11730 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011731 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011732 ValueDecl *D = Res.first;
11733 if (!D)
11734 continue;
11735
Alexey Bataev88202be2017-07-27 13:20:36 +000011736 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000011737 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000011738 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
11739 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000011740 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000011741 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011742 } else if (OASE) {
11743 QualType BaseType =
11744 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
11745 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000011746 Type = ATy->getElementType();
11747 else
11748 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000011749 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011750 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011751 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000011752 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011753 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000011754
Alexey Bataevc5e02582014-06-16 07:08:35 +000011755 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
11756 // A variable that appears in a private clause must not have an incomplete
11757 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000011758 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011759 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011760 continue;
11761 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000011762 // A list item that appears in a reduction clause must not be
11763 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011764 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11765 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011766 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000011767
11768 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011769 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11770 // If a list-item is a reference type then it must bind to the same object
11771 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000011772 if (!ASE && !OASE) {
11773 if (VD) {
11774 VarDecl *VDDef = VD->getDefinition();
11775 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11776 DSARefChecker Check(Stack);
11777 if (Check.Visit(VDDef->getInit())) {
11778 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11779 << getOpenMPClauseName(ClauseKind) << ERange;
11780 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11781 continue;
11782 }
Alexey Bataeva1764212015-09-30 09:22:36 +000011783 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000011784 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011785
Alexey Bataevbc529672018-09-28 19:33:14 +000011786 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11787 // in a Construct]
11788 // Variables with the predetermined data-sharing attributes may not be
11789 // listed in data-sharing attributes clauses, except for the cases
11790 // listed below. For these exceptions only, listing a predetermined
11791 // variable in a data-sharing attribute clause is allowed and overrides
11792 // the variable's predetermined data-sharing attributes.
11793 // OpenMP [2.14.3.6, Restrictions, p.3]
11794 // Any number of reduction clauses can be specified on the directive,
11795 // but a list item can appear only once in the reduction clauses for that
11796 // directive.
11797 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11798 if (DVar.CKind == OMPC_reduction) {
11799 S.Diag(ELoc, diag::err_omp_once_referenced)
11800 << getOpenMPClauseName(ClauseKind);
11801 if (DVar.RefExpr)
11802 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
11803 continue;
11804 }
11805 if (DVar.CKind != OMPC_unknown) {
11806 S.Diag(ELoc, diag::err_omp_wrong_dsa)
11807 << getOpenMPClauseName(DVar.CKind)
11808 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000011809 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011810 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000011811 }
Alexey Bataevbc529672018-09-28 19:33:14 +000011812
11813 // OpenMP [2.14.3.6, Restrictions, p.1]
11814 // A list item that appears in a reduction clause of a worksharing
11815 // construct must be shared in the parallel regions to which any of the
11816 // worksharing regions arising from the worksharing construct bind.
11817 if (isOpenMPWorksharingDirective(CurrDir) &&
11818 !isOpenMPParallelDirective(CurrDir) &&
11819 !isOpenMPTeamsDirective(CurrDir)) {
11820 DVar = Stack->getImplicitDSA(D, true);
11821 if (DVar.CKind != OMPC_shared) {
11822 S.Diag(ELoc, diag::err_omp_required_access)
11823 << getOpenMPClauseName(OMPC_reduction)
11824 << getOpenMPClauseName(OMPC_shared);
11825 reportOriginalDsa(S, Stack, D, DVar);
11826 continue;
11827 }
11828 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000011829 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011830
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011831 // Try to find 'declare reduction' corresponding construct before using
11832 // builtin/overloaded operators.
11833 CXXCastPath BasePath;
11834 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011835 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011836 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11837 if (DeclareReductionRef.isInvalid())
11838 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011839 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011840 (DeclareReductionRef.isUnset() ||
11841 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011842 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011843 continue;
11844 }
11845 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
11846 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011847 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011848 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011849 << Type << ReductionIdRange;
11850 continue;
11851 }
11852
11853 // OpenMP [2.14.3.6, reduction clause, Restrictions]
11854 // The type of a list item that appears in a reduction clause must be valid
11855 // for the reduction-identifier. For a max or min reduction in C, the type
11856 // of the list item must be an allowed arithmetic data type: char, int,
11857 // float, double, or _Bool, possibly modified with long, short, signed, or
11858 // unsigned. For a max or min reduction in C++, the type of the list item
11859 // must be an allowed arithmetic data type: char, wchar_t, int, float,
11860 // double, or bool, possibly modified with long, short, signed, or unsigned.
11861 if (DeclareReductionRef.isUnset()) {
11862 if ((BOK == BO_GT || BOK == BO_LT) &&
11863 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011864 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
11865 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000011866 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011867 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011868 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11869 VarDecl::DeclarationOnly;
11870 S.Diag(D->getLocation(),
11871 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011872 << D;
11873 }
11874 continue;
11875 }
11876 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011877 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000011878 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11879 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011880 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011881 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11882 VarDecl::DeclarationOnly;
11883 S.Diag(D->getLocation(),
11884 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011885 << D;
11886 }
11887 continue;
11888 }
11889 }
11890
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011891 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011892 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
11893 D->hasAttrs() ? &D->getAttrs() : nullptr);
11894 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
11895 D->hasAttrs() ? &D->getAttrs() : nullptr);
11896 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011897
11898 // Try if we can determine constant lengths for all array sections and avoid
11899 // the VLA.
11900 bool ConstantLengthOASE = false;
11901 if (OASE) {
11902 bool SingleElement;
11903 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000011904 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011905 Context, OASE, SingleElement, ArraySizes);
11906
11907 // If we don't have a single element, we must emit a constant array type.
11908 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011909 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011910 PrivateTy = Context.getConstantArrayType(
11911 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011912 }
11913 }
11914
11915 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000011916 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000011917 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000011918 if (!Context.getTargetInfo().isVLASupported() &&
11919 S.shouldDiagnoseTargetSupportFromOpenMP()) {
11920 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
11921 S.Diag(ELoc, diag::note_vla_unsupported);
11922 continue;
11923 }
David Majnemer9d168222016-08-05 17:44:54 +000011924 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011925 // Create pseudo array type for private copy. The size for this array will
11926 // be generated during codegen.
11927 // For array subscripts or single variables Private Ty is the same as Type
11928 // (type of the variable or single array element).
11929 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011930 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000011931 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011932 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000011933 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000011934 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011935 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011936 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011937 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000011938 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011939 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
11940 D->hasAttrs() ? &D->getAttrs() : nullptr,
11941 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011942 // Add initializer for private variable.
11943 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011944 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
11945 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011946 if (DeclareReductionRef.isUsable()) {
11947 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
11948 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
11949 if (DRD->getInitializer()) {
11950 Init = DRDRef;
11951 RHSVD->setInit(DRDRef);
11952 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011953 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011954 } else {
11955 switch (BOK) {
11956 case BO_Add:
11957 case BO_Xor:
11958 case BO_Or:
11959 case BO_LOr:
11960 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
11961 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011962 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011963 break;
11964 case BO_Mul:
11965 case BO_LAnd:
11966 if (Type->isScalarType() || Type->isAnyComplexType()) {
11967 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011968 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011969 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011970 break;
11971 case BO_And: {
11972 // '&' reduction op - initializer is '~0'.
11973 QualType OrigType = Type;
11974 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
11975 Type = ComplexTy->getElementType();
11976 if (Type->isRealFloatingType()) {
11977 llvm::APFloat InitValue =
11978 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
11979 /*isIEEE=*/true);
11980 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11981 Type, ELoc);
11982 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011983 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011984 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11985 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11986 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11987 }
11988 if (Init && OrigType->isAnyComplexType()) {
11989 // Init = 0xFFFF + 0xFFFFi;
11990 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011991 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011992 }
11993 Type = OrigType;
11994 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011995 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011996 case BO_LT:
11997 case BO_GT: {
11998 // 'min' reduction op - initializer is 'Largest representable number in
11999 // the reduction list item type'.
12000 // 'max' reduction op - initializer is 'Least representable number in
12001 // the reduction list item type'.
12002 if (Type->isIntegerType() || Type->isPointerType()) {
12003 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000012004 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012005 QualType IntTy =
12006 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
12007 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012008 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
12009 : llvm::APInt::getMinValue(Size)
12010 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
12011 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012012 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
12013 if (Type->isPointerType()) {
12014 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012015 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000012016 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012017 if (CastExpr.isInvalid())
12018 continue;
12019 Init = CastExpr.get();
12020 }
12021 } else if (Type->isRealFloatingType()) {
12022 llvm::APFloat InitValue = llvm::APFloat::getLargest(
12023 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
12024 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
12025 Type, ELoc);
12026 }
12027 break;
12028 }
12029 case BO_PtrMemD:
12030 case BO_PtrMemI:
12031 case BO_MulAssign:
12032 case BO_Div:
12033 case BO_Rem:
12034 case BO_Sub:
12035 case BO_Shl:
12036 case BO_Shr:
12037 case BO_LE:
12038 case BO_GE:
12039 case BO_EQ:
12040 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000012041 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012042 case BO_AndAssign:
12043 case BO_XorAssign:
12044 case BO_OrAssign:
12045 case BO_Assign:
12046 case BO_AddAssign:
12047 case BO_SubAssign:
12048 case BO_DivAssign:
12049 case BO_RemAssign:
12050 case BO_ShlAssign:
12051 case BO_ShrAssign:
12052 case BO_Comma:
12053 llvm_unreachable("Unexpected reduction operation");
12054 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012055 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012056 if (Init && DeclareReductionRef.isUnset())
12057 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
12058 else if (!Init)
12059 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012060 if (RHSVD->isInvalidDecl())
12061 continue;
Alexey Bataev09232662019-04-04 17:28:22 +000012062 if (!RHSVD->hasInit() &&
12063 (DeclareReductionRef.isUnset() || !S.LangOpts.CPlusPlus)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012064 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
12065 << Type << ReductionIdRange;
12066 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
12067 VarDecl::DeclarationOnly;
12068 S.Diag(D->getLocation(),
12069 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000012070 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012071 continue;
12072 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000012073 // Store initializer for single element in private copy. Will be used during
12074 // codegen.
12075 PrivateVD->setInit(RHSVD->getInit());
12076 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000012077 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012078 ExprResult ReductionOp;
12079 if (DeclareReductionRef.isUsable()) {
12080 QualType RedTy = DeclareReductionRef.get()->getType();
12081 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012082 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
12083 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012084 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012085 LHS = S.DefaultLvalueConversion(LHS.get());
12086 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012087 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
12088 CK_UncheckedDerivedToBase, LHS.get(),
12089 &BasePath, LHS.get()->getValueKind());
12090 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
12091 CK_UncheckedDerivedToBase, RHS.get(),
12092 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000012093 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012094 FunctionProtoType::ExtProtoInfo EPI;
12095 QualType Params[] = {PtrRedTy, PtrRedTy};
12096 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
12097 auto *OVE = new (Context) OpaqueValueExpr(
12098 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012099 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012100 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000012101 ReductionOp =
12102 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012103 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012104 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012105 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012106 if (ReductionOp.isUsable()) {
12107 if (BOK != BO_LT && BOK != BO_GT) {
12108 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012109 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012110 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012111 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000012112 auto *ConditionalOp = new (Context)
12113 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
12114 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012115 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012116 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012117 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012118 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000012119 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012120 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
12121 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012122 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000012123 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012124 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000012125 }
12126
Alexey Bataevfa312f32017-07-21 18:48:21 +000012127 // OpenMP [2.15.4.6, Restrictions, p.2]
12128 // A list item that appears in an in_reduction clause of a task construct
12129 // must appear in a task_reduction clause of a construct associated with a
12130 // taskgroup region that includes the participating task in its taskgroup
12131 // set. The construct associated with the innermost region that meets this
12132 // condition must specify the same reduction-identifier as the in_reduction
12133 // clause.
12134 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000012135 SourceRange ParentSR;
12136 BinaryOperatorKind ParentBOK;
12137 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000012138 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000012139 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000012140 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
12141 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000012142 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000012143 Stack->getTopMostTaskgroupReductionData(
12144 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000012145 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
12146 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
12147 if (!IsParentBOK && !IsParentReductionOp) {
12148 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
12149 continue;
12150 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000012151 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
12152 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
12153 IsParentReductionOp) {
12154 bool EmitError = true;
12155 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
12156 llvm::FoldingSetNodeID RedId, ParentRedId;
12157 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
12158 DeclareReductionRef.get()->Profile(RedId, Context,
12159 /*Canonical=*/true);
12160 EmitError = RedId != ParentRedId;
12161 }
12162 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012163 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000012164 diag::err_omp_reduction_identifier_mismatch)
12165 << ReductionIdRange << RefExpr->getSourceRange();
12166 S.Diag(ParentSR.getBegin(),
12167 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000012168 << ParentSR
12169 << (IsParentBOK ? ParentBOKDSA.RefExpr
12170 : ParentReductionOpDSA.RefExpr)
12171 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000012172 continue;
12173 }
12174 }
Alexey Bataev88202be2017-07-27 13:20:36 +000012175 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
12176 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000012177 }
12178
Alexey Bataev60da77e2016-02-29 05:54:20 +000012179 DeclRefExpr *Ref = nullptr;
12180 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012181 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000012182 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012183 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000012184 VarsExpr =
12185 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
12186 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000012187 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012188 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000012189 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012190 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012191 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000012192 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012193 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000012194 if (!RefRes.isUsable())
12195 continue;
12196 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012197 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
12198 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000012199 if (!PostUpdateRes.isUsable())
12200 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012201 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
12202 Stack->getCurrentDirective() == OMPD_taskgroup) {
12203 S.Diag(RefExpr->getExprLoc(),
12204 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000012205 << RefExpr->getSourceRange();
12206 continue;
12207 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012208 RD.ExprPostUpdates.emplace_back(
12209 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000012210 }
12211 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000012212 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000012213 // All reduction items are still marked as reduction (to do not increase
12214 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012215 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000012216 if (CurrDir == OMPD_taskgroup) {
12217 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000012218 Stack->addTaskgroupReductionData(D, ReductionIdRange,
12219 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000012220 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000012221 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000012222 }
Alexey Bataev88202be2017-07-27 13:20:36 +000012223 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
12224 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000012225 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012226 return RD.Vars.empty();
12227}
Alexey Bataevc5e02582014-06-16 07:08:35 +000012228
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012229OMPClause *Sema::ActOnOpenMPReductionClause(
12230 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12231 SourceLocation ColonLoc, SourceLocation EndLoc,
12232 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12233 ArrayRef<Expr *> UnresolvedReductions) {
12234 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000012235 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000012236 StartLoc, LParenLoc, ColonLoc, EndLoc,
12237 ReductionIdScopeSpec, ReductionId,
12238 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000012239 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000012240
Alexey Bataevc5e02582014-06-16 07:08:35 +000012241 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000012242 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12243 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
12244 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
12245 buildPreInits(Context, RD.ExprCaptures),
12246 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000012247}
12248
Alexey Bataev169d96a2017-07-18 20:17:46 +000012249OMPClause *Sema::ActOnOpenMPTaskReductionClause(
12250 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12251 SourceLocation ColonLoc, SourceLocation EndLoc,
12252 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12253 ArrayRef<Expr *> UnresolvedReductions) {
12254 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000012255 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
12256 StartLoc, LParenLoc, ColonLoc, EndLoc,
12257 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000012258 UnresolvedReductions, RD))
12259 return nullptr;
12260
12261 return OMPTaskReductionClause::Create(
12262 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12263 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
12264 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
12265 buildPreInits(Context, RD.ExprCaptures),
12266 buildPostUpdate(*this, RD.ExprPostUpdates));
12267}
12268
Alexey Bataevfa312f32017-07-21 18:48:21 +000012269OMPClause *Sema::ActOnOpenMPInReductionClause(
12270 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
12271 SourceLocation ColonLoc, SourceLocation EndLoc,
12272 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
12273 ArrayRef<Expr *> UnresolvedReductions) {
12274 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000012275 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000012276 StartLoc, LParenLoc, ColonLoc, EndLoc,
12277 ReductionIdScopeSpec, ReductionId,
12278 UnresolvedReductions, RD))
12279 return nullptr;
12280
12281 return OMPInReductionClause::Create(
12282 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
12283 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000012284 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000012285 buildPreInits(Context, RD.ExprCaptures),
12286 buildPostUpdate(*this, RD.ExprPostUpdates));
12287}
12288
Alexey Bataevecba70f2016-04-12 11:02:11 +000012289bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
12290 SourceLocation LinLoc) {
12291 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
12292 LinKind == OMPC_LINEAR_unknown) {
12293 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
12294 return true;
12295 }
12296 return false;
12297}
12298
Alexey Bataeve3727102018-04-18 15:57:46 +000012299bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000012300 OpenMPLinearClauseKind LinKind,
12301 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012302 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000012303 // A variable must not have an incomplete type or a reference type.
12304 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
12305 return true;
12306 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
12307 !Type->isReferenceType()) {
12308 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
12309 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
12310 return true;
12311 }
12312 Type = Type.getNonReferenceType();
12313
Joel E. Dennybae586f2019-01-04 22:12:13 +000012314 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
12315 // A variable that is privatized must not have a const-qualified type
12316 // unless it is of class type with a mutable member. This restriction does
12317 // not apply to the firstprivate clause.
12318 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000012319 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012320
12321 // A list item must be of integral or pointer type.
12322 Type = Type.getUnqualifiedType().getCanonicalType();
12323 const auto *Ty = Type.getTypePtrOrNull();
12324 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
12325 !Ty->isPointerType())) {
12326 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
12327 if (D) {
12328 bool IsDecl =
12329 !VD ||
12330 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
12331 Diag(D->getLocation(),
12332 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
12333 << D;
12334 }
12335 return true;
12336 }
12337 return false;
12338}
12339
Alexey Bataev182227b2015-08-20 10:54:39 +000012340OMPClause *Sema::ActOnOpenMPLinearClause(
12341 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
12342 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
12343 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012344 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012345 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000012346 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000012347 SmallVector<Decl *, 4> ExprCaptures;
12348 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012349 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000012350 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000012351 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012352 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012353 SourceLocation ELoc;
12354 SourceRange ERange;
12355 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012356 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012357 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000012358 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012359 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012360 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000012361 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000012362 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012363 ValueDecl *D = Res.first;
12364 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000012365 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000012366
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012367 QualType Type = D->getType();
12368 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000012369
12370 // OpenMP [2.14.3.7, linear clause]
12371 // A list-item cannot appear in more than one linear clause.
12372 // A list-item that appears in a linear clause cannot appear in any
12373 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012374 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000012375 if (DVar.RefExpr) {
12376 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
12377 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000012378 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000012379 continue;
12380 }
12381
Alexey Bataevecba70f2016-04-12 11:02:11 +000012382 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000012383 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000012384 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000012385
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012386 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000012387 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000012388 buildVarDecl(*this, ELoc, Type, D->getName(),
12389 D->hasAttrs() ? &D->getAttrs() : nullptr,
12390 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012391 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012392 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012393 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012394 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012395 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012396 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012397 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012398 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000012399 ExprCaptures.push_back(Ref->getDecl());
12400 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
12401 ExprResult RefRes = DefaultLvalueConversion(Ref);
12402 if (!RefRes.isUsable())
12403 continue;
12404 ExprResult PostUpdateRes =
12405 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
12406 SimpleRefExpr, RefRes.get());
12407 if (!PostUpdateRes.isUsable())
12408 continue;
12409 ExprPostUpdates.push_back(
12410 IgnoredValueConversions(PostUpdateRes.get()).get());
12411 }
12412 }
12413 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012414 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012415 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012416 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012417 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012418 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000012419 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012420 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000012421
12422 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000012423 Vars.push_back((VD || CurContext->isDependentContext())
12424 ? RefExpr->IgnoreParens()
12425 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012426 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000012427 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000012428 }
12429
12430 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012431 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012432
12433 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000012434 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000012435 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
12436 !Step->isInstantiationDependent() &&
12437 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012438 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000012439 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000012440 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000012441 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000012442 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000012443
Alexander Musman3276a272015-03-21 10:12:56 +000012444 // Build var to save the step value.
12445 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012446 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000012447 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000012448 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000012449 ExprResult CalcStep =
12450 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012451 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012452
Alexander Musman8dba6642014-04-22 13:09:42 +000012453 // Warn about zero linear step (it would be probably better specified as
12454 // making corresponding variables 'const').
12455 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000012456 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
12457 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000012458 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
12459 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000012460 if (!IsConstant && CalcStep.isUsable()) {
12461 // Calculate the step beforehand instead of doing this on each iteration.
12462 // (This is not used if the number of iterations may be kfold-ed).
12463 CalcStepExpr = CalcStep.get();
12464 }
Alexander Musman8dba6642014-04-22 13:09:42 +000012465 }
12466
Alexey Bataev182227b2015-08-20 10:54:39 +000012467 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
12468 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000012469 StepExpr, CalcStepExpr,
12470 buildPreInits(Context, ExprCaptures),
12471 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000012472}
12473
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012474static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
12475 Expr *NumIterations, Sema &SemaRef,
12476 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000012477 // Walk the vars and build update/final expressions for the CodeGen.
12478 SmallVector<Expr *, 8> Updates;
12479 SmallVector<Expr *, 8> Finals;
12480 Expr *Step = Clause.getStep();
12481 Expr *CalcStep = Clause.getCalcStep();
12482 // OpenMP [2.14.3.7, linear clause]
12483 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000012484 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000012485 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012486 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000012487 Step = cast<BinaryOperator>(CalcStep)->getLHS();
12488 bool HasErrors = false;
12489 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012490 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000012491 OpenMPLinearClauseKind LinKind = Clause.getModifier();
12492 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012493 SourceLocation ELoc;
12494 SourceRange ERange;
12495 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012496 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012497 ValueDecl *D = Res.first;
12498 if (Res.second || !D) {
12499 Updates.push_back(nullptr);
12500 Finals.push_back(nullptr);
12501 HasErrors = true;
12502 continue;
12503 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012504 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000012505 // OpenMP [2.15.11, distribute simd Construct]
12506 // A list item may not appear in a linear clause, unless it is the loop
12507 // iteration variable.
12508 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
12509 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
12510 SemaRef.Diag(ELoc,
12511 diag::err_omp_linear_distribute_var_non_loop_iteration);
12512 Updates.push_back(nullptr);
12513 Finals.push_back(nullptr);
12514 HasErrors = true;
12515 continue;
12516 }
Alexander Musman3276a272015-03-21 10:12:56 +000012517 Expr *InitExpr = *CurInit;
12518
12519 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000012520 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000012521 Expr *CapturedRef;
12522 if (LinKind == OMPC_LINEAR_uval)
12523 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
12524 else
12525 CapturedRef =
12526 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
12527 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
12528 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000012529
12530 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012531 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000012532 if (!Info.first)
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012533 Update =
Alexey Bataeve3727102018-04-18 15:57:46 +000012534 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012535 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataeve3727102018-04-18 15:57:46 +000012536 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012537 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012538 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012539 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000012540
12541 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012542 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000012543 if (!Info.first)
12544 Final =
12545 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
12546 InitExpr, NumIterations, Step, /*Subtract=*/false);
12547 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012548 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012549 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012550 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000012551
Alexander Musman3276a272015-03-21 10:12:56 +000012552 if (!Update.isUsable() || !Final.isUsable()) {
12553 Updates.push_back(nullptr);
12554 Finals.push_back(nullptr);
12555 HasErrors = true;
12556 } else {
12557 Updates.push_back(Update.get());
12558 Finals.push_back(Final.get());
12559 }
Richard Trieucc3949d2016-02-18 22:34:54 +000012560 ++CurInit;
12561 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000012562 }
12563 Clause.setUpdates(Updates);
12564 Clause.setFinals(Finals);
12565 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000012566}
12567
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012568OMPClause *Sema::ActOnOpenMPAlignedClause(
12569 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
12570 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012571 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000012572 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000012573 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12574 SourceLocation ELoc;
12575 SourceRange ERange;
12576 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012577 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000012578 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012579 // It will be analyzed later.
12580 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012581 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000012582 ValueDecl *D = Res.first;
12583 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012584 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012585
Alexey Bataev1efd1662016-03-29 10:59:56 +000012586 QualType QType = D->getType();
12587 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012588
12589 // OpenMP [2.8.1, simd construct, Restrictions]
12590 // The type of list items appearing in the aligned clause must be
12591 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012592 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012593 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000012594 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012595 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012596 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012597 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000012598 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012599 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000012600 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012601 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000012602 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012603 continue;
12604 }
12605
12606 // OpenMP [2.8.1, simd construct, Restrictions]
12607 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000012608 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000012609 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012610 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
12611 << getOpenMPClauseName(OMPC_aligned);
12612 continue;
12613 }
12614
Alexey Bataev1efd1662016-03-29 10:59:56 +000012615 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000012616 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000012617 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
12618 Vars.push_back(DefaultFunctionArrayConversion(
12619 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
12620 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000012621 }
12622
12623 // OpenMP [2.8.1, simd construct, Description]
12624 // The parameter of the aligned clause, alignment, must be a constant
12625 // positive integer expression.
12626 // If no optional parameter is specified, implementation-defined default
12627 // alignments for SIMD instructions on the target platforms are assumed.
12628 if (Alignment != nullptr) {
12629 ExprResult AlignResult =
12630 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
12631 if (AlignResult.isInvalid())
12632 return nullptr;
12633 Alignment = AlignResult.get();
12634 }
12635 if (Vars.empty())
12636 return nullptr;
12637
12638 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
12639 EndLoc, Vars, Alignment);
12640}
12641
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012642OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
12643 SourceLocation StartLoc,
12644 SourceLocation LParenLoc,
12645 SourceLocation EndLoc) {
12646 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012647 SmallVector<Expr *, 8> SrcExprs;
12648 SmallVector<Expr *, 8> DstExprs;
12649 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012650 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000012651 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
12652 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012653 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000012654 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012655 SrcExprs.push_back(nullptr);
12656 DstExprs.push_back(nullptr);
12657 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012658 continue;
12659 }
12660
Alexey Bataeved09d242014-05-28 05:53:51 +000012661 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012662 // OpenMP [2.1, C/C++]
12663 // A list item is a variable name.
12664 // OpenMP [2.14.4.1, Restrictions, p.1]
12665 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000012666 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012667 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000012668 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
12669 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012670 continue;
12671 }
12672
12673 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000012674 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012675
12676 QualType Type = VD->getType();
12677 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
12678 // It will be analyzed later.
12679 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012680 SrcExprs.push_back(nullptr);
12681 DstExprs.push_back(nullptr);
12682 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012683 continue;
12684 }
12685
12686 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
12687 // A list item that appears in a copyin clause must be threadprivate.
12688 if (!DSAStack->isThreadPrivate(VD)) {
12689 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000012690 << getOpenMPClauseName(OMPC_copyin)
12691 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012692 continue;
12693 }
12694
12695 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12696 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000012697 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012698 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000012699 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
12700 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012701 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012702 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012703 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012704 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000012705 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012706 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000012707 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012708 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000012709 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012710 // For arrays generate assignment operation for single element and replace
12711 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000012712 ExprResult AssignmentOp =
12713 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
12714 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012715 if (AssignmentOp.isInvalid())
12716 continue;
12717 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012718 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012719 if (AssignmentOp.isInvalid())
12720 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012721
12722 DSAStack->addDSA(VD, DE, OMPC_copyin);
12723 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012724 SrcExprs.push_back(PseudoSrcExpr);
12725 DstExprs.push_back(PseudoDstExpr);
12726 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012727 }
12728
Alexey Bataeved09d242014-05-28 05:53:51 +000012729 if (Vars.empty())
12730 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012731
Alexey Bataevf56f98c2015-04-16 05:39:01 +000012732 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
12733 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000012734}
12735
Alexey Bataevbae9a792014-06-27 10:37:06 +000012736OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
12737 SourceLocation StartLoc,
12738 SourceLocation LParenLoc,
12739 SourceLocation EndLoc) {
12740 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000012741 SmallVector<Expr *, 8> SrcExprs;
12742 SmallVector<Expr *, 8> DstExprs;
12743 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000012744 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012745 assert(RefExpr && "NULL expr in OpenMP linear clause.");
12746 SourceLocation ELoc;
12747 SourceRange ERange;
12748 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000012749 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000012750 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012751 // It will be analyzed later.
12752 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012753 SrcExprs.push_back(nullptr);
12754 DstExprs.push_back(nullptr);
12755 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012756 }
Alexey Bataeve122da12016-03-17 10:50:17 +000012757 ValueDecl *D = Res.first;
12758 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000012759 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012760
Alexey Bataeve122da12016-03-17 10:50:17 +000012761 QualType Type = D->getType();
12762 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012763
12764 // OpenMP [2.14.4.2, Restrictions, p.2]
12765 // A list item that appears in a copyprivate clause may not appear in a
12766 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000012767 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012768 DSAStackTy::DSAVarData DVar =
12769 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012770 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12771 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012772 Diag(ELoc, diag::err_omp_wrong_dsa)
12773 << getOpenMPClauseName(DVar.CKind)
12774 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012775 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012776 continue;
12777 }
12778
12779 // OpenMP [2.11.4.2, Restrictions, p.1]
12780 // All list items that appear in a copyprivate clause must be either
12781 // threadprivate or private in the enclosing context.
12782 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012783 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012784 if (DVar.CKind == OMPC_shared) {
12785 Diag(ELoc, diag::err_omp_required_access)
12786 << getOpenMPClauseName(OMPC_copyprivate)
12787 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000012788 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012789 continue;
12790 }
12791 }
12792 }
12793
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012794 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012795 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012796 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012797 << getOpenMPClauseName(OMPC_copyprivate) << Type
12798 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012799 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000012800 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012801 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000012802 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012803 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000012804 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012805 continue;
12806 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012807
Alexey Bataevbae9a792014-06-27 10:37:06 +000012808 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12809 // A variable of class type (or array thereof) that appears in a
12810 // copyin clause requires an accessible, unambiguous copy assignment
12811 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012812 Type = Context.getBaseElementType(Type.getNonReferenceType())
12813 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012814 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012815 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000012816 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012817 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
12818 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012819 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000012820 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012821 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
12822 ExprResult AssignmentOp = BuildBinOp(
12823 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012824 if (AssignmentOp.isInvalid())
12825 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012826 AssignmentOp =
12827 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012828 if (AssignmentOp.isInvalid())
12829 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012830
12831 // No need to mark vars as copyprivate, they are already threadprivate or
12832 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000012833 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000012834 Vars.push_back(
12835 VD ? RefExpr->IgnoreParens()
12836 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000012837 SrcExprs.push_back(PseudoSrcExpr);
12838 DstExprs.push_back(PseudoDstExpr);
12839 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000012840 }
12841
12842 if (Vars.empty())
12843 return nullptr;
12844
Alexey Bataeva63048e2015-03-23 06:18:07 +000012845 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12846 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012847}
12848
Alexey Bataev6125da92014-07-21 11:26:11 +000012849OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12850 SourceLocation StartLoc,
12851 SourceLocation LParenLoc,
12852 SourceLocation EndLoc) {
12853 if (VarList.empty())
12854 return nullptr;
12855
12856 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
12857}
Alexey Bataevdea47612014-07-23 07:46:59 +000012858
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012859OMPClause *
12860Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12861 SourceLocation DepLoc, SourceLocation ColonLoc,
12862 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12863 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012864 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012865 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012866 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012867 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000012868 return nullptr;
12869 }
12870 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012871 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12872 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000012873 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012874 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012875 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12876 /*Last=*/OMPC_DEPEND_unknown, Except)
12877 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012878 return nullptr;
12879 }
12880 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000012881 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012882 llvm::APSInt DepCounter(/*BitWidth=*/32);
12883 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000012884 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12885 if (const Expr *OrderedCountExpr =
12886 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012887 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
12888 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012889 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012890 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012891 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000012892 assert(RefExpr && "NULL expr in OpenMP shared clause.");
12893 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12894 // It will be analyzed later.
12895 Vars.push_back(RefExpr);
12896 continue;
12897 }
12898
12899 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000012900 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000012901 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000012902 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012903 DepCounter >= TotalDepCount) {
12904 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
12905 continue;
12906 }
12907 ++DepCounter;
12908 // OpenMP [2.13.9, Summary]
12909 // depend(dependence-type : vec), where dependence-type is:
12910 // 'sink' and where vec is the iteration vector, which has the form:
12911 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
12912 // where n is the value specified by the ordered clause in the loop
12913 // directive, xi denotes the loop iteration variable of the i-th nested
12914 // loop associated with the loop directive, and di is a constant
12915 // non-negative integer.
12916 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012917 // It will be analyzed later.
12918 Vars.push_back(RefExpr);
12919 continue;
12920 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012921 SimpleExpr = SimpleExpr->IgnoreImplicit();
12922 OverloadedOperatorKind OOK = OO_None;
12923 SourceLocation OOLoc;
12924 Expr *LHS = SimpleExpr;
12925 Expr *RHS = nullptr;
12926 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
12927 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
12928 OOLoc = BO->getOperatorLoc();
12929 LHS = BO->getLHS()->IgnoreParenImpCasts();
12930 RHS = BO->getRHS()->IgnoreParenImpCasts();
12931 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
12932 OOK = OCE->getOperator();
12933 OOLoc = OCE->getOperatorLoc();
12934 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12935 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
12936 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
12937 OOK = MCE->getMethodDecl()
12938 ->getNameInfo()
12939 .getName()
12940 .getCXXOverloadedOperator();
12941 OOLoc = MCE->getCallee()->getExprLoc();
12942 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
12943 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012944 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012945 SourceLocation ELoc;
12946 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000012947 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012948 if (Res.second) {
12949 // It will be analyzed later.
12950 Vars.push_back(RefExpr);
12951 }
12952 ValueDecl *D = Res.first;
12953 if (!D)
12954 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012955
Alexey Bataev17daedf2018-02-15 22:42:57 +000012956 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
12957 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
12958 continue;
12959 }
12960 if (RHS) {
12961 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
12962 RHS, OMPC_depend, /*StrictlyPositive=*/false);
12963 if (RHSRes.isInvalid())
12964 continue;
12965 }
12966 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012967 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012968 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012969 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000012970 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000012971 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000012972 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
12973 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000012974 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000012975 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000012976 continue;
12977 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012978 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012979 } else {
12980 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12981 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12982 (ASE &&
12983 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12984 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12985 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12986 << RefExpr->getSourceRange();
12987 continue;
12988 }
12989 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12990 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12991 ExprResult Res =
12992 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12993 getDiagnostics().setSuppressAllDiagnostics(Suppress);
12994 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12995 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12996 << RefExpr->getSourceRange();
12997 continue;
12998 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012999 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000013000 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000013001 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000013002
13003 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
13004 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000013005 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000013006 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
13007 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
13008 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
13009 }
13010 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
13011 Vars.empty())
13012 return nullptr;
13013
Alexey Bataev8b427062016-05-25 12:36:08 +000013014 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000013015 DepKind, DepLoc, ColonLoc, Vars,
13016 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000013017 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
13018 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000013019 DSAStack->addDoacrossDependClause(C, OpsOffs);
13020 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000013021}
Michael Wonge710d542015-08-07 16:16:36 +000013022
13023OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
13024 SourceLocation LParenLoc,
13025 SourceLocation EndLoc) {
13026 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000013027 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000013028
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013029 // OpenMP [2.9.1, Restrictions]
13030 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000013031 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000013032 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013033 return nullptr;
13034
Alexey Bataev931e19b2017-10-02 16:32:39 +000013035 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000013036 OpenMPDirectiveKind CaptureRegion =
13037 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
13038 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013039 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013040 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000013041 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13042 HelperValStmt = buildPreInits(Context, Captures);
13043 }
13044
Alexey Bataev8451efa2018-01-15 19:06:12 +000013045 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
13046 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000013047}
Kelvin Li0bff7af2015-11-23 05:32:03 +000013048
Alexey Bataeve3727102018-04-18 15:57:46 +000013049static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000013050 DSAStackTy *Stack, QualType QTy,
13051 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000013052 NamedDecl *ND;
13053 if (QTy->isIncompleteType(&ND)) {
13054 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
13055 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013056 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000013057 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
13058 !QTy.isTrivialType(SemaRef.Context))
13059 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013060 return true;
13061}
13062
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000013063/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013064/// (array section or array subscript) does NOT specify the whole size of the
13065/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013066static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013067 const Expr *E,
13068 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013069 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013070
13071 // If this is an array subscript, it refers to the whole size if the size of
13072 // the dimension is constant and equals 1. Also, an array section assumes the
13073 // format of an array subscript if no colon is used.
13074 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013075 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013076 return ATy->getSize().getSExtValue() != 1;
13077 // Size can't be evaluated statically.
13078 return false;
13079 }
13080
13081 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000013082 const Expr *LowerBound = OASE->getLowerBound();
13083 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013084
13085 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000013086 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013087 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000013088 Expr::EvalResult Result;
13089 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013090 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000013091
13092 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013093 if (ConstLowerBound.getSExtValue())
13094 return true;
13095 }
13096
13097 // If we don't have a length we covering the whole dimension.
13098 if (!Length)
13099 return false;
13100
13101 // If the base is a pointer, we don't have a way to get the size of the
13102 // pointee.
13103 if (BaseQTy->isPointerType())
13104 return false;
13105
13106 // We can only check if the length is the same as the size of the dimension
13107 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000013108 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013109 if (!CATy)
13110 return false;
13111
Fangrui Song407659a2018-11-30 23:41:18 +000013112 Expr::EvalResult Result;
13113 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013114 return false; // Can't get the integer value as a constant.
13115
Fangrui Song407659a2018-11-30 23:41:18 +000013116 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013117 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
13118}
13119
13120// Return true if it can be proven that the provided array expression (array
13121// section or array subscript) does NOT specify a single element of the array
13122// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000013123static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000013124 const Expr *E,
13125 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013126 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013127
13128 // An array subscript always refer to a single element. Also, an array section
13129 // assumes the format of an array subscript if no colon is used.
13130 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
13131 return false;
13132
13133 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000013134 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013135
13136 // If we don't have a length we have to check if the array has unitary size
13137 // for this dimension. Also, we should always expect a length if the base type
13138 // is pointer.
13139 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013140 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013141 return ATy->getSize().getSExtValue() != 1;
13142 // We cannot assume anything.
13143 return false;
13144 }
13145
13146 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000013147 Expr::EvalResult Result;
13148 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013149 return false; // Can't get the integer value as a constant.
13150
Fangrui Song407659a2018-11-30 23:41:18 +000013151 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013152 return ConstLength.getSExtValue() != 1;
13153}
13154
Samuel Antao661c0902016-05-26 17:39:58 +000013155// Return the expression of the base of the mappable expression or null if it
13156// cannot be determined and do all the necessary checks to see if the expression
13157// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000013158// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013159static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000013160 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000013161 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013162 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013163 SourceLocation ELoc = E->getExprLoc();
13164 SourceRange ERange = E->getSourceRange();
13165
13166 // The base of elements of list in a map clause have to be either:
13167 // - a reference to variable or field.
13168 // - a member expression.
13169 // - an array expression.
13170 //
13171 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
13172 // reference to 'r'.
13173 //
13174 // If we have:
13175 //
13176 // struct SS {
13177 // Bla S;
13178 // foo() {
13179 // #pragma omp target map (S.Arr[:12]);
13180 // }
13181 // }
13182 //
13183 // We want to retrieve the member expression 'this->S';
13184
Alexey Bataeve3727102018-04-18 15:57:46 +000013185 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013186
Samuel Antao5de996e2016-01-22 20:21:36 +000013187 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
13188 // If a list item is an array section, it must specify contiguous storage.
13189 //
13190 // For this restriction it is sufficient that we make sure only references
13191 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013192 // exist except in the rightmost expression (unless they cover the whole
13193 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000013194 //
13195 // r.ArrS[3:5].Arr[6:7]
13196 //
13197 // r.ArrS[3:5].x
13198 //
13199 // but these would be valid:
13200 // r.ArrS[3].Arr[6:7]
13201 //
13202 // r.ArrS[3].x
13203
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013204 bool AllowUnitySizeArraySection = true;
13205 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013206
Dmitry Polukhin644a9252016-03-11 07:58:34 +000013207 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013208 E = E->IgnoreParenImpCasts();
13209
13210 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
13211 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000013212 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013213
13214 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013215
13216 // If we got a reference to a declaration, we should not expect any array
13217 // section before that.
13218 AllowUnitySizeArraySection = false;
13219 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000013220
13221 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013222 CurComponents.emplace_back(CurE, CurE->getDecl());
13223 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013224 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000013225
13226 if (isa<CXXThisExpr>(BaseE))
13227 // We found a base expression: this->Val.
13228 RelevantExpr = CurE;
13229 else
13230 E = BaseE;
13231
13232 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013233 if (!NoDiagnose) {
13234 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
13235 << CurE->getSourceRange();
13236 return nullptr;
13237 }
13238 if (RelevantExpr)
13239 return nullptr;
13240 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000013241 }
13242
13243 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
13244
13245 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
13246 // A bit-field cannot appear in a map clause.
13247 //
13248 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013249 if (!NoDiagnose) {
13250 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
13251 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
13252 return nullptr;
13253 }
13254 if (RelevantExpr)
13255 return nullptr;
13256 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000013257 }
13258
13259 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13260 // If the type of a list item is a reference to a type T then the type
13261 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013262 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013263
13264 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
13265 // A list item cannot be a variable that is a member of a structure with
13266 // a union type.
13267 //
Alexey Bataeve3727102018-04-18 15:57:46 +000013268 if (CurType->isUnionType()) {
13269 if (!NoDiagnose) {
13270 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
13271 << CurE->getSourceRange();
13272 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013273 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013274 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013275 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013276
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013277 // If we got a member expression, we should not expect any array section
13278 // before that:
13279 //
13280 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
13281 // If a list item is an element of a structure, only the rightmost symbol
13282 // of the variable reference can be an array section.
13283 //
13284 AllowUnitySizeArraySection = false;
13285 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000013286
13287 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013288 CurComponents.emplace_back(CurE, FD);
13289 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013290 E = CurE->getBase()->IgnoreParenImpCasts();
13291
13292 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013293 if (!NoDiagnose) {
13294 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13295 << 0 << CurE->getSourceRange();
13296 return nullptr;
13297 }
13298 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000013299 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013300
13301 // If we got an array subscript that express the whole dimension we
13302 // can have any array expressions before. If it only expressing part of
13303 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000013304 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013305 E->getType()))
13306 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000013307
Patrick Lystere13b1e32019-01-02 19:28:48 +000013308 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13309 Expr::EvalResult Result;
13310 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
13311 if (!Result.Val.getInt().isNullValue()) {
13312 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13313 diag::err_omp_invalid_map_this_expr);
13314 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
13315 diag::note_omp_invalid_subscript_on_this_ptr_map);
13316 }
13317 }
13318 RelevantExpr = TE;
13319 }
13320
Samuel Antao90927002016-04-26 14:54:23 +000013321 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013322 CurComponents.emplace_back(CurE, nullptr);
13323 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013324 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000013325 E = CurE->getBase()->IgnoreParenImpCasts();
13326
Alexey Bataev27041fa2017-12-05 15:22:49 +000013327 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013328 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13329
Samuel Antao5de996e2016-01-22 20:21:36 +000013330 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13331 // If the type of a list item is a reference to a type T then the type
13332 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000013333 if (CurType->isReferenceType())
13334 CurType = CurType->getPointeeType();
13335
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013336 bool IsPointer = CurType->isAnyPointerType();
13337
13338 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013339 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
13340 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013341 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013342 }
13343
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013344 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000013345 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013346 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000013347 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013348
Samuel Antaodab51bb2016-07-18 23:22:11 +000013349 if (AllowWholeSizeArraySection) {
13350 // Any array section is currently allowed. Allowing a whole size array
13351 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013352 //
13353 // If this array section refers to the whole dimension we can still
13354 // accept other array sections before this one, except if the base is a
13355 // pointer. Otherwise, only unitary sections are accepted.
13356 if (NotWhole || IsPointer)
13357 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000013358 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013359 // A unity or whole array section is not allowed and that is not
13360 // compatible with the properties of the current array section.
13361 SemaRef.Diag(
13362 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
13363 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000013364 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000013365 }
Samuel Antao90927002016-04-26 14:54:23 +000013366
Patrick Lystere13b1e32019-01-02 19:28:48 +000013367 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
13368 Expr::EvalResult ResultR;
13369 Expr::EvalResult ResultL;
13370 if (CurE->getLength()->EvaluateAsInt(ResultR,
13371 SemaRef.getASTContext())) {
13372 if (!ResultR.Val.getInt().isOneValue()) {
13373 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13374 diag::err_omp_invalid_map_this_expr);
13375 SemaRef.Diag(CurE->getLength()->getExprLoc(),
13376 diag::note_omp_invalid_length_on_this_ptr_mapping);
13377 }
13378 }
13379 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
13380 ResultL, SemaRef.getASTContext())) {
13381 if (!ResultL.Val.getInt().isNullValue()) {
13382 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13383 diag::err_omp_invalid_map_this_expr);
13384 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
13385 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
13386 }
13387 }
13388 RelevantExpr = TE;
13389 }
13390
Samuel Antao90927002016-04-26 14:54:23 +000013391 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000013392 CurComponents.emplace_back(CurE, nullptr);
13393 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000013394 if (!NoDiagnose) {
13395 // If nothing else worked, this is not a valid map clause expression.
13396 SemaRef.Diag(
13397 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
13398 << ERange;
13399 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000013400 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013401 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013402 }
13403
13404 return RelevantExpr;
13405}
13406
13407// Return true if expression E associated with value VD has conflicts with other
13408// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000013409static bool checkMapConflicts(
13410 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000013411 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000013412 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
13413 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013414 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000013415 SourceLocation ELoc = E->getExprLoc();
13416 SourceRange ERange = E->getSourceRange();
13417
13418 // In order to easily check the conflicts we need to match each component of
13419 // the expression under test with the components of the expressions that are
13420 // already in the stack.
13421
Samuel Antao5de996e2016-01-22 20:21:36 +000013422 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013423 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013424 "Map clause expression with unexpected base!");
13425
13426 // Variables to help detecting enclosing problems in data environment nests.
13427 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000013428 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000013429
Samuel Antao90927002016-04-26 14:54:23 +000013430 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
13431 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000013432 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
13433 ERange, CKind, &EnclosingExpr,
13434 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
13435 StackComponents,
13436 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013437 assert(!StackComponents.empty() &&
13438 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000013439 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000013440 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000013441 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013442
Samuel Antao90927002016-04-26 14:54:23 +000013443 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000013444 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000013445
Samuel Antao5de996e2016-01-22 20:21:36 +000013446 // Expressions must start from the same base. Here we detect at which
13447 // point both expressions diverge from each other and see if we can
13448 // detect if the memory referred to both expressions is contiguous and
13449 // do not overlap.
13450 auto CI = CurComponents.rbegin();
13451 auto CE = CurComponents.rend();
13452 auto SI = StackComponents.rbegin();
13453 auto SE = StackComponents.rend();
13454 for (; CI != CE && SI != SE; ++CI, ++SI) {
13455
13456 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
13457 // At most one list item can be an array item derived from a given
13458 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000013459 if (CurrentRegionOnly &&
13460 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
13461 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
13462 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
13463 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
13464 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000013465 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000013466 << CI->getAssociatedExpression()->getSourceRange();
13467 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
13468 diag::note_used_here)
13469 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000013470 return true;
13471 }
13472
13473 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000013474 if (CI->getAssociatedExpression()->getStmtClass() !=
13475 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000013476 break;
13477
13478 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000013479 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000013480 break;
13481 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000013482 // Check if the extra components of the expressions in the enclosing
13483 // data environment are redundant for the current base declaration.
13484 // If they are, the maps completely overlap, which is legal.
13485 for (; SI != SE; ++SI) {
13486 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000013487 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000013488 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000013489 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000013490 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000013491 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013492 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000013493 Type =
13494 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
13495 }
13496 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000013497 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000013498 SemaRef, SI->getAssociatedExpression(), Type))
13499 break;
13500 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013501
13502 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13503 // List items of map clauses in the same construct must not share
13504 // original storage.
13505 //
13506 // If the expressions are exactly the same or one is a subset of the
13507 // other, it means they are sharing storage.
13508 if (CI == CE && SI == SE) {
13509 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013510 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000013511 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013512 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013513 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013514 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13515 << ERange;
13516 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013517 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13518 << RE->getSourceRange();
13519 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013520 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013521 // If we find the same expression in the enclosing data environment,
13522 // that is legal.
13523 IsEnclosedByDataEnvironmentExpr = true;
13524 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000013525 }
13526
Samuel Antao90927002016-04-26 14:54:23 +000013527 QualType DerivedType =
13528 std::prev(CI)->getAssociatedDeclaration()->getType();
13529 SourceLocation DerivedLoc =
13530 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000013531
13532 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13533 // If the type of a list item is a reference to a type T then the type
13534 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000013535 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013536
13537 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
13538 // A variable for which the type is pointer and an array section
13539 // derived from that variable must not appear as list items of map
13540 // clauses of the same construct.
13541 //
13542 // Also, cover one of the cases in:
13543 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13544 // If any part of the original storage of a list item has corresponding
13545 // storage in the device data environment, all of the original storage
13546 // must have corresponding storage in the device data environment.
13547 //
13548 if (DerivedType->isAnyPointerType()) {
13549 if (CI == CE || SI == SE) {
13550 SemaRef.Diag(
13551 DerivedLoc,
13552 diag::err_omp_pointer_mapped_along_with_derived_section)
13553 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013554 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13555 << RE->getSourceRange();
13556 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000013557 }
13558 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000013559 SI->getAssociatedExpression()->getStmtClass() ||
13560 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
13561 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000013562 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000013563 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000013564 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000013565 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13566 << RE->getSourceRange();
13567 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000013568 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013569 }
13570
13571 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
13572 // List items of map clauses in the same construct must not share
13573 // original storage.
13574 //
13575 // An expression is a subset of the other.
13576 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013577 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000013578 if (CI != CE || SI != SE) {
13579 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
13580 // a pointer.
13581 auto Begin =
13582 CI != CE ? CurComponents.begin() : StackComponents.begin();
13583 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
13584 auto It = Begin;
13585 while (It != End && !It->getAssociatedDeclaration())
13586 std::advance(It, 1);
13587 assert(It != End &&
13588 "Expected at least one component with the declaration.");
13589 if (It != Begin && It->getAssociatedDeclaration()
13590 ->getType()
13591 .getCanonicalType()
13592 ->isAnyPointerType()) {
13593 IsEnclosedByDataEnvironmentExpr = false;
13594 EnclosingExpr = nullptr;
13595 return false;
13596 }
13597 }
Samuel Antao661c0902016-05-26 17:39:58 +000013598 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000013599 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000013600 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000013601 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
13602 << ERange;
13603 }
Samuel Antao5de996e2016-01-22 20:21:36 +000013604 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
13605 << RE->getSourceRange();
13606 return true;
13607 }
13608
13609 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000013610 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000013611 if (!CurrentRegionOnly && SI != SE)
13612 EnclosingExpr = RE;
13613
13614 // The current expression is a subset of the expression in the data
13615 // environment.
13616 IsEnclosedByDataEnvironmentExpr |=
13617 (!CurrentRegionOnly && CI != CE && SI == SE);
13618
13619 return false;
13620 });
13621
13622 if (CurrentRegionOnly)
13623 return FoundError;
13624
13625 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
13626 // If any part of the original storage of a list item has corresponding
13627 // storage in the device data environment, all of the original storage must
13628 // have corresponding storage in the device data environment.
13629 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
13630 // If a list item is an element of a structure, and a different element of
13631 // the structure has a corresponding list item in the device data environment
13632 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000013633 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000013634 // data environment prior to the task encountering the construct.
13635 //
13636 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
13637 SemaRef.Diag(ELoc,
13638 diag::err_omp_original_storage_is_shared_and_does_not_contain)
13639 << ERange;
13640 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
13641 << EnclosingExpr->getSourceRange();
13642 return true;
13643 }
13644
13645 return FoundError;
13646}
13647
Michael Kruse4304e9d2019-02-19 16:38:20 +000013648// Look up the user-defined mapper given the mapper name and mapped type, and
13649// build a reference to it.
Benjamin Kramerba2ea932019-03-28 17:18:42 +000013650static ExprResult buildUserDefinedMapperRef(Sema &SemaRef, Scope *S,
13651 CXXScopeSpec &MapperIdScopeSpec,
13652 const DeclarationNameInfo &MapperId,
13653 QualType Type,
13654 Expr *UnresolvedMapper) {
Michael Kruse4304e9d2019-02-19 16:38:20 +000013655 if (MapperIdScopeSpec.isInvalid())
13656 return ExprError();
13657 // Find all user-defined mappers with the given MapperId.
13658 SmallVector<UnresolvedSet<8>, 4> Lookups;
13659 LookupResult Lookup(SemaRef, MapperId, Sema::LookupOMPMapperName);
13660 Lookup.suppressDiagnostics();
13661 if (S) {
13662 while (S && SemaRef.LookupParsedName(Lookup, S, &MapperIdScopeSpec)) {
13663 NamedDecl *D = Lookup.getRepresentativeDecl();
13664 while (S && !S->isDeclScope(D))
13665 S = S->getParent();
13666 if (S)
13667 S = S->getParent();
13668 Lookups.emplace_back();
13669 Lookups.back().append(Lookup.begin(), Lookup.end());
13670 Lookup.clear();
13671 }
13672 } else if (auto *ULE = cast_or_null<UnresolvedLookupExpr>(UnresolvedMapper)) {
13673 // Extract the user-defined mappers with the given MapperId.
13674 Lookups.push_back(UnresolvedSet<8>());
13675 for (NamedDecl *D : ULE->decls()) {
13676 auto *DMD = cast<OMPDeclareMapperDecl>(D);
13677 assert(DMD && "Expect valid OMPDeclareMapperDecl during instantiation.");
13678 Lookups.back().addDecl(DMD);
13679 }
13680 }
13681 // Defer the lookup for dependent types. The results will be passed through
13682 // UnresolvedMapper on instantiation.
13683 if (SemaRef.CurContext->isDependentContext() || Type->isDependentType() ||
13684 Type->isInstantiationDependentType() ||
13685 Type->containsUnexpandedParameterPack() ||
13686 filterLookupForUDReductionAndMapper<bool>(Lookups, [](ValueDecl *D) {
13687 return !D->isInvalidDecl() &&
13688 (D->getType()->isDependentType() ||
13689 D->getType()->isInstantiationDependentType() ||
13690 D->getType()->containsUnexpandedParameterPack());
13691 })) {
13692 UnresolvedSet<8> URS;
13693 for (const UnresolvedSet<8> &Set : Lookups) {
13694 if (Set.empty())
13695 continue;
13696 URS.append(Set.begin(), Set.end());
13697 }
13698 return UnresolvedLookupExpr::Create(
13699 SemaRef.Context, /*NamingClass=*/nullptr,
13700 MapperIdScopeSpec.getWithLocInContext(SemaRef.Context), MapperId,
13701 /*ADL=*/false, /*Overloaded=*/true, URS.begin(), URS.end());
13702 }
13703 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
13704 // The type must be of struct, union or class type in C and C++
13705 if (!Type->isStructureOrClassType() && !Type->isUnionType())
13706 return ExprEmpty();
13707 SourceLocation Loc = MapperId.getLoc();
13708 // Perform argument dependent lookup.
13709 if (SemaRef.getLangOpts().CPlusPlus && !MapperIdScopeSpec.isSet())
13710 argumentDependentLookup(SemaRef, MapperId, Loc, Type, Lookups);
13711 // Return the first user-defined mapper with the desired type.
13712 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13713 Lookups, [&SemaRef, Type](ValueDecl *D) -> ValueDecl * {
13714 if (!D->isInvalidDecl() &&
13715 SemaRef.Context.hasSameType(D->getType(), Type))
13716 return D;
13717 return nullptr;
13718 }))
13719 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13720 // Find the first user-defined mapper with a type derived from the desired
13721 // type.
13722 if (auto *VD = filterLookupForUDReductionAndMapper<ValueDecl *>(
13723 Lookups, [&SemaRef, Type, Loc](ValueDecl *D) -> ValueDecl * {
13724 if (!D->isInvalidDecl() &&
13725 SemaRef.IsDerivedFrom(Loc, Type, D->getType()) &&
13726 !Type.isMoreQualifiedThan(D->getType()))
13727 return D;
13728 return nullptr;
13729 })) {
13730 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
13731 /*DetectVirtual=*/false);
13732 if (SemaRef.IsDerivedFrom(Loc, Type, VD->getType(), Paths)) {
13733 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
13734 VD->getType().getUnqualifiedType()))) {
13735 if (SemaRef.CheckBaseClassAccess(
13736 Loc, VD->getType(), Type, Paths.front(),
13737 /*DiagID=*/0) != Sema::AR_inaccessible) {
13738 return SemaRef.BuildDeclRefExpr(VD, Type, VK_LValue, Loc);
13739 }
13740 }
13741 }
13742 }
13743 // Report error if a mapper is specified, but cannot be found.
13744 if (MapperIdScopeSpec.isSet() || MapperId.getAsString() != "default") {
13745 SemaRef.Diag(Loc, diag::err_omp_invalid_mapper)
13746 << Type << MapperId.getName();
13747 return ExprError();
13748 }
13749 return ExprEmpty();
13750}
13751
Samuel Antao661c0902016-05-26 17:39:58 +000013752namespace {
13753// Utility struct that gathers all the related lists associated with a mappable
13754// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013755struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000013756 // The list of expressions.
13757 ArrayRef<Expr *> VarList;
13758 // The list of processed expressions.
13759 SmallVector<Expr *, 16> ProcessedVarList;
13760 // The mappble components for each expression.
13761 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
13762 // The base declaration of the variable.
13763 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
Michael Kruse4304e9d2019-02-19 16:38:20 +000013764 // The reference to the user-defined mapper associated with every expression.
13765 SmallVector<Expr *, 16> UDMapperList;
Samuel Antao661c0902016-05-26 17:39:58 +000013766
13767 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
13768 // We have a list of components and base declarations for each entry in the
13769 // variable list.
13770 VarComponents.reserve(VarList.size());
13771 VarBaseDeclarations.reserve(VarList.size());
13772 }
13773};
13774}
13775
13776// Check the validity of the provided variable list for the provided clause kind
Michael Kruse4304e9d2019-02-19 16:38:20 +000013777// \a CKind. In the check process the valid expressions, mappable expression
13778// components, variables, and user-defined mappers are extracted and used to
13779// fill \a ProcessedVarList, \a VarComponents, \a VarBaseDeclarations, and \a
13780// UDMapperList in MVLI. \a MapType, \a IsMapTypeImplicit, \a MapperIdScopeSpec,
13781// and \a MapperId are expected to be valid if the clause kind is 'map'.
13782static void checkMappableExpressionList(
13783 Sema &SemaRef, DSAStackTy *DSAS, OpenMPClauseKind CKind,
13784 MappableVarListInfo &MVLI, SourceLocation StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000013785 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo MapperId,
13786 ArrayRef<Expr *> UnresolvedMappers,
Michael Kruse4304e9d2019-02-19 16:38:20 +000013787 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
Michael Kruse01f670d2019-02-22 22:29:42 +000013788 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013789 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
13790 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000013791 "Unexpected clause kind with mappable expressions!");
Michael Kruse01f670d2019-02-22 22:29:42 +000013792
13793 // If the identifier of user-defined mapper is not specified, it is "default".
13794 // We do not change the actual name in this clause to distinguish whether a
13795 // mapper is specified explicitly, i.e., it is not explicitly specified when
13796 // MapperId.getName() is empty.
13797 if (!MapperId.getName() || MapperId.getName().isEmpty()) {
13798 auto &DeclNames = SemaRef.getASTContext().DeclarationNames;
13799 MapperId.setName(DeclNames.getIdentifier(
13800 &SemaRef.getASTContext().Idents.get("default")));
13801 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013802
13803 // Iterators to find the current unresolved mapper expression.
13804 auto UMIt = UnresolvedMappers.begin(), UMEnd = UnresolvedMappers.end();
13805 bool UpdateUMIt = false;
13806 Expr *UnresolvedMapper = nullptr;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013807
Samuel Antao90927002016-04-26 14:54:23 +000013808 // Keep track of the mappable components and base declarations in this clause.
13809 // Each entry in the list is going to have a list of components associated. We
13810 // record each set of the components so that we can build the clause later on.
13811 // In the end we should have the same amount of declarations and component
13812 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000013813
Alexey Bataeve3727102018-04-18 15:57:46 +000013814 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000013815 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013816 SourceLocation ELoc = RE->getExprLoc();
13817
Michael Kruse4304e9d2019-02-19 16:38:20 +000013818 // Find the current unresolved mapper expression.
13819 if (UpdateUMIt && UMIt != UMEnd) {
13820 UMIt++;
13821 assert(
13822 UMIt != UMEnd &&
13823 "Expect the size of UnresolvedMappers to match with that of VarList");
13824 }
13825 UpdateUMIt = true;
13826 if (UMIt != UMEnd)
13827 UnresolvedMapper = *UMIt;
13828
Alexey Bataeve3727102018-04-18 15:57:46 +000013829 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013830
13831 if (VE->isValueDependent() || VE->isTypeDependent() ||
13832 VE->isInstantiationDependent() ||
13833 VE->containsUnexpandedParameterPack()) {
Michael Kruse0336c752019-02-25 20:34:15 +000013834 // Try to find the associated user-defined mapper.
13835 ExprResult ER = buildUserDefinedMapperRef(
13836 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13837 VE->getType().getCanonicalType(), UnresolvedMapper);
13838 if (ER.isInvalid())
13839 continue;
13840 MVLI.UDMapperList.push_back(ER.get());
Samuel Antao5de996e2016-01-22 20:21:36 +000013841 // We can only analyze this information once the missing information is
13842 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000013843 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013844 continue;
13845 }
13846
Alexey Bataeve3727102018-04-18 15:57:46 +000013847 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013848
Samuel Antao5de996e2016-01-22 20:21:36 +000013849 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000013850 SemaRef.Diag(ELoc,
13851 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000013852 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000013853 continue;
13854 }
13855
Samuel Antao90927002016-04-26 14:54:23 +000013856 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
13857 ValueDecl *CurDeclaration = nullptr;
13858
13859 // Obtain the array or member expression bases if required. Also, fill the
13860 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000013861 const Expr *BE = checkMapClauseExpressionBase(
13862 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000013863 if (!BE)
13864 continue;
13865
Samuel Antao90927002016-04-26 14:54:23 +000013866 assert(!CurComponents.empty() &&
13867 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000013868
Patrick Lystere13b1e32019-01-02 19:28:48 +000013869 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
13870 // Add store "this" pointer to class in DSAStackTy for future checking
13871 DSAS->addMappedClassesQualTypes(TE->getType());
Michael Kruse0336c752019-02-25 20:34:15 +000013872 // Try to find the associated user-defined mapper.
13873 ExprResult ER = buildUserDefinedMapperRef(
13874 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
13875 VE->getType().getCanonicalType(), UnresolvedMapper);
13876 if (ER.isInvalid())
13877 continue;
13878 MVLI.UDMapperList.push_back(ER.get());
Patrick Lystere13b1e32019-01-02 19:28:48 +000013879 // Skip restriction checking for variable or field declarations
13880 MVLI.ProcessedVarList.push_back(RE);
13881 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13882 MVLI.VarComponents.back().append(CurComponents.begin(),
13883 CurComponents.end());
13884 MVLI.VarBaseDeclarations.push_back(nullptr);
13885 continue;
13886 }
13887
Samuel Antao90927002016-04-26 14:54:23 +000013888 // For the following checks, we rely on the base declaration which is
13889 // expected to be associated with the last component. The declaration is
13890 // expected to be a variable or a field (if 'this' is being mapped).
13891 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
13892 assert(CurDeclaration && "Null decl on map clause.");
13893 assert(
13894 CurDeclaration->isCanonicalDecl() &&
13895 "Expecting components to have associated only canonical declarations.");
13896
13897 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000013898 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000013899
13900 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000013901 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000013902
13903 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000013904 // threadprivate variables cannot appear in a map clause.
13905 // OpenMP 4.5 [2.10.5, target update Construct]
13906 // threadprivate variables cannot appear in a from clause.
13907 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013908 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013909 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
13910 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000013911 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013912 continue;
13913 }
13914
Samuel Antao5de996e2016-01-22 20:21:36 +000013915 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13916 // A list item cannot appear in both a map clause and a data-sharing
13917 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000013918
Samuel Antao5de996e2016-01-22 20:21:36 +000013919 // Check conflicts with other map clause expressions. We check the conflicts
13920 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000013921 // environment, because the restrictions are different. We only have to
13922 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000013923 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013924 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013925 break;
Samuel Antao661c0902016-05-26 17:39:58 +000013926 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013927 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013928 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013929 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013930
Samuel Antao661c0902016-05-26 17:39:58 +000013931 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000013932 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13933 // If the type of a list item is a reference to a type T then the type will
13934 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000013935 auto I = llvm::find_if(
13936 CurComponents,
13937 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
13938 return MC.getAssociatedDeclaration();
13939 });
13940 assert(I != CurComponents.end() && "Null decl on map clause.");
13941 QualType Type =
13942 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013943
Samuel Antao661c0902016-05-26 17:39:58 +000013944 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
13945 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000013946 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000013947 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013948 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000013949 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000013950 continue;
13951
Samuel Antao661c0902016-05-26 17:39:58 +000013952 if (CKind == OMPC_map) {
13953 // target enter data
13954 // OpenMP [2.10.2, Restrictions, p. 99]
13955 // A map-type must be specified in all map clauses and must be either
13956 // to or alloc.
13957 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
13958 if (DKind == OMPD_target_enter_data &&
13959 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
13960 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13961 << (IsMapTypeImplicit ? 1 : 0)
13962 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13963 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013964 continue;
13965 }
Samuel Antao661c0902016-05-26 17:39:58 +000013966
13967 // target exit_data
13968 // OpenMP [2.10.3, Restrictions, p. 102]
13969 // A map-type must be specified in all map clauses and must be either
13970 // from, release, or delete.
13971 if (DKind == OMPD_target_exit_data &&
13972 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
13973 MapType == OMPC_MAP_delete)) {
13974 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13975 << (IsMapTypeImplicit ? 1 : 0)
13976 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13977 << getOpenMPDirectiveName(DKind);
13978 continue;
13979 }
13980
13981 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13982 // A list item cannot appear in both a map clause and a data-sharing
13983 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000013984 if (VD && isOpenMPTargetExecutionDirective(DKind)) {
13985 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013986 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000013987 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000013988 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000013989 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000013990 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000013991 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000013992 continue;
13993 }
13994 }
Michael Kruse01f670d2019-02-22 22:29:42 +000013995 }
Michael Kruse4304e9d2019-02-19 16:38:20 +000013996
Michael Kruse01f670d2019-02-22 22:29:42 +000013997 // Try to find the associated user-defined mapper.
Michael Kruse0336c752019-02-25 20:34:15 +000013998 ExprResult ER = buildUserDefinedMapperRef(
13999 SemaRef, DSAS->getCurScope(), MapperIdScopeSpec, MapperId,
14000 Type.getCanonicalType(), UnresolvedMapper);
14001 if (ER.isInvalid())
14002 continue;
14003 MVLI.UDMapperList.push_back(ER.get());
Carlo Bertollib74bfc82016-03-18 21:43:32 +000014004
Samuel Antao90927002016-04-26 14:54:23 +000014005 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000014006 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000014007
14008 // Store the components in the stack so that they can be used to check
14009 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000014010 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
14011 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000014012
14013 // Save the components and declaration to create the clause. For purposes of
14014 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000014015 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000014016 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14017 MVLI.VarComponents.back().append(CurComponents.begin(),
14018 CurComponents.end());
14019 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
14020 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000014021 }
Samuel Antao661c0902016-05-26 17:39:58 +000014022}
14023
Michael Kruse4304e9d2019-02-19 16:38:20 +000014024OMPClause *Sema::ActOnOpenMPMapClause(
14025 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
14026 ArrayRef<SourceLocation> MapTypeModifiersLoc,
14027 CXXScopeSpec &MapperIdScopeSpec, DeclarationNameInfo &MapperId,
14028 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit, SourceLocation MapLoc,
14029 SourceLocation ColonLoc, ArrayRef<Expr *> VarList,
14030 const OMPVarListLocTy &Locs, ArrayRef<Expr *> UnresolvedMappers) {
14031 OpenMPMapModifierKind Modifiers[] = {OMPC_MAP_MODIFIER_unknown,
14032 OMPC_MAP_MODIFIER_unknown,
14033 OMPC_MAP_MODIFIER_unknown};
Kelvin Lief579432018-12-18 22:18:41 +000014034 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
14035
14036 // Process map-type-modifiers, flag errors for duplicate modifiers.
14037 unsigned Count = 0;
14038 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
14039 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
14040 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
14041 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
14042 continue;
14043 }
14044 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000014045 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000014046 Modifiers[Count] = MapTypeModifiers[I];
14047 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
14048 ++Count;
14049 }
14050
Michael Kruse4304e9d2019-02-19 16:38:20 +000014051 MappableVarListInfo MVLI(VarList);
14052 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, Locs.StartLoc,
Michael Kruse01f670d2019-02-22 22:29:42 +000014053 MapperIdScopeSpec, MapperId, UnresolvedMappers,
14054 MapType, IsMapTypeImplicit);
Michael Kruse4304e9d2019-02-19 16:38:20 +000014055
Samuel Antao5de996e2016-01-22 20:21:36 +000014056 // We need to produce a map clause even if we don't have variables so that
14057 // other diagnostics related with non-existing map clauses are accurate.
Michael Kruse4304e9d2019-02-19 16:38:20 +000014058 return OMPMapClause::Create(Context, Locs, MVLI.ProcessedVarList,
14059 MVLI.VarBaseDeclarations, MVLI.VarComponents,
14060 MVLI.UDMapperList, Modifiers, ModifiersLoc,
14061 MapperIdScopeSpec.getWithLocInContext(Context),
14062 MapperId, MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000014063}
Kelvin Li099bb8c2015-11-24 20:50:12 +000014064
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014065QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
14066 TypeResult ParsedType) {
14067 assert(ParsedType.isUsable());
14068
14069 QualType ReductionType = GetTypeFromParser(ParsedType.get());
14070 if (ReductionType.isNull())
14071 return QualType();
14072
14073 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
14074 // A type name in a declare reduction directive cannot be a function type, an
14075 // array type, a reference type, or a type qualified with const, volatile or
14076 // restrict.
14077 if (ReductionType.hasQualifiers()) {
14078 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
14079 return QualType();
14080 }
14081
14082 if (ReductionType->isFunctionType()) {
14083 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
14084 return QualType();
14085 }
14086 if (ReductionType->isReferenceType()) {
14087 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
14088 return QualType();
14089 }
14090 if (ReductionType->isArrayType()) {
14091 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
14092 return QualType();
14093 }
14094 return ReductionType;
14095}
14096
14097Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
14098 Scope *S, DeclContext *DC, DeclarationName Name,
14099 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
14100 AccessSpecifier AS, Decl *PrevDeclInScope) {
14101 SmallVector<Decl *, 8> Decls;
14102 Decls.reserve(ReductionTypes.size());
14103
14104 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000014105 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014106 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
14107 // A reduction-identifier may not be re-declared in the current scope for the
14108 // same type or for a type that is compatible according to the base language
14109 // rules.
14110 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
14111 OMPDeclareReductionDecl *PrevDRD = nullptr;
14112 bool InCompoundScope = true;
14113 if (S != nullptr) {
14114 // Find previous declaration with the same name not referenced in other
14115 // declarations.
14116 FunctionScopeInfo *ParentFn = getEnclosingFunction();
14117 InCompoundScope =
14118 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
14119 LookupName(Lookup, S);
14120 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14121 /*AllowInlineNamespace=*/false);
14122 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000014123 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014124 while (Filter.hasNext()) {
14125 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
14126 if (InCompoundScope) {
14127 auto I = UsedAsPrevious.find(PrevDecl);
14128 if (I == UsedAsPrevious.end())
14129 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000014130 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014131 UsedAsPrevious[D] = true;
14132 }
14133 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14134 PrevDecl->getLocation();
14135 }
14136 Filter.done();
14137 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014138 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014139 if (!PrevData.second) {
14140 PrevDRD = PrevData.first;
14141 break;
14142 }
14143 }
14144 }
14145 } else if (PrevDeclInScope != nullptr) {
14146 auto *PrevDRDInScope = PrevDRD =
14147 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
14148 do {
14149 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
14150 PrevDRDInScope->getLocation();
14151 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
14152 } while (PrevDRDInScope != nullptr);
14153 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014154 for (const auto &TyData : ReductionTypes) {
14155 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014156 bool Invalid = false;
14157 if (I != PreviousRedeclTypes.end()) {
14158 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
14159 << TyData.first;
14160 Diag(I->second, diag::note_previous_definition);
14161 Invalid = true;
14162 }
14163 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
14164 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
14165 Name, TyData.first, PrevDRD);
14166 DC->addDecl(DRD);
14167 DRD->setAccess(AS);
14168 Decls.push_back(DRD);
14169 if (Invalid)
14170 DRD->setInvalidDecl();
14171 else
14172 PrevDRD = DRD;
14173 }
14174
14175 return DeclGroupPtrTy::make(
14176 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
14177}
14178
14179void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
14180 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14181
14182 // Enter new function scope.
14183 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000014184 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014185 getCurFunction()->setHasOMPDeclareReductionCombiner();
14186
14187 if (S != nullptr)
14188 PushDeclContext(S, DRD);
14189 else
14190 CurContext = DRD;
14191
Faisal Valid143a0c2017-04-01 21:30:49 +000014192 PushExpressionEvaluationContext(
14193 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014194
14195 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014196 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
14197 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
14198 // uses semantics of argument handles by value, but it should be passed by
14199 // reference. C lang does not support references, so pass all parameters as
14200 // pointers.
14201 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000014202 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014203 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014204 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
14205 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
14206 // uses semantics of argument handles by value, but it should be passed by
14207 // reference. C lang does not support references, so pass all parameters as
14208 // pointers.
14209 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000014210 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014211 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
14212 if (S != nullptr) {
14213 PushOnScopeChains(OmpInParm, S);
14214 PushOnScopeChains(OmpOutParm, S);
14215 } else {
14216 DRD->addDecl(OmpInParm);
14217 DRD->addDecl(OmpOutParm);
14218 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000014219 Expr *InE =
14220 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
14221 Expr *OutE =
14222 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
14223 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014224}
14225
14226void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
14227 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14228 DiscardCleanupsInEvaluationContext();
14229 PopExpressionEvaluationContext();
14230
14231 PopDeclContext();
14232 PopFunctionScopeInfo();
14233
14234 if (Combiner != nullptr)
14235 DRD->setCombiner(Combiner);
14236 else
14237 DRD->setInvalidDecl();
14238}
14239
Alexey Bataev070f43a2017-09-06 14:49:58 +000014240VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014241 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14242
14243 // Enter new function scope.
14244 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000014245 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014246
14247 if (S != nullptr)
14248 PushDeclContext(S, DRD);
14249 else
14250 CurContext = DRD;
14251
Faisal Valid143a0c2017-04-01 21:30:49 +000014252 PushExpressionEvaluationContext(
14253 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014254
14255 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014256 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
14257 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
14258 // uses semantics of argument handles by value, but it should be passed by
14259 // reference. C lang does not support references, so pass all parameters as
14260 // pointers.
14261 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000014262 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014263 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014264 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
14265 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
14266 // uses semantics of argument handles by value, but it should be passed by
14267 // reference. C lang does not support references, so pass all parameters as
14268 // pointers.
14269 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000014270 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000014271 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014272 if (S != nullptr) {
14273 PushOnScopeChains(OmpPrivParm, S);
14274 PushOnScopeChains(OmpOrigParm, S);
14275 } else {
14276 DRD->addDecl(OmpPrivParm);
14277 DRD->addDecl(OmpOrigParm);
14278 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000014279 Expr *OrigE =
14280 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
14281 Expr *PrivE =
14282 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
14283 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000014284 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014285}
14286
Alexey Bataev070f43a2017-09-06 14:49:58 +000014287void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
14288 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014289 auto *DRD = cast<OMPDeclareReductionDecl>(D);
14290 DiscardCleanupsInEvaluationContext();
14291 PopExpressionEvaluationContext();
14292
14293 PopDeclContext();
14294 PopFunctionScopeInfo();
14295
Alexey Bataev070f43a2017-09-06 14:49:58 +000014296 if (Initializer != nullptr) {
14297 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
14298 } else if (OmpPrivParm->hasInit()) {
14299 DRD->setInitializer(OmpPrivParm->getInit(),
14300 OmpPrivParm->isDirectInit()
14301 ? OMPDeclareReductionDecl::DirectInit
14302 : OMPDeclareReductionDecl::CopyInit);
14303 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014304 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000014305 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014306}
14307
14308Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
14309 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014310 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014311 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014312 if (S)
14313 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
14314 /*AddToContext=*/false);
14315 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014316 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014317 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000014318 }
14319 return DeclReductions;
14320}
14321
Michael Kruse251e1482019-02-01 20:25:04 +000014322TypeResult Sema::ActOnOpenMPDeclareMapperVarDecl(Scope *S, Declarator &D) {
14323 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14324 QualType T = TInfo->getType();
14325 if (D.isInvalidType())
14326 return true;
14327
14328 if (getLangOpts().CPlusPlus) {
14329 // Check that there are no default arguments (C++ only).
14330 CheckExtraCXXDefaultArguments(D);
14331 }
14332
14333 return CreateParsedType(T, TInfo);
14334}
14335
14336QualType Sema::ActOnOpenMPDeclareMapperType(SourceLocation TyLoc,
14337 TypeResult ParsedType) {
14338 assert(ParsedType.isUsable() && "Expect usable parsed mapper type");
14339
14340 QualType MapperType = GetTypeFromParser(ParsedType.get());
14341 assert(!MapperType.isNull() && "Expect valid mapper type");
14342
14343 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14344 // The type must be of struct, union or class type in C and C++
14345 if (!MapperType->isStructureOrClassType() && !MapperType->isUnionType()) {
14346 Diag(TyLoc, diag::err_omp_mapper_wrong_type);
14347 return QualType();
14348 }
14349 return MapperType;
14350}
14351
14352OMPDeclareMapperDecl *Sema::ActOnOpenMPDeclareMapperDirectiveStart(
14353 Scope *S, DeclContext *DC, DeclarationName Name, QualType MapperType,
14354 SourceLocation StartLoc, DeclarationName VN, AccessSpecifier AS,
14355 Decl *PrevDeclInScope) {
14356 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPMapperName,
14357 forRedeclarationInCurContext());
14358 // [OpenMP 5.0], 2.19.7.3 declare mapper Directive, Restrictions
14359 // A mapper-identifier may not be redeclared in the current scope for the
14360 // same type or for a type that is compatible according to the base language
14361 // rules.
14362 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
14363 OMPDeclareMapperDecl *PrevDMD = nullptr;
14364 bool InCompoundScope = true;
14365 if (S != nullptr) {
14366 // Find previous declaration with the same name not referenced in other
14367 // declarations.
14368 FunctionScopeInfo *ParentFn = getEnclosingFunction();
14369 InCompoundScope =
14370 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
14371 LookupName(Lookup, S);
14372 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
14373 /*AllowInlineNamespace=*/false);
14374 llvm::DenseMap<OMPDeclareMapperDecl *, bool> UsedAsPrevious;
14375 LookupResult::Filter Filter = Lookup.makeFilter();
14376 while (Filter.hasNext()) {
14377 auto *PrevDecl = cast<OMPDeclareMapperDecl>(Filter.next());
14378 if (InCompoundScope) {
14379 auto I = UsedAsPrevious.find(PrevDecl);
14380 if (I == UsedAsPrevious.end())
14381 UsedAsPrevious[PrevDecl] = false;
14382 if (OMPDeclareMapperDecl *D = PrevDecl->getPrevDeclInScope())
14383 UsedAsPrevious[D] = true;
14384 }
14385 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
14386 PrevDecl->getLocation();
14387 }
14388 Filter.done();
14389 if (InCompoundScope) {
14390 for (const auto &PrevData : UsedAsPrevious) {
14391 if (!PrevData.second) {
14392 PrevDMD = PrevData.first;
14393 break;
14394 }
14395 }
14396 }
14397 } else if (PrevDeclInScope) {
14398 auto *PrevDMDInScope = PrevDMD =
14399 cast<OMPDeclareMapperDecl>(PrevDeclInScope);
14400 do {
14401 PreviousRedeclTypes[PrevDMDInScope->getType().getCanonicalType()] =
14402 PrevDMDInScope->getLocation();
14403 PrevDMDInScope = PrevDMDInScope->getPrevDeclInScope();
14404 } while (PrevDMDInScope != nullptr);
14405 }
14406 const auto I = PreviousRedeclTypes.find(MapperType.getCanonicalType());
14407 bool Invalid = false;
14408 if (I != PreviousRedeclTypes.end()) {
14409 Diag(StartLoc, diag::err_omp_declare_mapper_redefinition)
14410 << MapperType << Name;
14411 Diag(I->second, diag::note_previous_definition);
14412 Invalid = true;
14413 }
14414 auto *DMD = OMPDeclareMapperDecl::Create(Context, DC, StartLoc, Name,
14415 MapperType, VN, PrevDMD);
14416 DC->addDecl(DMD);
14417 DMD->setAccess(AS);
14418 if (Invalid)
14419 DMD->setInvalidDecl();
14420
14421 // Enter new function scope.
14422 PushFunctionScope();
14423 setFunctionHasBranchProtectedScope();
14424
14425 CurContext = DMD;
14426
14427 return DMD;
14428}
14429
14430void Sema::ActOnOpenMPDeclareMapperDirectiveVarDecl(OMPDeclareMapperDecl *DMD,
14431 Scope *S,
14432 QualType MapperType,
14433 SourceLocation StartLoc,
14434 DeclarationName VN) {
14435 VarDecl *VD = buildVarDecl(*this, StartLoc, MapperType, VN.getAsString());
14436 if (S)
14437 PushOnScopeChains(VD, S);
14438 else
14439 DMD->addDecl(VD);
14440 Expr *MapperVarRefExpr = buildDeclRefExpr(*this, VD, MapperType, StartLoc);
14441 DMD->setMapperVarRef(MapperVarRefExpr);
14442}
14443
14444Sema::DeclGroupPtrTy
14445Sema::ActOnOpenMPDeclareMapperDirectiveEnd(OMPDeclareMapperDecl *D, Scope *S,
14446 ArrayRef<OMPClause *> ClauseList) {
14447 PopDeclContext();
14448 PopFunctionScopeInfo();
14449
14450 if (D) {
14451 if (S)
14452 PushOnScopeChains(D, S, /*AddToContext=*/false);
14453 D->CreateClauses(Context, ClauseList);
14454 }
14455
14456 return DeclGroupPtrTy::make(DeclGroupRef(D));
14457}
14458
David Majnemer9d168222016-08-05 17:44:54 +000014459OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000014460 SourceLocation StartLoc,
14461 SourceLocation LParenLoc,
14462 SourceLocation EndLoc) {
14463 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014464 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014465
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014466 // OpenMP [teams Constrcut, Restrictions]
14467 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014468 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000014469 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014470 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000014471
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014472 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014473 OpenMPDirectiveKind CaptureRegion =
14474 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
14475 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014476 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014477 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000014478 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14479 HelperValStmt = buildPreInits(Context, Captures);
14480 }
14481
14482 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
14483 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000014484}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014485
14486OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
14487 SourceLocation StartLoc,
14488 SourceLocation LParenLoc,
14489 SourceLocation EndLoc) {
14490 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014491 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014492
14493 // OpenMP [teams Constrcut, Restrictions]
14494 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000014495 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000014496 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014497 return nullptr;
14498
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014499 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000014500 OpenMPDirectiveKind CaptureRegion =
14501 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
14502 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014503 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014504 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000014505 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14506 HelperValStmt = buildPreInits(Context, Captures);
14507 }
14508
14509 return new (Context) OMPThreadLimitClause(
14510 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000014511}
Alexey Bataeva0569352015-12-01 10:17:31 +000014512
14513OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
14514 SourceLocation StartLoc,
14515 SourceLocation LParenLoc,
14516 SourceLocation EndLoc) {
14517 Expr *ValExpr = Priority;
14518
14519 // OpenMP [2.9.1, task Constrcut]
14520 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014521 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000014522 /*StrictlyPositive=*/false))
14523 return nullptr;
14524
14525 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14526}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014527
14528OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
14529 SourceLocation StartLoc,
14530 SourceLocation LParenLoc,
14531 SourceLocation EndLoc) {
14532 Expr *ValExpr = Grainsize;
14533
14534 // OpenMP [2.9.2, taskloop Constrcut]
14535 // The parameter of the grainsize clause must be a positive integer
14536 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014537 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000014538 /*StrictlyPositive=*/true))
14539 return nullptr;
14540
14541 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14542}
Alexey Bataev382967a2015-12-08 12:06:20 +000014543
14544OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
14545 SourceLocation StartLoc,
14546 SourceLocation LParenLoc,
14547 SourceLocation EndLoc) {
14548 Expr *ValExpr = NumTasks;
14549
14550 // OpenMP [2.9.2, taskloop Constrcut]
14551 // The parameter of the num_tasks clause must be a positive integer
14552 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000014553 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000014554 /*StrictlyPositive=*/true))
14555 return nullptr;
14556
14557 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
14558}
14559
Alexey Bataev28c75412015-12-15 08:19:24 +000014560OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
14561 SourceLocation LParenLoc,
14562 SourceLocation EndLoc) {
14563 // OpenMP [2.13.2, critical construct, Description]
14564 // ... where hint-expression is an integer constant expression that evaluates
14565 // to a valid lock hint.
14566 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
14567 if (HintExpr.isInvalid())
14568 return nullptr;
14569 return new (Context)
14570 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
14571}
14572
Carlo Bertollib4adf552016-01-15 18:50:31 +000014573OMPClause *Sema::ActOnOpenMPDistScheduleClause(
14574 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
14575 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
14576 SourceLocation EndLoc) {
14577 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
14578 std::string Values;
14579 Values += "'";
14580 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
14581 Values += "'";
14582 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
14583 << Values << getOpenMPClauseName(OMPC_dist_schedule);
14584 return nullptr;
14585 }
14586 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000014587 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000014588 if (ChunkSize) {
14589 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
14590 !ChunkSize->isInstantiationDependent() &&
14591 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014592 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000014593 ExprResult Val =
14594 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
14595 if (Val.isInvalid())
14596 return nullptr;
14597
14598 ValExpr = Val.get();
14599
14600 // OpenMP [2.7.1, Restrictions]
14601 // chunk_size must be a loop invariant integer expression with a positive
14602 // value.
14603 llvm::APSInt Result;
14604 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
14605 if (Result.isSigned() && !Result.isStrictlyPositive()) {
14606 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
14607 << "dist_schedule" << ChunkSize->getSourceRange();
14608 return nullptr;
14609 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000014610 } else if (getOpenMPCaptureRegionForClause(
14611 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
14612 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000014613 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000014614 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000014615 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000014616 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
14617 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014618 }
14619 }
14620 }
14621
14622 return new (Context)
14623 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000014624 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000014625}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014626
14627OMPClause *Sema::ActOnOpenMPDefaultmapClause(
14628 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
14629 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
14630 SourceLocation KindLoc, SourceLocation EndLoc) {
14631 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000014632 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014633 std::string Value;
14634 SourceLocation Loc;
14635 Value += "'";
14636 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
14637 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014638 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014639 Loc = MLoc;
14640 } else {
14641 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000014642 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014643 Loc = KindLoc;
14644 }
14645 Value += "'";
14646 Diag(Loc, diag::err_omp_unexpected_clause_value)
14647 << Value << getOpenMPClauseName(OMPC_defaultmap);
14648 return nullptr;
14649 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000014650 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000014651
14652 return new (Context)
14653 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
14654}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014655
14656bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
14657 DeclContext *CurLexicalContext = getCurLexicalContext();
14658 if (!CurLexicalContext->isFileContext() &&
14659 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000014660 !CurLexicalContext->isExternCXXContext() &&
14661 !isa<CXXRecordDecl>(CurLexicalContext) &&
14662 !isa<ClassTemplateDecl>(CurLexicalContext) &&
14663 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
14664 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014665 Diag(Loc, diag::err_omp_region_not_file_context);
14666 return false;
14667 }
Kelvin Libc38e632018-09-10 02:07:09 +000014668 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014669 return true;
14670}
14671
14672void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000014673 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014674 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000014675 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014676}
14677
David Majnemer9d168222016-08-05 17:44:54 +000014678void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
14679 CXXScopeSpec &ScopeSpec,
14680 const DeclarationNameInfo &Id,
14681 OMPDeclareTargetDeclAttr::MapTypeTy MT,
14682 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014683 LookupResult Lookup(*this, Id, LookupOrdinaryName);
14684 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
14685
14686 if (Lookup.isAmbiguous())
14687 return;
14688 Lookup.suppressDiagnostics();
14689
14690 if (!Lookup.isSingleResult()) {
Bruno Ricci70ad3962019-03-25 17:08:51 +000014691 VarOrFuncDeclFilterCCC CCC(*this);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014692 if (TypoCorrection Corrected =
Bruno Ricci70ad3962019-03-25 17:08:51 +000014693 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr, CCC,
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014694 CTK_ErrorRecovery)) {
14695 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
14696 << Id.getName());
14697 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
14698 return;
14699 }
14700
14701 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
14702 return;
14703 }
14704
14705 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev30a78212018-09-11 13:59:10 +000014706 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
14707 isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014708 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
14709 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
Alexey Bataev30a78212018-09-11 13:59:10 +000014710 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14711 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
14712 cast<ValueDecl>(ND));
14713 if (!Res) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014714 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014715 ND->addAttr(A);
14716 if (ASTMutationListener *ML = Context.getASTMutationListener())
14717 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000014718 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Alexey Bataev30a78212018-09-11 13:59:10 +000014719 } else if (*Res != MT) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014720 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
14721 << Id.getName();
14722 }
Alexey Bataeve3727102018-04-18 15:57:46 +000014723 } else {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014724 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataeve3727102018-04-18 15:57:46 +000014725 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000014726}
14727
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014728static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
14729 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014730 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014731 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000014732 auto *VD = cast<VarDecl>(D);
14733 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
14734 return;
14735 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
14736 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014737}
14738
14739static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
14740 Sema &SemaRef, DSAStackTy *Stack,
14741 ValueDecl *VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000014742 return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
14743 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
14744 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014745}
14746
Kelvin Li1ce87c72017-12-12 20:08:12 +000014747void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
14748 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014749 if (!D || D->isInvalidDecl())
14750 return;
14751 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000014752 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000014753 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000014754 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000014755 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
14756 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000014757 return;
14758 // 2.10.6: threadprivate variable cannot appear in a declare target
14759 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014760 if (DSAStack->isThreadPrivate(VD)) {
14761 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000014762 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014763 return;
14764 }
14765 }
Alexey Bataev97b72212018-08-14 18:31:20 +000014766 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
14767 D = FTD->getTemplatedDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000014768 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000014769 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
14770 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
14771 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000014772 assert(IdLoc.isValid() && "Source location is expected");
14773 Diag(IdLoc, diag::err_omp_function_in_link_clause);
14774 Diag(FD->getLocation(), diag::note_defined_here) << FD;
14775 return;
14776 }
14777 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014778 if (auto *VD = dyn_cast<ValueDecl>(D)) {
14779 // Problem if any with var declared with incomplete type will be reported
14780 // as normal, so no need to check it here.
14781 if ((E || !VD->getType()->isIncompleteType()) &&
14782 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
14783 return;
14784 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
14785 // Checking declaration inside declare target region.
14786 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
14787 isa<FunctionTemplateDecl>(D)) {
14788 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
14789 Context, OMPDeclareTargetDeclAttr::MT_To);
14790 D->addAttr(A);
14791 if (ASTMutationListener *ML = Context.getASTMutationListener())
14792 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
14793 }
14794 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014795 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014796 }
Alexey Bataev30a78212018-09-11 13:59:10 +000014797 if (!E)
14798 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000014799 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
14800}
Samuel Antao661c0902016-05-26 17:39:58 +000014801
14802OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
Michael Kruse01f670d2019-02-22 22:29:42 +000014803 CXXScopeSpec &MapperIdScopeSpec,
14804 DeclarationNameInfo &MapperId,
14805 const OMPVarListLocTy &Locs,
14806 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antao661c0902016-05-26 17:39:58 +000014807 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014808 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, Locs.StartLoc,
14809 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antao661c0902016-05-26 17:39:58 +000014810 if (MVLI.ProcessedVarList.empty())
14811 return nullptr;
14812
Michael Kruse01f670d2019-02-22 22:29:42 +000014813 return OMPToClause::Create(
14814 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14815 MVLI.VarComponents, MVLI.UDMapperList,
14816 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antao661c0902016-05-26 17:39:58 +000014817}
Samuel Antaoec172c62016-05-26 17:49:04 +000014818
14819OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
Michael Kruse0336c752019-02-25 20:34:15 +000014820 CXXScopeSpec &MapperIdScopeSpec,
14821 DeclarationNameInfo &MapperId,
14822 const OMPVarListLocTy &Locs,
14823 ArrayRef<Expr *> UnresolvedMappers) {
Samuel Antaoec172c62016-05-26 17:49:04 +000014824 MappableVarListInfo MVLI(VarList);
Michael Kruse01f670d2019-02-22 22:29:42 +000014825 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, Locs.StartLoc,
14826 MapperIdScopeSpec, MapperId, UnresolvedMappers);
Samuel Antaoec172c62016-05-26 17:49:04 +000014827 if (MVLI.ProcessedVarList.empty())
14828 return nullptr;
14829
Michael Kruse0336c752019-02-25 20:34:15 +000014830 return OMPFromClause::Create(
14831 Context, Locs, MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
14832 MVLI.VarComponents, MVLI.UDMapperList,
14833 MapperIdScopeSpec.getWithLocInContext(Context), MapperId);
Samuel Antaoec172c62016-05-26 17:49:04 +000014834}
Carlo Bertolli2404b172016-07-13 15:37:16 +000014835
14836OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014837 const OMPVarListLocTy &Locs) {
Samuel Antaocc10b852016-07-28 14:23:26 +000014838 MappableVarListInfo MVLI(VarList);
14839 SmallVector<Expr *, 8> PrivateCopies;
14840 SmallVector<Expr *, 8> Inits;
14841
Alexey Bataeve3727102018-04-18 15:57:46 +000014842 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014843 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
14844 SourceLocation ELoc;
14845 SourceRange ERange;
14846 Expr *SimpleRefExpr = RefExpr;
14847 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14848 if (Res.second) {
14849 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000014850 MVLI.ProcessedVarList.push_back(RefExpr);
14851 PrivateCopies.push_back(nullptr);
14852 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014853 }
14854 ValueDecl *D = Res.first;
14855 if (!D)
14856 continue;
14857
14858 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000014859 Type = Type.getNonReferenceType().getUnqualifiedType();
14860
14861 auto *VD = dyn_cast<VarDecl>(D);
14862
14863 // Item should be a pointer or reference to pointer.
14864 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000014865 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
14866 << 0 << RefExpr->getSourceRange();
14867 continue;
14868 }
Samuel Antaocc10b852016-07-28 14:23:26 +000014869
14870 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000014871 auto VDPrivate =
14872 buildVarDecl(*this, ELoc, Type, D->getName(),
14873 D->hasAttrs() ? &D->getAttrs() : nullptr,
14874 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000014875 if (VDPrivate->isInvalidDecl())
14876 continue;
14877
14878 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000014879 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000014880 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
14881
14882 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000014883 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000014884 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000014885 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
14886 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000014887 AddInitializerToDecl(VDPrivate,
14888 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000014889 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000014890
14891 // If required, build a capture to implement the privatization initialized
14892 // with the current list item value.
14893 DeclRefExpr *Ref = nullptr;
14894 if (!VD)
14895 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
14896 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
14897 PrivateCopies.push_back(VDPrivateRefExpr);
14898 Inits.push_back(VDInitRefExpr);
14899
14900 // We need to add a data sharing attribute for this variable to make sure it
14901 // is correctly captured. A variable that shows up in a use_device_ptr has
14902 // similar properties of a first private variable.
14903 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
14904
14905 // Create a mappable component for the list item. List items in this clause
14906 // only need a component.
14907 MVLI.VarBaseDeclarations.push_back(D);
14908 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14909 MVLI.VarComponents.back().push_back(
14910 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000014911 }
14912
Samuel Antaocc10b852016-07-28 14:23:26 +000014913 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000014914 return nullptr;
14915
Samuel Antaocc10b852016-07-28 14:23:26 +000014916 return OMPUseDevicePtrClause::Create(
Michael Kruse4304e9d2019-02-19 16:38:20 +000014917 Context, Locs, MVLI.ProcessedVarList, PrivateCopies, Inits,
14918 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000014919}
Carlo Bertolli70594e92016-07-13 17:16:49 +000014920
14921OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
Michael Kruse4304e9d2019-02-19 16:38:20 +000014922 const OMPVarListLocTy &Locs) {
Samuel Antao6890b092016-07-28 14:25:09 +000014923 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000014924 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000014925 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000014926 SourceLocation ELoc;
14927 SourceRange ERange;
14928 Expr *SimpleRefExpr = RefExpr;
14929 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
14930 if (Res.second) {
14931 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000014932 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014933 }
14934 ValueDecl *D = Res.first;
14935 if (!D)
14936 continue;
14937
14938 QualType Type = D->getType();
14939 // item should be a pointer or array or reference to pointer or array
14940 if (!Type.getNonReferenceType()->isPointerType() &&
14941 !Type.getNonReferenceType()->isArrayType()) {
14942 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
14943 << 0 << RefExpr->getSourceRange();
14944 continue;
14945 }
Samuel Antao6890b092016-07-28 14:25:09 +000014946
14947 // Check if the declaration in the clause does not show up in any data
14948 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000014949 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000014950 if (isOpenMPPrivate(DVar.CKind)) {
14951 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
14952 << getOpenMPClauseName(DVar.CKind)
14953 << getOpenMPClauseName(OMPC_is_device_ptr)
14954 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000014955 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000014956 continue;
14957 }
14958
Alexey Bataeve3727102018-04-18 15:57:46 +000014959 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000014960 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000014961 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000014962 [&ConflictExpr](
14963 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
14964 OpenMPClauseKind) -> bool {
14965 ConflictExpr = R.front().getAssociatedExpression();
14966 return true;
14967 })) {
14968 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
14969 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
14970 << ConflictExpr->getSourceRange();
14971 continue;
14972 }
14973
14974 // Store the components in the stack so that they can be used to check
14975 // against other clauses later on.
14976 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
14977 DSAStack->addMappableExpressionComponents(
14978 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
14979
14980 // Record the expression we've just processed.
14981 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
14982
14983 // Create a mappable component for the list item. List items in this clause
14984 // only need a component. We use a null declaration to signal fields in
14985 // 'this'.
14986 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
14987 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
14988 "Unexpected device pointer expression!");
14989 MVLI.VarBaseDeclarations.push_back(
14990 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
14991 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
14992 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000014993 }
14994
Samuel Antao6890b092016-07-28 14:25:09 +000014995 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000014996 return nullptr;
14997
Michael Kruse4304e9d2019-02-19 16:38:20 +000014998 return OMPIsDevicePtrClause::Create(Context, Locs, MVLI.ProcessedVarList,
14999 MVLI.VarBaseDeclarations,
15000 MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000015001}
Alexey Bataeve04483e2019-03-27 14:14:31 +000015002
15003OMPClause *Sema::ActOnOpenMPAllocateClause(
15004 Expr *Allocator, ArrayRef<Expr *> VarList, SourceLocation StartLoc,
15005 SourceLocation ColonLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
15006 if (Allocator) {
15007 // OpenMP [2.11.4 allocate Clause, Description]
15008 // allocator is an expression of omp_allocator_handle_t type.
15009 if (!findOMPAllocatorHandleT(*this, Allocator->getExprLoc(), DSAStack))
15010 return nullptr;
15011
15012 ExprResult AllocatorRes = DefaultLvalueConversion(Allocator);
15013 if (AllocatorRes.isInvalid())
15014 return nullptr;
15015 AllocatorRes = PerformImplicitConversion(AllocatorRes.get(),
15016 DSAStack->getOMPAllocatorHandleT(),
15017 Sema::AA_Initializing,
15018 /*AllowExplicit=*/true);
15019 if (AllocatorRes.isInvalid())
15020 return nullptr;
15021 Allocator = AllocatorRes.get();
Alexey Bataev84c8bae2019-04-01 16:56:59 +000015022 } else {
15023 // OpenMP 5.0, 2.11.4 allocate Clause, Restrictions.
15024 // allocate clauses that appear on a target construct or on constructs in a
15025 // target region must specify an allocator expression unless a requires
15026 // directive with the dynamic_allocators clause is present in the same
15027 // compilation unit.
15028 if (LangOpts.OpenMPIsDevice &&
15029 !DSAStack->hasRequiresDeclWithClause<OMPDynamicAllocatorsClause>())
15030 targetDiag(StartLoc, diag::err_expected_allocator_expression);
Alexey Bataeve04483e2019-03-27 14:14:31 +000015031 }
15032 // Analyze and build list of variables.
15033 SmallVector<Expr *, 8> Vars;
15034 for (Expr *RefExpr : VarList) {
15035 assert(RefExpr && "NULL expr in OpenMP private clause.");
15036 SourceLocation ELoc;
15037 SourceRange ERange;
15038 Expr *SimpleRefExpr = RefExpr;
15039 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
15040 if (Res.second) {
15041 // It will be analyzed later.
15042 Vars.push_back(RefExpr);
15043 }
15044 ValueDecl *D = Res.first;
15045 if (!D)
15046 continue;
15047
15048 auto *VD = dyn_cast<VarDecl>(D);
15049 DeclRefExpr *Ref = nullptr;
15050 if (!VD && !CurContext->isDependentContext())
15051 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
15052 Vars.push_back((VD || CurContext->isDependentContext())
15053 ? RefExpr->IgnoreParens()
15054 : Ref);
15055 }
15056
15057 if (Vars.empty())
15058 return nullptr;
15059
15060 return OMPAllocateClause::Create(Context, StartLoc, LParenLoc, Allocator,
15061 ColonLoc, EndLoc, Vars);
15062}