blob: 0a46543c3a5bf20f565b2cc572c6b58c1a37738d [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;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +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 Bataeved09d242014-05-28 05:53:51 +0000150 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000151 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000152 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
153 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000154 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000155 };
156
Alexey Bataeve3727102018-04-18 15:57:46 +0000157 using StackTy = SmallVector<SharingMapTy, 4>;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000158
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000159 /// Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000160 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000161 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
162 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000163 /// true, if check for DSA must be from parent directive, false, if
Alexey Bataev39f915b82015-05-08 10:41:21 +0000164 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000165 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000166 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000167 bool ForceCapturing = false;
Alexey Bataev60705422018-10-30 15:50:12 +0000168 /// true if all the vaiables in the target executable directives must be
169 /// captured by reference.
170 bool ForceCaptureByReferenceInTargetExecutable = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000171 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000172
Alexey Bataeve3727102018-04-18 15:57:46 +0000173 using iterator = StackTy::const_reverse_iterator;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000174
Alexey Bataeve3727102018-04-18 15:57:46 +0000175 DSAVarData getDSA(iterator &Iter, ValueDecl *D) const;
Alexey Bataevec3da872014-01-31 05:15:34 +0000176
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000177 /// Checks if the variable is a local for OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000178 bool isOpenMPLocal(VarDecl *D, iterator Iter) const;
Alexey Bataeved09d242014-05-28 05:53:51 +0000179
Alexey Bataev4b465392017-04-26 15:06:24 +0000180 bool isStackEmpty() const {
181 return Stack.empty() ||
182 Stack.back().second != CurrentNonCapturingFunctionScope ||
183 Stack.back().first.empty();
184 }
185
Kelvin Li1408f912018-09-26 04:28:39 +0000186 /// Vector of previously declared requires directives
187 SmallVector<const OMPRequiresDecl *, 2> RequiresDecls;
188
Alexey Bataev758e55e2013-09-06 18:03:48 +0000189public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000190 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000191
Alexey Bataevaac108a2015-06-23 04:51:00 +0000192 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000193 OpenMPClauseKind getClauseParsingMode() const {
194 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
195 return ClauseKindMode;
196 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000197 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000198
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000199 bool isForceVarCapturing() const { return ForceCapturing; }
200 void setForceVarCapturing(bool V) { ForceCapturing = V; }
201
Alexey Bataev60705422018-10-30 15:50:12 +0000202 void setForceCaptureByReferenceInTargetExecutable(bool V) {
203 ForceCaptureByReferenceInTargetExecutable = V;
204 }
205 bool isForceCaptureByReferenceInTargetExecutable() const {
206 return ForceCaptureByReferenceInTargetExecutable;
207 }
208
Alexey Bataev758e55e2013-09-06 18:03:48 +0000209 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000210 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000211 if (Stack.empty() ||
212 Stack.back().second != CurrentNonCapturingFunctionScope)
213 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
214 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
215 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000216 }
217
218 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000219 assert(!Stack.back().first.empty() &&
220 "Data-sharing attributes stack is empty!");
221 Stack.back().first.pop_back();
222 }
223
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000224 /// Marks that we're started loop parsing.
225 void loopInit() {
226 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
227 "Expected loop-based directive.");
228 Stack.back().first.back().LoopStart = true;
229 }
230 /// Start capturing of the variables in the loop context.
231 void loopStart() {
232 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
233 "Expected loop-based directive.");
234 Stack.back().first.back().LoopStart = false;
235 }
236 /// true, if variables are captured, false otherwise.
237 bool isLoopStarted() const {
238 assert(isOpenMPLoopDirective(getCurrentDirective()) &&
239 "Expected loop-based directive.");
240 return !Stack.back().first.back().LoopStart;
241 }
242 /// Marks (or clears) declaration as possibly loop counter.
243 void resetPossibleLoopCounter(const Decl *D = nullptr) {
244 Stack.back().first.back().PossiblyLoopCounter =
245 D ? D->getCanonicalDecl() : D;
246 }
247 /// Gets the possible loop counter decl.
248 const Decl *getPossiblyLoopCunter() const {
249 return Stack.back().first.back().PossiblyLoopCounter;
250 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000251 /// Start new OpenMP region stack in new non-capturing function.
252 void pushFunction() {
253 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
254 assert(!isa<CapturingScopeInfo>(CurFnScope));
255 CurrentNonCapturingFunctionScope = CurFnScope;
256 }
257 /// Pop region stack for non-capturing function.
258 void popFunction(const FunctionScopeInfo *OldFSI) {
259 if (!Stack.empty() && Stack.back().second == OldFSI) {
260 assert(Stack.back().first.empty());
261 Stack.pop_back();
262 }
263 CurrentNonCapturingFunctionScope = nullptr;
264 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
265 if (!isa<CapturingScopeInfo>(FSI)) {
266 CurrentNonCapturingFunctionScope = FSI;
267 break;
268 }
269 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000270 }
271
Alexey Bataeve3727102018-04-18 15:57:46 +0000272 void addCriticalWithHint(const OMPCriticalDirective *D, llvm::APSInt Hint) {
Alexey Bataev43a919f2018-04-13 17:48:43 +0000273 Criticals.try_emplace(D->getDirectiveName().getAsString(), D, Hint);
Alexey Bataev28c75412015-12-15 08:19:24 +0000274 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000275 const std::pair<const OMPCriticalDirective *, llvm::APSInt>
Alexey Bataev28c75412015-12-15 08:19:24 +0000276 getCriticalWithHint(const DeclarationNameInfo &Name) const {
277 auto I = Criticals.find(Name.getAsString());
278 if (I != Criticals.end())
279 return I->second;
280 return std::make_pair(nullptr, llvm::APSInt());
281 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000282 /// If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000283 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000284 /// for diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +0000285 const Expr *addUniqueAligned(const ValueDecl *D, const Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000286
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000287 /// Register specified variable as loop control variable.
Alexey Bataeve3727102018-04-18 15:57:46 +0000288 void addLoopControlVariable(const ValueDecl *D, VarDecl *Capture);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000289 /// Check if the specified variable is a loop control variable for
Alexey Bataev9c821032015-04-30 04:23:23 +0000290 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000291 /// \return The index of the loop control variable in the list of associated
292 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000293 const LCDeclInfo isLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000294 /// Check if the specified variable is a loop control variable for
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000295 /// parent region.
296 /// \return The index of the loop control variable in the list of associated
297 /// for-loops (from outer to inner).
Alexey Bataeve3727102018-04-18 15:57:46 +0000298 const LCDeclInfo isParentLoopControlVariable(const ValueDecl *D) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000299 /// Get the loop control variable for the I-th loop (or nullptr) in
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000300 /// parent directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000301 const ValueDecl *getParentLoopControlVariable(unsigned I) const;
Alexey Bataev9c821032015-04-30 04:23:23 +0000302
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000303 /// Adds explicit data sharing attribute to the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000304 void addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000305 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000306
Alexey Bataevfa312f32017-07-21 18:48:21 +0000307 /// Adds additional information for the reduction items with the reduction id
308 /// represented as an operator.
Alexey Bataeve3727102018-04-18 15:57:46 +0000309 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000310 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000311 /// Adds additional information for the reduction items with the reduction id
312 /// represented as reduction identifier.
Alexey Bataeve3727102018-04-18 15:57:46 +0000313 void addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000314 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000315 /// Returns the location and reduction operation from the innermost parent
316 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000317 const DSAVarData
318 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
319 BinaryOperatorKind &BOK,
320 Expr *&TaskgroupDescriptor) const;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000321 /// Returns the location and reduction operation from the innermost parent
322 /// region for the given \p D.
Alexey Bataeve3727102018-04-18 15:57:46 +0000323 const DSAVarData
324 getTopMostTaskgroupReductionData(const ValueDecl *D, SourceRange &SR,
325 const Expr *&ReductionRef,
326 Expr *&TaskgroupDescriptor) const;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000327 /// Return reduction reference expression for the current taskgroup.
328 Expr *getTaskgroupReductionRef() const {
329 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
330 "taskgroup reference expression requested for non taskgroup "
331 "directive.");
332 return Stack.back().first.back().TaskgroupReductionRef;
333 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000334 /// Checks if the given \p VD declaration is actually a taskgroup reduction
335 /// descriptor variable at the \p Level of OpenMP regions.
Alexey Bataeve3727102018-04-18 15:57:46 +0000336 bool isTaskgroupReductionRef(const ValueDecl *VD, unsigned Level) const {
Alexey Bataev88202be2017-07-27 13:20:36 +0000337 return Stack.back().first[Level].TaskgroupReductionRef &&
338 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
339 ->getDecl() == VD;
340 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000341
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000342 /// Returns data sharing attributes from top of the stack for the
Alexey Bataev758e55e2013-09-06 18:03:48 +0000343 /// specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000344 const DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000345 /// Returns data-sharing attributes for the specified declaration.
Alexey Bataeve3727102018-04-18 15:57:46 +0000346 const DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000347 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000348 /// match specified \a CPred predicate in any directive which matches \a DPred
349 /// predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000350 const DSAVarData
351 hasDSA(ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
352 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
353 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000354 /// Checks if the specified variables has data-sharing attributes which
Alexey Bataevf29276e2014-06-18 04:14:57 +0000355 /// match specified \a CPred predicate in any innermost directive which
356 /// matches \a DPred predicate.
Alexey Bataeve3727102018-04-18 15:57:46 +0000357 const DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000358 hasInnermostDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000359 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
360 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000361 bool FromParent) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000362 /// Checks if the specified variables has explicit data-sharing
Alexey Bataevaac108a2015-06-23 04:51:00 +0000363 /// attributes which match specified \a CPred predicate at the specified
364 /// OpenMP region.
Alexey Bataeve3727102018-04-18 15:57:46 +0000365 bool hasExplicitDSA(const ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000366 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000367 unsigned Level, bool NotLastprivate = false) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000368
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000369 /// Returns true if the directive at level \Level matches in the
Samuel Antao4be30e92015-10-02 17:14:03 +0000370 /// specified \a DPred predicate.
371 bool hasExplicitDirective(
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000372 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000373 unsigned Level) const;
Samuel Antao4be30e92015-10-02 17:14:03 +0000374
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000375 /// Finds a directive which matches specified \a DPred predicate.
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000376 bool hasDirective(
377 const llvm::function_ref<bool(
378 OpenMPDirectiveKind, const DeclarationNameInfo &, SourceLocation)>
379 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +0000380 bool FromParent) const;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000381
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000382 /// Returns currently analyzed directive.
Alexey Bataev758e55e2013-09-06 18:03:48 +0000383 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000384 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000385 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000386 /// Returns directive kind at specified level.
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000387 OpenMPDirectiveKind getDirective(unsigned Level) const {
388 assert(!isStackEmpty() && "No directive at specified level.");
389 return Stack.back().first[Level].Directive;
390 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000391 /// Returns parent directive.
Alexey Bataev549210e2014-06-24 04:39:47 +0000392 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000393 if (isStackEmpty() || Stack.back().first.size() == 1)
394 return OMPD_unknown;
395 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000396 }
Alexey Bataev6ab5bb12018-10-29 15:01:58 +0000397
Kelvin Li1408f912018-09-26 04:28:39 +0000398 /// Add requires decl to internal vector
399 void addRequiresDecl(OMPRequiresDecl *RD) {
400 RequiresDecls.push_back(RD);
401 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000402
Kelvin Li1408f912018-09-26 04:28:39 +0000403 /// Checks for a duplicate clause amongst previously declared requires
404 /// directives
405 bool hasDuplicateRequiresClause(ArrayRef<OMPClause *> ClauseList) const {
406 bool IsDuplicate = false;
407 for (OMPClause *CNew : ClauseList) {
408 for (const OMPRequiresDecl *D : RequiresDecls) {
409 for (const OMPClause *CPrev : D->clauselists()) {
410 if (CNew->getClauseKind() == CPrev->getClauseKind()) {
411 SemaRef.Diag(CNew->getBeginLoc(),
412 diag::err_omp_requires_clause_redeclaration)
413 << getOpenMPClauseName(CNew->getClauseKind());
414 SemaRef.Diag(CPrev->getBeginLoc(),
415 diag::note_omp_requires_previous_clause)
416 << getOpenMPClauseName(CPrev->getClauseKind());
417 IsDuplicate = true;
418 }
419 }
420 }
421 }
422 return IsDuplicate;
423 }
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +0000424
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000425 /// Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000426 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000427 assert(!isStackEmpty());
428 Stack.back().first.back().DefaultAttr = DSA_none;
429 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000430 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000431 /// Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000432 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000433 assert(!isStackEmpty());
434 Stack.back().first.back().DefaultAttr = DSA_shared;
435 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000436 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000437 /// Set default data mapping attribute to 'tofrom:scalar'.
438 void setDefaultDMAToFromScalar(SourceLocation Loc) {
439 assert(!isStackEmpty());
440 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
441 Stack.back().first.back().DefaultMapAttrLoc = Loc;
442 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000443
444 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000445 return isStackEmpty() ? DSA_unspecified
446 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000447 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000448 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000449 return isStackEmpty() ? SourceLocation()
450 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000451 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000452 DefaultMapAttributes getDefaultDMA() const {
453 return isStackEmpty() ? DMA_unspecified
454 : Stack.back().first.back().DefaultMapAttr;
455 }
456 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
457 return Stack.back().first[Level].DefaultMapAttr;
458 }
459 SourceLocation getDefaultDMALocation() const {
460 return isStackEmpty() ? SourceLocation()
461 : Stack.back().first.back().DefaultMapAttrLoc;
462 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000463
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000464 /// Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000465 bool isThreadPrivate(VarDecl *D) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000466 const DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000467 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000468 }
469
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000470 /// Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataevf138fda2018-08-13 19:04:24 +0000471 void setOrderedRegion(bool IsOrdered, const Expr *Param,
472 OMPOrderedClause *Clause) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000473 assert(!isStackEmpty());
Alexey Bataevf138fda2018-08-13 19:04:24 +0000474 if (IsOrdered)
475 Stack.back().first.back().OrderedRegion.emplace(Param, Clause);
476 else
477 Stack.back().first.back().OrderedRegion.reset();
478 }
479 /// Returns true, if region is ordered (has associated 'ordered' clause),
480 /// false - otherwise.
481 bool isOrderedRegion() const {
482 if (isStackEmpty())
483 return false;
484 return Stack.back().first.rbegin()->OrderedRegion.hasValue();
485 }
486 /// Returns optional parameter for the ordered region.
487 std::pair<const Expr *, OMPOrderedClause *> getOrderedRegionParam() const {
488 if (isStackEmpty() ||
489 !Stack.back().first.rbegin()->OrderedRegion.hasValue())
490 return std::make_pair(nullptr, nullptr);
491 return Stack.back().first.rbegin()->OrderedRegion.getValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000492 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000493 /// Returns true, if parent region is ordered (has associated
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000494 /// 'ordered' clause), false - otherwise.
495 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000496 if (isStackEmpty() || Stack.back().first.size() == 1)
497 return false;
Alexey Bataevf138fda2018-08-13 19:04:24 +0000498 return std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000499 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000500 /// Returns optional parameter for the ordered region.
Alexey Bataevf138fda2018-08-13 19:04:24 +0000501 std::pair<const Expr *, OMPOrderedClause *>
502 getParentOrderedRegionParam() const {
503 if (isStackEmpty() || Stack.back().first.size() == 1 ||
504 !std::next(Stack.back().first.rbegin())->OrderedRegion.hasValue())
505 return std::make_pair(nullptr, nullptr);
506 return std::next(Stack.back().first.rbegin())->OrderedRegion.getValue();
Alexey Bataev346265e2015-09-25 10:37:12 +0000507 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000508 /// Marks current region as nowait (it has a 'nowait' clause).
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000509 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000510 assert(!isStackEmpty());
511 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000512 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000513 /// Returns true, if parent region is nowait (has associated
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000514 /// 'nowait' clause), false - otherwise.
515 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000516 if (isStackEmpty() || Stack.back().first.size() == 1)
517 return false;
518 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000519 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000520 /// Marks parent region as cancel region.
Alexey Bataev25e5b442015-09-15 12:52:43 +0000521 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000522 if (!isStackEmpty() && Stack.back().first.size() > 1) {
523 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
524 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
525 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000526 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000527 /// Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000528 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000529 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000530 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000531
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000532 /// Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000533 void setAssociatedLoops(unsigned Val) {
534 assert(!isStackEmpty());
535 Stack.back().first.back().AssociatedLoops = Val;
536 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000537 /// Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000538 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000539 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000540 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000541
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000542 /// Marks current target region as one with closely nested teams
Alexey Bataev13314bf2014-10-09 04:18:56 +0000543 /// region.
544 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000545 if (!isStackEmpty() && Stack.back().first.size() > 1) {
546 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
547 TeamsRegionLoc;
548 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000549 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000550 /// Returns true, if current region has closely nested teams region.
Alexey Bataev13314bf2014-10-09 04:18:56 +0000551 bool hasInnerTeamsRegion() const {
552 return getInnerTeamsRegionLoc().isValid();
553 }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000554 /// Returns location of the nested teams region (if any).
Alexey Bataev13314bf2014-10-09 04:18:56 +0000555 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000556 return isStackEmpty() ? SourceLocation()
557 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000558 }
559
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000560 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000561 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000562 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000563 SourceLocation getConstructLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000564 return isStackEmpty() ? SourceLocation()
565 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000566 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000567
Samuel Antao4c8035b2016-12-12 18:00:20 +0000568 /// Do the check specified in \a Check to all component lists and return true
569 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000570 bool checkMappableExprComponentListsForDecl(
Alexey Bataeve3727102018-04-18 15:57:46 +0000571 const ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000572 const llvm::function_ref<
573 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000574 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000575 Check) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000576 if (isStackEmpty())
577 return false;
578 auto SI = Stack.back().first.rbegin();
579 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000580
581 if (SI == SE)
582 return false;
583
Alexey Bataeve3727102018-04-18 15:57:46 +0000584 if (CurrentRegionOnly)
Samuel Antao5de996e2016-01-22 20:21:36 +0000585 SE = std::next(SI);
Alexey Bataeve3727102018-04-18 15:57:46 +0000586 else
587 std::advance(SI, 1);
Samuel Antao5de996e2016-01-22 20:21:36 +0000588
589 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000590 auto MI = SI->MappedExprComponents.find(VD);
591 if (MI != SI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000592 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
593 MI->second.Components)
Samuel Antao6890b092016-07-28 14:25:09 +0000594 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000595 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000596 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000597 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000598 }
599
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000600 /// Do the check specified in \a Check to all component lists at a given level
601 /// and return true if any issue is found.
602 bool checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +0000603 const ValueDecl *VD, unsigned Level,
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000604 const llvm::function_ref<
605 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
Alexey Bataev97d18bf2018-04-11 19:21:00 +0000606 OpenMPClauseKind)>
Alexey Bataeve3727102018-04-18 15:57:46 +0000607 Check) const {
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000608 if (isStackEmpty())
609 return false;
610
611 auto StartI = Stack.back().first.begin();
612 auto EndI = Stack.back().first.end();
613 if (std::distance(StartI, EndI) <= (int)Level)
614 return false;
615 std::advance(StartI, Level);
616
617 auto MI = StartI->MappedExprComponents.find(VD);
618 if (MI != StartI->MappedExprComponents.end())
Alexey Bataeve3727102018-04-18 15:57:46 +0000619 for (OMPClauseMappableExprCommon::MappableExprComponentListRef L :
620 MI->second.Components)
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000621 if (Check(L, MI->second.Kind))
622 return true;
623 return false;
624 }
625
Samuel Antao4c8035b2016-12-12 18:00:20 +0000626 /// Create a new mappable expression component list associated with a given
627 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000628 void addMappableExpressionComponents(
Alexey Bataeve3727102018-04-18 15:57:46 +0000629 const ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000630 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
631 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000632 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000633 "Not expecting to retrieve components from a empty stack!");
Alexey Bataeve3727102018-04-18 15:57:46 +0000634 MappedExprComponentTy &MEC =
635 Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000636 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000637 MEC.Components.resize(MEC.Components.size() + 1);
638 MEC.Components.back().append(Components.begin(), Components.end());
639 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000640 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000641
642 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000643 assert(!isStackEmpty());
644 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000645 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000646 void addDoacrossDependClause(OMPDependClause *C,
647 const OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000648 assert(!isStackEmpty() && Stack.back().first.size() > 1);
Alexey Bataeve3727102018-04-18 15:57:46 +0000649 SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000650 assert(isOpenMPWorksharingDirective(StackElem.Directive));
Alexey Bataeve3727102018-04-18 15:57:46 +0000651 StackElem.DoacrossDepends.try_emplace(C, OpsOffs);
Alexey Bataev8b427062016-05-25 12:36:08 +0000652 }
653 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
654 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000655 assert(!isStackEmpty());
Alexey Bataeve3727102018-04-18 15:57:46 +0000656 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000657 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000658 const DoacrossDependMapTy &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000659 return llvm::make_range(Ref.begin(), Ref.end());
660 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000661 return llvm::make_range(StackElem.DoacrossDepends.end(),
662 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000663 }
Patrick Lystere13b1e32019-01-02 19:28:48 +0000664
665 // Store types of classes which have been explicitly mapped
666 void addMappedClassesQualTypes(QualType QT) {
667 SharingMapTy &StackElem = Stack.back().first.back();
668 StackElem.MappedClassesQualTypes.insert(QT);
669 }
670
671 // Return set of mapped classes types
672 bool isClassPreviouslyMapped(QualType QT) const {
673 const SharingMapTy &StackElem = Stack.back().first.back();
674 return StackElem.MappedClassesQualTypes.count(QT) != 0;
675 }
676
Alexey Bataev758e55e2013-09-06 18:03:48 +0000677};
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000678
679bool isImplicitTaskingRegion(OpenMPDirectiveKind DKind) {
680 return isOpenMPParallelDirective(DKind) || isOpenMPTeamsDirective(DKind);
681}
682
683bool isImplicitOrExplicitTaskingRegion(OpenMPDirectiveKind DKind) {
684 return isImplicitTaskingRegion(DKind) || isOpenMPTaskingDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000685}
Alexey Bataeve3727102018-04-18 15:57:46 +0000686
Alexey Bataeved09d242014-05-28 05:53:51 +0000687} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000688
Alexey Bataeve3727102018-04-18 15:57:46 +0000689static const Expr *getExprAsWritten(const Expr *E) {
Bill Wendling7c44da22018-10-31 03:48:47 +0000690 if (const auto *FE = dyn_cast<FullExpr>(E))
691 E = FE->getSubExpr();
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000692
Alexey Bataeve3727102018-04-18 15:57:46 +0000693 if (const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000694 E = MTE->GetTemporaryExpr();
695
Alexey Bataeve3727102018-04-18 15:57:46 +0000696 while (const auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000697 E = Binder->getSubExpr();
698
Alexey Bataeve3727102018-04-18 15:57:46 +0000699 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000700 E = ICE->getSubExprAsWritten();
701 return E->IgnoreParens();
702}
703
Alexey Bataeve3727102018-04-18 15:57:46 +0000704static Expr *getExprAsWritten(Expr *E) {
705 return const_cast<Expr *>(getExprAsWritten(const_cast<const Expr *>(E)));
706}
707
708static const ValueDecl *getCanonicalDecl(const ValueDecl *D) {
709 if (const auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
710 if (const auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000711 D = ME->getMemberDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +0000712 const auto *VD = dyn_cast<VarDecl>(D);
713 const auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000714 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000715 VD = VD->getCanonicalDecl();
716 D = VD;
717 } else {
718 assert(FD);
719 FD = FD->getCanonicalDecl();
720 D = FD;
721 }
722 return D;
723}
724
Alexey Bataeve3727102018-04-18 15:57:46 +0000725static ValueDecl *getCanonicalDecl(ValueDecl *D) {
726 return const_cast<ValueDecl *>(
727 getCanonicalDecl(const_cast<const ValueDecl *>(D)));
728}
729
730DSAStackTy::DSAVarData DSAStackTy::getDSA(iterator &Iter,
731 ValueDecl *D) const {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000732 D = getCanonicalDecl(D);
733 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000734 const auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000735 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000736 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000737 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
738 // in a region but not in construct]
739 // File-scope or namespace-scope variables referenced in called routines
740 // in the region are shared unless they appear in a threadprivate
741 // directive.
Alexey Bataeve3727102018-04-18 15:57:46 +0000742 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(VD))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000743 DVar.CKind = OMPC_shared;
744
745 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
746 // in a region but not in construct]
747 // Variables with static storage duration that are declared in called
748 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000749 if (VD && VD->hasGlobalStorage())
750 DVar.CKind = OMPC_shared;
751
752 // Non-static data members are shared by default.
753 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000754 DVar.CKind = OMPC_shared;
755
Alexey Bataev758e55e2013-09-06 18:03:48 +0000756 return DVar;
757 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000758
Alexey Bataevec3da872014-01-31 05:15:34 +0000759 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
760 // in a Construct, C/C++, predetermined, p.1]
761 // Variables with automatic storage duration that are declared in a scope
762 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000763 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
764 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000765 DVar.CKind = OMPC_private;
766 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000767 }
768
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000769 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000770 // Explicitly specified attributes and local variables with predetermined
771 // attributes.
772 if (Iter->SharingMap.count(D)) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000773 const DSAInfo &Data = Iter->SharingMap.lookup(D);
774 DVar.RefExpr = Data.RefExpr.getPointer();
775 DVar.PrivateCopy = Data.PrivateCopy;
776 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000777 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000778 return DVar;
779 }
780
781 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
782 // in a Construct, C/C++, implicitly determined, p.1]
783 // In a parallel or task construct, the data-sharing attributes of these
784 // variables are determined by the default clause, if present.
785 switch (Iter->DefaultAttr) {
786 case DSA_shared:
787 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000788 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000789 return DVar;
790 case DSA_none:
791 return DVar;
792 case DSA_unspecified:
793 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
794 // in a Construct, implicitly determined, p.2]
795 // In a parallel construct, if no default clause is present, these
796 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000797 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000798 if (isOpenMPParallelDirective(DVar.DKind) ||
799 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000800 DVar.CKind = OMPC_shared;
801 return DVar;
802 }
803
804 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
805 // in a Construct, implicitly determined, p.4]
806 // In a task construct, if no default clause is present, a variable that in
807 // the enclosing context is determined to be shared by all implicit tasks
808 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000809 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000810 DSAVarData DVarTemp;
Alexey Bataeve3727102018-04-18 15:57:46 +0000811 iterator I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000812 do {
813 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000814 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000815 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000816 // In a task construct, if no default clause is present, a variable
817 // whose data-sharing attribute is not determined by the rules above is
818 // firstprivate.
819 DVarTemp = getDSA(I, D);
820 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000821 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000822 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000823 return DVar;
824 }
Alexey Bataev7e6803e2019-01-09 15:58:05 +0000825 } while (I != E && !isImplicitTaskingRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000826 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000827 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000828 return DVar;
829 }
830 }
831 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
832 // in a Construct, implicitly determined, p.3]
833 // For constructs other than task, if no default clause is present, these
834 // variables inherit their data-sharing attributes from the enclosing
835 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000836 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000837}
838
Alexey Bataeve3727102018-04-18 15:57:46 +0000839const Expr *DSAStackTy::addUniqueAligned(const ValueDecl *D,
840 const Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000841 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000842 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000843 SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000844 auto It = StackElem.AlignedMap.find(D);
845 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000846 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000847 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000848 return nullptr;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000849 }
Alexey Bataeve3727102018-04-18 15:57:46 +0000850 assert(It->second && "Unexpected nullptr expr in the aligned map");
851 return It->second;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000852}
853
Alexey Bataeve3727102018-04-18 15:57:46 +0000854void DSAStackTy::addLoopControlVariable(const ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000855 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000856 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000857 SharingMapTy &StackElem = Stack.back().first.back();
858 StackElem.LCVMap.try_emplace(
859 D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture));
Alexey Bataev9c821032015-04-30 04:23:23 +0000860}
861
Alexey Bataeve3727102018-04-18 15:57:46 +0000862const DSAStackTy::LCDeclInfo
863DSAStackTy::isLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000864 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000865 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000866 const SharingMapTy &StackElem = Stack.back().first.back();
Alexey Bataev4b465392017-04-26 15:06:24 +0000867 auto It = StackElem.LCVMap.find(D);
868 if (It != StackElem.LCVMap.end())
869 return It->second;
870 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000871}
872
Alexey Bataeve3727102018-04-18 15:57:46 +0000873const DSAStackTy::LCDeclInfo
874DSAStackTy::isParentLoopControlVariable(const ValueDecl *D) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000875 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
876 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000877 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +0000878 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000879 auto It = StackElem.LCVMap.find(D);
880 if (It != StackElem.LCVMap.end())
881 return It->second;
882 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000883}
884
Alexey Bataeve3727102018-04-18 15:57:46 +0000885const ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000886 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
887 "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000888 const SharingMapTy &StackElem = *std::next(Stack.back().first.rbegin());
Alexey Bataev4b465392017-04-26 15:06:24 +0000889 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000890 return nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +0000891 for (const auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000892 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000893 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000894 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000895}
896
Alexey Bataeve3727102018-04-18 15:57:46 +0000897void DSAStackTy::addDSA(const ValueDecl *D, const Expr *E, OpenMPClauseKind A,
Alexey Bataev90c228f2016-02-08 09:29:13 +0000898 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000899 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000900 if (A == OMPC_threadprivate) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000901 DSAInfo &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000902 Data.Attributes = A;
903 Data.RefExpr.setPointer(E);
904 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000905 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000906 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataeve3727102018-04-18 15:57:46 +0000907 DSAInfo &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000908 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
909 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
910 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
911 (isLoopControlVariable(D).first && A == OMPC_private));
912 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
913 Data.RefExpr.setInt(/*IntVal=*/true);
914 return;
915 }
916 const bool IsLastprivate =
917 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
918 Data.Attributes = A;
919 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
920 Data.PrivateCopy = PrivateCopy;
921 if (PrivateCopy) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000922 DSAInfo &Data =
923 Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000924 Data.Attributes = A;
925 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
926 Data.PrivateCopy = nullptr;
927 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000928 }
929}
930
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000931/// Build a variable declaration for OpenMP loop iteration variable.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000932static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000933 StringRef Name, const AttrVec *Attrs = nullptr,
934 DeclRefExpr *OrigRef = nullptr) {
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000935 DeclContext *DC = SemaRef.CurContext;
936 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
937 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
Alexey Bataeve3727102018-04-18 15:57:46 +0000938 auto *Decl =
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000939 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
940 if (Attrs) {
941 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
942 I != E; ++I)
943 Decl->addAttr(*I);
944 }
945 Decl->setImplicit();
Alexey Bataev63cc8e92018-03-20 14:45:59 +0000946 if (OrigRef) {
947 Decl->addAttr(
948 OMPReferencedVarAttr::CreateImplicit(SemaRef.Context, OrigRef));
949 }
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000950 return Decl;
951}
952
953static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
954 SourceLocation Loc,
955 bool RefersToCapture = false) {
956 D->setReferenced();
957 D->markUsed(S.Context);
958 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
959 SourceLocation(), D, RefersToCapture, Loc, Ty,
960 VK_LValue);
961}
962
Alexey Bataeve3727102018-04-18 15:57:46 +0000963void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000964 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000965 D = getCanonicalDecl(D);
966 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000967 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000968 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000969 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +0000970 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +0000971 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000972 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000973 "Additional reduction info may be specified only once for reduction "
974 "items.");
975 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000976 Expr *&TaskgroupReductionRef =
977 Stack.back().first.back().TaskgroupReductionRef;
978 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +0000979 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
980 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +0000981 TaskgroupReductionRef =
982 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000983 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000984}
985
Alexey Bataeve3727102018-04-18 15:57:46 +0000986void DSAStackTy::addTaskgroupReductionData(const ValueDecl *D, SourceRange SR,
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000987 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000988 D = getCanonicalDecl(D);
989 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000990 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000991 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000992 "Additional reduction info may be specified only for reduction items.");
Alexey Bataeve3727102018-04-18 15:57:46 +0000993 ReductionData &ReductionData = Stack.back().first.back().ReductionMap[D];
Alexey Bataevfa312f32017-07-21 18:48:21 +0000994 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000995 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000996 "Additional reduction info may be specified only once for reduction "
997 "items.");
998 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000999 Expr *&TaskgroupReductionRef =
1000 Stack.back().first.back().TaskgroupReductionRef;
1001 if (!TaskgroupReductionRef) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001002 VarDecl *VD = buildVarDecl(SemaRef, SR.getBegin(),
1003 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +00001004 TaskgroupReductionRef =
1005 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +00001006 }
Alexey Bataevfa312f32017-07-21 18:48:21 +00001007}
1008
Alexey Bataeve3727102018-04-18 15:57:46 +00001009const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1010 const ValueDecl *D, SourceRange &SR, BinaryOperatorKind &BOK,
1011 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001012 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001013 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1014 if (Stack.back().first.empty())
1015 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001016 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1017 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001018 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001019 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001020 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001021 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001022 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001023 if (!ReductionData.ReductionOp ||
1024 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001025 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001026 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +00001027 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001028 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1029 "expression for the descriptor is not "
1030 "set.");
1031 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001032 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1033 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001034 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001035 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001036}
1037
Alexey Bataeve3727102018-04-18 15:57:46 +00001038const DSAStackTy::DSAVarData DSAStackTy::getTopMostTaskgroupReductionData(
1039 const ValueDecl *D, SourceRange &SR, const Expr *&ReductionRef,
1040 Expr *&TaskgroupDescriptor) const {
Alexey Bataevfa312f32017-07-21 18:48:21 +00001041 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001042 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
1043 if (Stack.back().first.empty())
1044 return DSAVarData();
Alexey Bataeve3727102018-04-18 15:57:46 +00001045 for (iterator I = std::next(Stack.back().first.rbegin(), 1),
1046 E = Stack.back().first.rend();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001047 I != E; std::advance(I, 1)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001048 const DSAInfo &Data = I->SharingMap.lookup(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +00001049 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +00001050 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001051 const ReductionData &ReductionData = I->ReductionMap.lookup(D);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001052 if (!ReductionData.ReductionOp ||
1053 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +00001054 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001055 SR = ReductionData.ReductionRange;
1056 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +00001057 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
1058 "expression for the descriptor is not "
1059 "set.");
1060 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +00001061 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
1062 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +00001063 }
Alexey Bataevf189cb72017-07-24 14:52:13 +00001064 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +00001065}
1066
Alexey Bataeve3727102018-04-18 15:57:46 +00001067bool DSAStackTy::isOpenMPLocal(VarDecl *D, iterator Iter) const {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001068 D = D->getCanonicalDecl();
Alexey Bataev852525d2018-03-02 17:17:12 +00001069 if (!isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001070 iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001071 Scope *TopScope = nullptr;
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001072 while (I != E && !isImplicitOrExplicitTaskingRegion(I->Directive) &&
Alexey Bataev852525d2018-03-02 17:17:12 +00001073 !isOpenMPTargetExecutionDirective(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +00001074 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +00001075 if (I == E)
1076 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001077 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001078 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001079 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +00001080 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +00001081 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001082 }
Alexey Bataevec3da872014-01-31 05:15:34 +00001083 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001084}
1085
Joel E. Dennyd2649292019-01-04 22:11:56 +00001086static bool isConstNotMutableType(Sema &SemaRef, QualType Type,
1087 bool AcceptIfMutable = true,
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001088 bool *IsClassType = nullptr) {
1089 ASTContext &Context = SemaRef.getASTContext();
Joel E. Dennyd2649292019-01-04 22:11:56 +00001090 Type = Type.getNonReferenceType().getCanonicalType();
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001091 bool IsConstant = Type.isConstant(Context);
1092 Type = Context.getBaseElementType(Type);
Joel E. Dennyd2649292019-01-04 22:11:56 +00001093 const CXXRecordDecl *RD = AcceptIfMutable && SemaRef.getLangOpts().CPlusPlus
1094 ? Type->getAsCXXRecordDecl()
1095 : nullptr;
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001096 if (const auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1097 if (const ClassTemplateDecl *CTD = CTSD->getSpecializedTemplate())
1098 RD = CTD->getTemplatedDecl();
1099 if (IsClassType)
1100 *IsClassType = RD;
1101 return IsConstant && !(SemaRef.getLangOpts().CPlusPlus && RD &&
1102 RD->hasDefinition() && RD->hasMutableFields());
1103}
1104
Joel E. Dennyd2649292019-01-04 22:11:56 +00001105static bool rejectConstNotMutableType(Sema &SemaRef, const ValueDecl *D,
1106 QualType Type, OpenMPClauseKind CKind,
1107 SourceLocation ELoc,
1108 bool AcceptIfMutable = true,
1109 bool ListItemNotVar = false) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001110 ASTContext &Context = SemaRef.getASTContext();
1111 bool IsClassType;
Joel E. Dennyd2649292019-01-04 22:11:56 +00001112 if (isConstNotMutableType(SemaRef, Type, AcceptIfMutable, &IsClassType)) {
1113 unsigned Diag = ListItemNotVar
1114 ? diag::err_omp_const_list_item
1115 : IsClassType ? diag::err_omp_const_not_mutable_variable
1116 : diag::err_omp_const_variable;
1117 SemaRef.Diag(ELoc, Diag) << getOpenMPClauseName(CKind);
1118 if (!ListItemNotVar && D) {
1119 const VarDecl *VD = dyn_cast<VarDecl>(D);
1120 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
1121 VarDecl::DeclarationOnly;
1122 SemaRef.Diag(D->getLocation(),
1123 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1124 << D;
1125 }
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001126 return true;
1127 }
1128 return false;
1129}
1130
Alexey Bataeve3727102018-04-18 15:57:46 +00001131const DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D,
1132 bool FromParent) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001133 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001134 DSAVarData DVar;
1135
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001136 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001137 auto TI = Threadprivates.find(D);
1138 if (TI != Threadprivates.end()) {
1139 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001140 DVar.CKind = OMPC_threadprivate;
1141 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001142 }
1143 if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
Alexey Bataev817d7f32017-11-14 21:01:01 +00001144 DVar.RefExpr = buildDeclRefExpr(
1145 SemaRef, VD, D->getType().getNonReferenceType(),
1146 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
1147 DVar.CKind = OMPC_threadprivate;
1148 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +00001149 return DVar;
1150 }
1151 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1152 // in a Construct, C/C++, predetermined, p.1]
1153 // Variables appearing in threadprivate directives are threadprivate.
1154 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
1155 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1156 SemaRef.getLangOpts().OpenMPUseTLS &&
1157 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
1158 (VD && VD->getStorageClass() == SC_Register &&
1159 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
1160 DVar.RefExpr = buildDeclRefExpr(
1161 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
1162 DVar.CKind = OMPC_threadprivate;
1163 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
1164 return DVar;
1165 }
1166 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
1167 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
1168 !isLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001169 iterator IterTarget =
Alexey Bataev852525d2018-03-02 17:17:12 +00001170 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
1171 [](const SharingMapTy &Data) {
1172 return isOpenMPTargetExecutionDirective(Data.Directive);
1173 });
1174 if (IterTarget != Stack.back().first.rend()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001175 iterator ParentIterTarget = std::next(IterTarget, 1);
1176 for (iterator Iter = Stack.back().first.rbegin();
1177 Iter != ParentIterTarget; std::advance(Iter, 1)) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001178 if (isOpenMPLocal(VD, Iter)) {
1179 DVar.RefExpr =
1180 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1181 D->getLocation());
1182 DVar.CKind = OMPC_threadprivate;
1183 return DVar;
1184 }
Alexey Bataev852525d2018-03-02 17:17:12 +00001185 }
1186 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1187 auto DSAIter = IterTarget->SharingMap.find(D);
1188 if (DSAIter != IterTarget->SharingMap.end() &&
1189 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1190 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1191 DVar.CKind = OMPC_threadprivate;
1192 return DVar;
Alexey Bataeve3727102018-04-18 15:57:46 +00001193 }
1194 iterator End = Stack.back().first.rend();
1195 if (!SemaRef.isOpenMPCapturedByRef(
1196 D, std::distance(ParentIterTarget, End))) {
Alexey Bataev852525d2018-03-02 17:17:12 +00001197 DVar.RefExpr =
1198 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1199 IterTarget->ConstructLoc);
1200 DVar.CKind = OMPC_threadprivate;
1201 return DVar;
1202 }
1203 }
1204 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001205 }
1206
Alexey Bataev4b465392017-04-26 15:06:24 +00001207 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001208 // Not in OpenMP execution region and top scope was already checked.
1209 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001210
Alexey Bataev758e55e2013-09-06 18:03:48 +00001211 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001212 // in a Construct, C/C++, predetermined, p.4]
1213 // Static data members are shared.
1214 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1215 // in a Construct, C/C++, predetermined, p.7]
1216 // Variables with static storage duration that are declared in a scope
1217 // inside the construct are shared.
Alexey Bataeve3727102018-04-18 15:57:46 +00001218 auto &&MatchesAlways = [](OpenMPDirectiveKind) { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001219 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001220 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001221 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +00001222 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001223
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001224 DVar.CKind = OMPC_shared;
1225 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001226 }
1227
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001228 // The predetermined shared attribute for const-qualified types having no
1229 // mutable members was removed after OpenMP 3.1.
1230 if (SemaRef.LangOpts.OpenMP <= 31) {
1231 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1232 // in a Construct, C/C++, predetermined, p.6]
1233 // Variables with const qualified type having no mutable member are
1234 // shared.
Joel E. Dennyd2649292019-01-04 22:11:56 +00001235 if (isConstNotMutableType(SemaRef, D->getType())) {
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001236 // Variables with const-qualified type having no mutable member may be
1237 // listed in a firstprivate clause, even if they are static data members.
1238 DSAVarData DVarTemp = hasInnermostDSA(
1239 D,
1240 [](OpenMPClauseKind C) {
1241 return C == OMPC_firstprivate || C == OMPC_shared;
1242 },
1243 MatchesAlways, FromParent);
1244 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
1245 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001246
Joel E. Dennye6234d1422019-01-04 22:11:31 +00001247 DVar.CKind = OMPC_shared;
1248 return DVar;
1249 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001250 }
1251
Alexey Bataev758e55e2013-09-06 18:03:48 +00001252 // Explicitly specified attributes and local variables with predetermined
1253 // attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +00001254 iterator I = Stack.back().first.rbegin();
1255 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001256 if (FromParent && I != EndI)
1257 std::advance(I, 1);
Alexey Bataeve3727102018-04-18 15:57:46 +00001258 auto It = I->SharingMap.find(D);
1259 if (It != I->SharingMap.end()) {
1260 const DSAInfo &Data = It->getSecond();
1261 DVar.RefExpr = Data.RefExpr.getPointer();
1262 DVar.PrivateCopy = Data.PrivateCopy;
1263 DVar.CKind = Data.Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001264 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001265 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001266 }
1267
1268 return DVar;
1269}
1270
Alexey Bataeve3727102018-04-18 15:57:46 +00001271const DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1272 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001273 if (isStackEmpty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00001274 iterator I;
Alexey Bataev4b465392017-04-26 15:06:24 +00001275 return getDSA(I, D);
1276 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001277 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001278 iterator StartI = Stack.back().first.rbegin();
1279 iterator EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001280 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001281 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001282 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001283}
1284
Alexey Bataeve3727102018-04-18 15:57:46 +00001285const DSAStackTy::DSAVarData
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001286DSAStackTy::hasDSA(ValueDecl *D,
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001287 const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1288 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001289 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001290 if (isStackEmpty())
1291 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001292 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001293 iterator I = Stack.back().first.rbegin();
1294 iterator EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001295 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001296 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001297 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001298 if (!DPred(I->Directive) && !isImplicitOrExplicitTaskingRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001299 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00001300 iterator NewI = I;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001301 DSAVarData DVar = getDSA(NewI, D);
1302 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001303 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001304 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001305 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001306}
1307
Alexey Bataeve3727102018-04-18 15:57:46 +00001308const DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001309 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1310 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001311 bool FromParent) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001312 if (isStackEmpty())
1313 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001314 D = getCanonicalDecl(D);
Alexey Bataeve3727102018-04-18 15:57:46 +00001315 iterator StartI = Stack.back().first.rbegin();
1316 iterator EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001317 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001318 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001319 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001320 return {};
Alexey Bataeve3727102018-04-18 15:57:46 +00001321 iterator NewI = StartI;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001322 DSAVarData DVar = getDSA(NewI, D);
1323 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001324}
1325
Alexey Bataevaac108a2015-06-23 04:51:00 +00001326bool DSAStackTy::hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001327 const ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> CPred,
1328 unsigned Level, bool NotLastprivate) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001329 if (isStackEmpty())
1330 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001331 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001332 auto StartI = Stack.back().first.begin();
1333 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001334 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001335 return false;
1336 std::advance(StartI, Level);
Alexey Bataeve3727102018-04-18 15:57:46 +00001337 auto I = StartI->SharingMap.find(D);
Alexey Bataev92b33652018-11-21 19:41:10 +00001338 if ((I != StartI->SharingMap.end()) &&
Alexey Bataeve3727102018-04-18 15:57:46 +00001339 I->getSecond().RefExpr.getPointer() &&
1340 CPred(I->getSecond().Attributes) &&
Alexey Bataev92b33652018-11-21 19:41:10 +00001341 (!NotLastprivate || !I->getSecond().RefExpr.getInt()))
1342 return true;
1343 // Check predetermined rules for the loop control variables.
1344 auto LI = StartI->LCVMap.find(D);
1345 if (LI != StartI->LCVMap.end())
1346 return CPred(OMPC_private);
1347 return false;
Alexey Bataevaac108a2015-06-23 04:51:00 +00001348}
1349
Samuel Antao4be30e92015-10-02 17:14:03 +00001350bool DSAStackTy::hasExplicitDirective(
Alexey Bataeve3727102018-04-18 15:57:46 +00001351 const llvm::function_ref<bool(OpenMPDirectiveKind)> DPred,
1352 unsigned Level) const {
Alexey Bataev4b465392017-04-26 15:06:24 +00001353 if (isStackEmpty())
1354 return false;
1355 auto StartI = Stack.back().first.begin();
1356 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001357 if (std::distance(StartI, EndI) <= (int)Level)
1358 return false;
1359 std::advance(StartI, Level);
1360 return DPred(StartI->Directive);
1361}
1362
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001363bool DSAStackTy::hasDirective(
1364 const llvm::function_ref<bool(OpenMPDirectiveKind,
1365 const DeclarationNameInfo &, SourceLocation)>
Alexey Bataev97d18bf2018-04-11 19:21:00 +00001366 DPred,
Alexey Bataeve3727102018-04-18 15:57:46 +00001367 bool FromParent) const {
Samuel Antaof0d79752016-05-27 15:21:27 +00001368 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001369 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001370 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001371 auto StartI = std::next(Stack.back().first.rbegin());
1372 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001373 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001374 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001375 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1376 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1377 return true;
1378 }
1379 return false;
1380}
1381
Alexey Bataev758e55e2013-09-06 18:03:48 +00001382void Sema::InitDataSharingAttributesStack() {
1383 VarDataSharingAttributesStack = new DSAStackTy(*this);
1384}
1385
1386#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1387
Alexey Bataev4b465392017-04-26 15:06:24 +00001388void Sema::pushOpenMPFunctionRegion() {
1389 DSAStack->pushFunction();
1390}
1391
1392void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1393 DSAStack->popFunction(OldFSI);
1394}
1395
Alexey Bataeve3727102018-04-18 15:57:46 +00001396bool Sema::isOpenMPCapturedByRef(const ValueDecl *D, unsigned Level) const {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001397 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1398
Alexey Bataeve3727102018-04-18 15:57:46 +00001399 ASTContext &Ctx = getASTContext();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001400 bool IsByRef = true;
1401
1402 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001403 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001404 QualType Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001405
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001406 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001407 // This table summarizes how a given variable should be passed to the device
1408 // given its type and the clauses where it appears. This table is based on
1409 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1410 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1411 //
1412 // =========================================================================
1413 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1414 // | |(tofrom:scalar)| | pvt | | | |
1415 // =========================================================================
1416 // | scl | | | | - | | bycopy|
1417 // | scl | | - | x | - | - | bycopy|
1418 // | scl | | x | - | - | - | null |
1419 // | scl | x | | | - | | byref |
1420 // | scl | x | - | x | - | - | bycopy|
1421 // | scl | x | x | - | - | - | null |
1422 // | scl | | - | - | - | x | byref |
1423 // | scl | x | - | - | - | x | byref |
1424 //
1425 // | agg | n.a. | | | - | | byref |
1426 // | agg | n.a. | - | x | - | - | byref |
1427 // | agg | n.a. | x | - | - | - | null |
1428 // | agg | n.a. | - | - | - | x | byref |
1429 // | agg | n.a. | - | - | - | x[] | byref |
1430 //
1431 // | ptr | n.a. | | | - | | bycopy|
1432 // | ptr | n.a. | - | x | - | - | bycopy|
1433 // | ptr | n.a. | x | - | - | - | null |
1434 // | ptr | n.a. | - | - | - | x | byref |
1435 // | ptr | n.a. | - | - | - | x[] | bycopy|
1436 // | ptr | n.a. | - | - | x | | bycopy|
1437 // | ptr | n.a. | - | - | x | x | bycopy|
1438 // | ptr | n.a. | - | - | x | x[] | bycopy|
1439 // =========================================================================
1440 // Legend:
1441 // scl - scalar
1442 // ptr - pointer
1443 // agg - aggregate
1444 // x - applies
1445 // - - invalid in this combination
1446 // [] - mapped with an array section
1447 // byref - should be mapped by reference
1448 // byval - should be mapped by value
1449 // null - initialize a local variable to null on the device
1450 //
1451 // Observations:
1452 // - All scalar declarations that show up in a map clause have to be passed
1453 // by reference, because they may have been mapped in the enclosing data
1454 // environment.
1455 // - If the scalar value does not fit the size of uintptr, it has to be
1456 // passed by reference, regardless the result in the table above.
1457 // - For pointers mapped by value that have either an implicit map or an
1458 // array section, the runtime library may pass the NULL value to the
1459 // device instead of the value passed to it by the compiler.
1460
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001461 if (Ty->isReferenceType())
1462 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001463
1464 // Locate map clauses and see if the variable being captured is referred to
1465 // in any of those clauses. Here we only care about variables, not fields,
1466 // because fields are part of aggregates.
1467 bool IsVariableUsedInMapClause = false;
1468 bool IsVariableAssociatedWithSection = false;
1469
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001470 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
Alexey Bataeve3727102018-04-18 15:57:46 +00001471 D, Level,
1472 [&IsVariableUsedInMapClause, &IsVariableAssociatedWithSection, D](
1473 OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001474 MapExprComponents,
1475 OpenMPClauseKind WhereFoundClauseKind) {
1476 // Only the map clause information influences how a variable is
1477 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001478 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001479 if (WhereFoundClauseKind != OMPC_map)
1480 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001481
1482 auto EI = MapExprComponents.rbegin();
1483 auto EE = MapExprComponents.rend();
1484
1485 assert(EI != EE && "Invalid map expression!");
1486
1487 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1488 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1489
1490 ++EI;
1491 if (EI == EE)
1492 return false;
1493
1494 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1495 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1496 isa<MemberExpr>(EI->getAssociatedExpression())) {
1497 IsVariableAssociatedWithSection = true;
1498 // There is nothing more we need to know about this variable.
1499 return true;
1500 }
1501
1502 // Keep looking for more map info.
1503 return false;
1504 });
1505
1506 if (IsVariableUsedInMapClause) {
1507 // If variable is identified in a map clause it is always captured by
1508 // reference except if it is a pointer that is dereferenced somehow.
1509 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1510 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001511 // By default, all the data that has a scalar type is mapped by copy
1512 // (except for reduction variables).
1513 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001514 (DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1515 !Ty->isAnyPointerType()) ||
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001516 !Ty->isScalarType() ||
1517 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1518 DSAStack->hasExplicitDSA(
1519 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001520 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001521 }
1522
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001523 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001524 IsByRef =
Alexey Bataev60705422018-10-30 15:50:12 +00001525 ((DSAStack->isForceCaptureByReferenceInTargetExecutable() &&
1526 !Ty->isAnyPointerType()) ||
1527 !DSAStack->hasExplicitDSA(
1528 D,
1529 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1530 Level, /*NotLastprivate=*/true)) &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001531 // If the variable is artificial and must be captured by value - try to
1532 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001533 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1534 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001535 }
1536
Samuel Antao86ace552016-04-27 22:40:57 +00001537 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001538 // and alignment, because the runtime library only deals with uintptr types.
1539 // If it does not fit the uintptr size, we need to pass the data by reference
1540 // instead.
1541 if (!IsByRef &&
1542 (Ctx.getTypeSizeInChars(Ty) >
1543 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001544 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001545 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001546 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001547
1548 return IsByRef;
1549}
1550
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001551unsigned Sema::getOpenMPNestingLevel() const {
1552 assert(getLangOpts().OpenMP);
1553 return DSAStack->getNestingLevel();
1554}
1555
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001556bool Sema::isInOpenMPTargetExecutionDirective() const {
1557 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1558 !DSAStack->isClauseParsingMode()) ||
1559 DSAStack->hasDirective(
1560 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1561 SourceLocation) -> bool {
1562 return isOpenMPTargetExecutionDirective(K);
1563 },
1564 false);
1565}
1566
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001567VarDecl *Sema::isOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001568 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001569 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001570
1571 // If we are attempting to capture a global variable in a directive with
1572 // 'target' we return true so that this global is also mapped to the device.
1573 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001574 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001575 if (VD && !VD->hasLocalStorage()) {
1576 if (isInOpenMPDeclareTargetContext() &&
1577 (getCurCapturedRegion() || getCurBlock() || getCurLambda())) {
1578 // Try to mark variable as declare target if it is used in capturing
1579 // regions.
Alexey Bataev97b72212018-08-14 18:31:20 +00001580 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001581 checkDeclIsAllowedInOpenMPTarget(nullptr, VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00001582 return nullptr;
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001583 } else if (isInOpenMPTargetExecutionDirective()) {
1584 // If the declaration is enclosed in a 'declare target' directive,
1585 // then it should not be captured.
1586 //
Alexey Bataev97b72212018-08-14 18:31:20 +00001587 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
Alexey Bataevbf8fe712018-08-07 16:14:36 +00001588 return nullptr;
1589 return VD;
1590 }
Alexey Bataev4f4bf7c2018-03-15 15:47:20 +00001591 }
Alexey Bataev60705422018-10-30 15:50:12 +00001592 // Capture variables captured by reference in lambdas for target-based
1593 // directives.
1594 if (VD && !DSAStack->isClauseParsingMode()) {
1595 if (const auto *RD = VD->getType()
1596 .getCanonicalType()
1597 .getNonReferenceType()
1598 ->getAsCXXRecordDecl()) {
1599 bool SavedForceCaptureByReferenceInTargetExecutable =
1600 DSAStack->isForceCaptureByReferenceInTargetExecutable();
1601 DSAStack->setForceCaptureByReferenceInTargetExecutable(/*V=*/true);
Alexey Bataevd1840e52018-11-16 21:13:33 +00001602 if (RD->isLambda()) {
1603 llvm::DenseMap<const VarDecl *, FieldDecl *> Captures;
1604 FieldDecl *ThisCapture;
1605 RD->getCaptureFields(Captures, ThisCapture);
Alexey Bataev60705422018-10-30 15:50:12 +00001606 for (const LambdaCapture &LC : RD->captures()) {
1607 if (LC.getCaptureKind() == LCK_ByRef) {
1608 VarDecl *VD = LC.getCapturedVar();
1609 DeclContext *VDC = VD->getDeclContext();
1610 if (!VDC->Encloses(CurContext))
1611 continue;
1612 DSAStackTy::DSAVarData DVarPrivate =
1613 DSAStack->getTopDSA(VD, /*FromParent=*/false);
1614 // Do not capture already captured variables.
1615 if (!OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD) &&
1616 DVarPrivate.CKind == OMPC_unknown &&
1617 !DSAStack->checkMappableExprComponentListsForDecl(
1618 D, /*CurrentRegionOnly=*/true,
1619 [](OMPClauseMappableExprCommon::
1620 MappableExprComponentListRef,
1621 OpenMPClauseKind) { return true; }))
1622 MarkVariableReferenced(LC.getLocation(), LC.getCapturedVar());
1623 } else if (LC.getCaptureKind() == LCK_This) {
Alexey Bataevd1840e52018-11-16 21:13:33 +00001624 QualType ThisTy = getCurrentThisType();
1625 if (!ThisTy.isNull() &&
1626 Context.typesAreCompatible(ThisTy, ThisCapture->getType()))
1627 CheckCXXThisCapture(LC.getLocation());
Alexey Bataev60705422018-10-30 15:50:12 +00001628 }
1629 }
Alexey Bataevd1840e52018-11-16 21:13:33 +00001630 }
Alexey Bataev60705422018-10-30 15:50:12 +00001631 DSAStack->setForceCaptureByReferenceInTargetExecutable(
1632 SavedForceCaptureByReferenceInTargetExecutable);
1633 }
1634 }
Samuel Antao4be30e92015-10-02 17:14:03 +00001635
Alexey Bataev48977c32015-08-04 08:10:48 +00001636 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1637 (!DSAStack->isClauseParsingMode() ||
1638 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001639 auto &&Info = DSAStack->isLoopControlVariable(D);
1640 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001641 (VD && VD->hasLocalStorage() &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00001642 isImplicitOrExplicitTaskingRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001643 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001644 return VD ? VD : Info.second;
Alexey Bataeve3727102018-04-18 15:57:46 +00001645 DSAStackTy::DSAVarData DVarPrivate =
1646 DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001647 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001648 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00001649 DVarPrivate = DSAStack->hasDSA(D, isOpenMPPrivate,
1650 [](OpenMPDirectiveKind) { return true; },
1651 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001652 if (DVarPrivate.CKind != OMPC_unknown)
1653 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001654 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001655 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001656}
1657
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001658void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1659 unsigned Level) const {
1660 SmallVector<OpenMPDirectiveKind, 4> Regions;
1661 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1662 FunctionScopesIndex -= Regions.size();
1663}
1664
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001665void Sema::startOpenMPLoop() {
1666 assert(LangOpts.OpenMP && "OpenMP must be enabled.");
1667 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective()))
1668 DSAStack->loopInit();
1669}
1670
Alexey Bataeve3727102018-04-18 15:57:46 +00001671bool Sema::isOpenMPPrivateDecl(const ValueDecl *D, unsigned Level) const {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001672 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00001673 if (isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
1674 if (DSAStack->getAssociatedLoops() > 0 &&
1675 !DSAStack->isLoopStarted()) {
1676 DSAStack->resetPossibleLoopCounter(D);
1677 DSAStack->loopStart();
1678 return true;
1679 }
1680 if ((DSAStack->getPossiblyLoopCunter() == D->getCanonicalDecl() ||
1681 DSAStack->isLoopControlVariable(D).first) &&
1682 !DSAStack->hasExplicitDSA(
1683 D, [](OpenMPClauseKind K) { return K != OMPC_private; }, Level) &&
1684 !isOpenMPSimdDirective(DSAStack->getCurrentDirective()))
1685 return true;
1686 }
Alexey Bataevaac108a2015-06-23 04:51:00 +00001687 return DSAStack->hasExplicitDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00001688 D, [](OpenMPClauseKind K) { return K == OMPC_private; }, Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001689 (DSAStack->isClauseParsingMode() &&
1690 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001691 // Consider taskgroup reduction descriptor variable a private to avoid
1692 // possible capture in the region.
1693 (DSAStack->hasExplicitDirective(
1694 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1695 Level) &&
1696 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001697}
1698
Alexey Bataeve3727102018-04-18 15:57:46 +00001699void Sema::setOpenMPCaptureKind(FieldDecl *FD, const ValueDecl *D,
1700 unsigned Level) {
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001701 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1702 D = getCanonicalDecl(D);
1703 OpenMPClauseKind OMPC = OMPC_unknown;
1704 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1705 const unsigned NewLevel = I - 1;
1706 if (DSAStack->hasExplicitDSA(D,
1707 [&OMPC](const OpenMPClauseKind K) {
1708 if (isOpenMPPrivate(K)) {
1709 OMPC = K;
1710 return true;
1711 }
1712 return false;
1713 },
1714 NewLevel))
1715 break;
1716 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1717 D, NewLevel,
1718 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1719 OpenMPClauseKind) { return true; })) {
1720 OMPC = OMPC_map;
1721 break;
1722 }
1723 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1724 NewLevel)) {
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001725 OMPC = OMPC_map;
1726 if (D->getType()->isScalarType() &&
1727 DSAStack->getDefaultDMAAtLevel(NewLevel) !=
1728 DefaultMapAttributes::DMA_tofrom_scalar)
1729 OMPC = OMPC_firstprivate;
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001730 break;
1731 }
1732 }
1733 if (OMPC != OMPC_unknown)
1734 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1735}
1736
Alexey Bataeve3727102018-04-18 15:57:46 +00001737bool Sema::isOpenMPTargetCapturedDecl(const ValueDecl *D,
1738 unsigned Level) const {
Samuel Antao4be30e92015-10-02 17:14:03 +00001739 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1740 // Return true if the current level is no longer enclosed in a target region.
1741
Alexey Bataeve3727102018-04-18 15:57:46 +00001742 const auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001743 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001744 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1745 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001746}
1747
Alexey Bataeved09d242014-05-28 05:53:51 +00001748void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001749
1750void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1751 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001752 Scope *CurScope, SourceLocation Loc) {
1753 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001754 PushExpressionEvaluationContext(
1755 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001756}
1757
Alexey Bataevaac108a2015-06-23 04:51:00 +00001758void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1759 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001760}
1761
Alexey Bataevaac108a2015-06-23 04:51:00 +00001762void Sema::EndOpenMPClause() {
1763 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001764}
1765
Alexey Bataev758e55e2013-09-06 18:03:48 +00001766void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001767 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1768 // A variable of class type (or array thereof) that appears in a lastprivate
1769 // clause requires an accessible, unambiguous default constructor for the
1770 // class type, unless the list item is also specified in a firstprivate
1771 // clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00001772 if (const auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
1773 for (OMPClause *C : D->clauses()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001774 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1775 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00001776 for (Expr *DE : Clause->varlists()) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001777 if (DE->isValueDependent() || DE->isTypeDependent()) {
1778 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001779 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001780 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001781 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +00001782 auto *VD = cast<VarDecl>(DRE->getDecl());
Alexey Bataev005248a2016-02-25 05:25:57 +00001783 QualType Type = VD->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +00001784 const DSAStackTy::DSAVarData DVar =
1785 DSAStack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001786 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001787 // Generate helper private variable and initialize it with the
1788 // default value. The address of the original variable is replaced
1789 // by the address of the new private variable in CodeGen. This new
1790 // variable is not added to IdResolver, so the code in the OpenMP
1791 // region uses original variable for proper diagnostics.
Alexey Bataeve3727102018-04-18 15:57:46 +00001792 VarDecl *VDPrivate = buildVarDecl(
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001793 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev63cc8e92018-03-20 14:45:59 +00001794 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr, DRE);
Richard Smith3beb7c62017-01-12 02:27:38 +00001795 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001796 if (VDPrivate->isInvalidDecl())
1797 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001798 PrivateCopies.push_back(buildDeclRefExpr(
1799 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001800 } else {
1801 // The variable is also a firstprivate, so initialization sequence
1802 // for private copy is generated already.
1803 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001804 }
1805 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001806 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001807 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001808 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001809 }
1810 }
1811 }
1812
Alexey Bataev758e55e2013-09-06 18:03:48 +00001813 DSAStack->pop();
1814 DiscardCleanupsInEvaluationContext();
1815 PopExpressionEvaluationContext();
1816}
1817
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001818static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1819 Expr *NumIterations, Sema &SemaRef,
1820 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001821
Alexey Bataeva769e072013-03-22 06:34:35 +00001822namespace {
1823
Alexey Bataeve3727102018-04-18 15:57:46 +00001824class VarDeclFilterCCC final : public CorrectionCandidateCallback {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001825private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001826 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001827
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001828public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001829 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001830 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001831 NamedDecl *ND = Candidate.getCorrectionDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +00001832 if (const auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001833 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001834 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1835 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001836 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001837 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001838 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001839};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001840
Alexey Bataeve3727102018-04-18 15:57:46 +00001841class VarOrFuncDeclFilterCCC final : public CorrectionCandidateCallback {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001842private:
1843 Sema &SemaRef;
1844
1845public:
1846 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1847 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1848 NamedDecl *ND = Candidate.getCorrectionDecl();
Kelvin Li59e3d192017-11-30 18:52:06 +00001849 if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001850 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1851 SemaRef.getCurScope());
1852 }
1853 return false;
1854 }
1855};
1856
Alexey Bataeved09d242014-05-28 05:53:51 +00001857} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001858
1859ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1860 CXXScopeSpec &ScopeSpec,
1861 const DeclarationNameInfo &Id) {
1862 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1863 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1864
1865 if (Lookup.isAmbiguous())
1866 return ExprError();
1867
1868 VarDecl *VD;
1869 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001870 if (TypoCorrection Corrected = CorrectTypo(
1871 Id, LookupOrdinaryName, CurScope, nullptr,
1872 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001873 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001874 PDiag(Lookup.empty()
1875 ? diag::err_undeclared_var_use_suggest
1876 : diag::err_omp_expected_var_arg_suggest)
1877 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001878 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001879 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001880 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1881 : diag::err_omp_expected_var_arg)
1882 << Id.getName();
1883 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001884 }
Alexey Bataeve3727102018-04-18 15:57:46 +00001885 } else if (!(VD = Lookup.getAsSingle<VarDecl>())) {
1886 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
1887 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1888 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001889 }
1890 Lookup.suppressDiagnostics();
1891
1892 // OpenMP [2.9.2, Syntax, C/C++]
1893 // Variables must be file-scope, namespace-scope, or static block-scope.
1894 if (!VD->hasGlobalStorage()) {
1895 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001896 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1897 bool IsDecl =
1898 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001899 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001900 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1901 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001902 return ExprError();
1903 }
1904
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001905 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00001906 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001907 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1908 // A threadprivate directive for file-scope variables must appear outside
1909 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001910 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1911 !getCurLexicalContext()->isTranslationUnit()) {
1912 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001913 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1914 bool IsDecl =
1915 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1916 Diag(VD->getLocation(),
1917 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1918 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001919 return ExprError();
1920 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001921 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1922 // A threadprivate directive for static class member variables must appear
1923 // in the class definition, in the same scope in which the member
1924 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001925 if (CanonicalVD->isStaticDataMember() &&
1926 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1927 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001928 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1929 bool IsDecl =
1930 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1931 Diag(VD->getLocation(),
1932 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1933 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001934 return ExprError();
1935 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001936 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1937 // A threadprivate directive for namespace-scope variables must appear
1938 // outside any definition or declaration other than the namespace
1939 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001940 if (CanonicalVD->getDeclContext()->isNamespace() &&
1941 (!getCurLexicalContext()->isFileContext() ||
1942 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1943 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001944 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1945 bool IsDecl =
1946 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1947 Diag(VD->getLocation(),
1948 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1949 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001950 return ExprError();
1951 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001952 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1953 // A threadprivate directive for static block-scope variables must appear
1954 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001955 if (CanonicalVD->isStaticLocal() && CurScope &&
1956 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001957 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001958 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1959 bool IsDecl =
1960 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1961 Diag(VD->getLocation(),
1962 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1963 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001964 return ExprError();
1965 }
1966
1967 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1968 // A threadprivate directive must lexically precede all references to any
1969 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001970 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001971 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001972 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001973 return ExprError();
1974 }
1975
1976 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001977 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1978 SourceLocation(), VD,
1979 /*RefersToEnclosingVariableOrCapture=*/false,
1980 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001981}
1982
Alexey Bataeved09d242014-05-28 05:53:51 +00001983Sema::DeclGroupPtrTy
1984Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1985 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001986 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001987 CurContext->addDecl(D);
1988 return DeclGroupPtrTy::make(DeclGroupRef(D));
1989 }
David Blaikie0403cb12016-01-15 23:43:25 +00001990 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001991}
1992
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001993namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00001994class LocalVarRefChecker final
1995 : public ConstStmtVisitor<LocalVarRefChecker, bool> {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001996 Sema &SemaRef;
1997
1998public:
1999 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002000 if (const auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002001 if (VD->hasLocalStorage()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002002 SemaRef.Diag(E->getBeginLoc(),
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002003 diag::err_omp_local_var_in_threadprivate_init)
2004 << E->getSourceRange();
2005 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
2006 << VD << VD->getSourceRange();
2007 return true;
2008 }
2009 }
2010 return false;
2011 }
2012 bool VisitStmt(const Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002013 for (const Stmt *Child : S->children()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002014 if (Child && Visit(Child))
2015 return true;
2016 }
2017 return false;
2018 }
Alexey Bataev23b69422014-06-18 07:08:49 +00002019 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002020};
2021} // namespace
2022
Alexey Bataeved09d242014-05-28 05:53:51 +00002023OMPThreadPrivateDecl *
2024Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002025 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +00002026 for (Expr *RefExpr : VarList) {
2027 auto *DE = cast<DeclRefExpr>(RefExpr);
2028 auto *VD = cast<VarDecl>(DE->getDecl());
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002029 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00002030
Alexey Bataev376b4a42016-02-09 09:41:09 +00002031 // Mark variable as used.
2032 VD->setReferenced();
2033 VD->markUsed(Context);
2034
Alexey Bataevf56f98c2015-04-16 05:39:01 +00002035 QualType QType = VD->getType();
2036 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
2037 // It will be analyzed later.
2038 Vars.push_back(DE);
2039 continue;
2040 }
2041
Alexey Bataeva769e072013-03-22 06:34:35 +00002042 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2043 // A threadprivate variable must not have an incomplete type.
2044 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002045 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00002046 continue;
2047 }
2048
2049 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
2050 // A threadprivate variable must not have a reference type.
2051 if (VD->getType()->isReferenceType()) {
2052 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00002053 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
2054 bool IsDecl =
2055 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2056 Diag(VD->getLocation(),
2057 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2058 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002059 continue;
2060 }
2061
Samuel Antaof8b50122015-07-13 22:54:53 +00002062 // Check if this is a TLS variable. If TLS is not being supported, produce
2063 // the corresponding diagnostic.
2064 if ((VD->getTLSKind() != VarDecl::TLS_None &&
2065 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
2066 getLangOpts().OpenMPUseTLS &&
2067 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00002068 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
2069 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00002070 Diag(ILoc, diag::err_omp_var_thread_local)
2071 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00002072 bool IsDecl =
2073 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
2074 Diag(VD->getLocation(),
2075 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
2076 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00002077 continue;
2078 }
2079
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002080 // Check if initial value of threadprivate variable reference variable with
2081 // local storage (it is not supported by runtime).
Alexey Bataeve3727102018-04-18 15:57:46 +00002082 if (const Expr *Init = VD->getAnyInitializer()) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002083 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002084 if (Checker.Visit(Init))
2085 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00002086 }
2087
Alexey Bataeved09d242014-05-28 05:53:51 +00002088 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00002089 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00002090 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
2091 Context, SourceRange(Loc, Loc)));
Alexey Bataeve3727102018-04-18 15:57:46 +00002092 if (ASTMutationListener *ML = Context.getASTMutationListener())
Alexey Bataev97720002014-11-11 04:05:39 +00002093 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00002094 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00002095 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00002096 if (!Vars.empty()) {
2097 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
2098 Vars);
2099 D->setAccess(AS_public);
2100 }
2101 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00002102}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00002103
Kelvin Li1408f912018-09-26 04:28:39 +00002104Sema::DeclGroupPtrTy
2105Sema::ActOnOpenMPRequiresDirective(SourceLocation Loc,
2106 ArrayRef<OMPClause *> ClauseList) {
2107 OMPRequiresDecl *D = nullptr;
2108 if (!CurContext->isFileContext()) {
2109 Diag(Loc, diag::err_omp_invalid_scope) << "requires";
2110 } else {
2111 D = CheckOMPRequiresDecl(Loc, ClauseList);
2112 if (D) {
2113 CurContext->addDecl(D);
2114 DSAStack->addRequiresDecl(D);
2115 }
2116 }
2117 return DeclGroupPtrTy::make(DeclGroupRef(D));
2118}
2119
2120OMPRequiresDecl *Sema::CheckOMPRequiresDecl(SourceLocation Loc,
2121 ArrayRef<OMPClause *> ClauseList) {
2122 if (!DSAStack->hasDuplicateRequiresClause(ClauseList))
2123 return OMPRequiresDecl::Create(Context, getCurLexicalContext(), Loc,
2124 ClauseList);
2125 return nullptr;
2126}
2127
Alexey Bataeve3727102018-04-18 15:57:46 +00002128static void reportOriginalDsa(Sema &SemaRef, const DSAStackTy *Stack,
2129 const ValueDecl *D,
2130 const DSAStackTy::DSAVarData &DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00002131 bool IsLoopIterVar = false) {
2132 if (DVar.RefExpr) {
2133 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
2134 << getOpenMPClauseName(DVar.CKind);
2135 return;
2136 }
2137 enum {
2138 PDSA_StaticMemberShared,
2139 PDSA_StaticLocalVarShared,
2140 PDSA_LoopIterVarPrivate,
2141 PDSA_LoopIterVarLinear,
2142 PDSA_LoopIterVarLastprivate,
2143 PDSA_ConstVarShared,
2144 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002145 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00002146 PDSA_LocalVarPrivate,
2147 PDSA_Implicit
2148 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002149 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002150 auto ReportLoc = D->getLocation();
2151 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00002152 if (IsLoopIterVar) {
2153 if (DVar.CKind == OMPC_private)
2154 Reason = PDSA_LoopIterVarPrivate;
2155 else if (DVar.CKind == OMPC_lastprivate)
2156 Reason = PDSA_LoopIterVarLastprivate;
2157 else
2158 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00002159 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
2160 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002161 Reason = PDSA_TaskVarFirstprivate;
2162 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002163 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002164 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002165 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002166 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002167 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00002168 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002169 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00002170 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002171 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00002172 ReportHint = true;
2173 Reason = PDSA_LocalVarPrivate;
2174 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00002175 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002176 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00002177 << Reason << ReportHint
2178 << getOpenMPDirectiveName(Stack->getCurrentDirective());
2179 } else if (DVar.ImplicitDSALoc.isValid()) {
2180 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
2181 << getOpenMPClauseName(DVar.CKind);
2182 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00002183}
2184
Alexey Bataev758e55e2013-09-06 18:03:48 +00002185namespace {
Alexey Bataeve3727102018-04-18 15:57:46 +00002186class DSAAttrChecker final : public StmtVisitor<DSAAttrChecker, void> {
Alexey Bataev758e55e2013-09-06 18:03:48 +00002187 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002188 Sema &SemaRef;
Alexey Bataeve3727102018-04-18 15:57:46 +00002189 bool ErrorFound = false;
2190 CapturedStmt *CS = nullptr;
2191 llvm::SmallVector<Expr *, 4> ImplicitFirstprivate;
2192 llvm::SmallVector<Expr *, 4> ImplicitMap;
2193 Sema::VarsWithInheritedDSAType VarsWithInheritedDSA;
2194 llvm::SmallDenseSet<const ValueDecl *, 4> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00002195
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00002196 void VisitSubCaptures(OMPExecutableDirective *S) {
2197 // Check implicitly captured variables.
2198 if (!S->hasAssociatedStmt() || !S->getAssociatedStmt())
2199 return;
2200 for (const CapturedStmt::Capture &Cap :
2201 S->getInnermostCapturedStmt()->captures()) {
2202 if (!Cap.capturesVariable())
2203 continue;
2204 VarDecl *VD = Cap.getCapturedVar();
2205 // Do not try to map the variable if it or its sub-component was mapped
2206 // already.
2207 if (isOpenMPTargetExecutionDirective(Stack->getCurrentDirective()) &&
2208 Stack->checkMappableExprComponentListsForDecl(
2209 VD, /*CurrentRegionOnly=*/true,
2210 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
2211 OpenMPClauseKind) { return true; }))
2212 continue;
2213 DeclRefExpr *DRE = buildDeclRefExpr(
2214 SemaRef, VD, VD->getType().getNonLValueExprType(SemaRef.Context),
2215 Cap.getLocation(), /*RefersToCapture=*/true);
2216 Visit(DRE);
2217 }
2218 }
2219
Alexey Bataev758e55e2013-09-06 18:03:48 +00002220public:
2221 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002222 if (E->isTypeDependent() || E->isValueDependent() ||
2223 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2224 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002225 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002226 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002227 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002228 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00002229 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002230
Alexey Bataeve3727102018-04-18 15:57:46 +00002231 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002232 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002233 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00002234 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002235
Alexey Bataevafe50572017-10-06 17:00:28 +00002236 // Skip internally declared static variables.
Alexey Bataev92327c52018-03-26 16:40:55 +00002237 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
Alexey Bataev97b72212018-08-14 18:31:20 +00002238 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD);
Alexey Bataev92327c52018-03-26 16:40:55 +00002239 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD) &&
2240 (!Res || *Res != OMPDeclareTargetDeclAttr::MT_Link))
Alexey Bataevafe50572017-10-06 17:00:28 +00002241 return;
2242
Alexey Bataeve3727102018-04-18 15:57:46 +00002243 SourceLocation ELoc = E->getExprLoc();
2244 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002245 // The default(none) clause requires that each variable that is referenced
2246 // in the construct, and does not have a predetermined data-sharing
2247 // attribute, must have its data-sharing attribute explicitly determined
2248 // by being listed in a data-sharing attribute clause.
2249 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev7e6803e2019-01-09 15:58:05 +00002250 isImplicitOrExplicitTaskingRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00002251 VarsWithInheritedDSA.count(VD) == 0) {
2252 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00002253 return;
2254 }
2255
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002256 if (isOpenMPTargetExecutionDirective(DKind) &&
2257 !Stack->isLoopControlVariable(VD).first) {
2258 if (!Stack->checkMappableExprComponentListsForDecl(
2259 VD, /*CurrentRegionOnly=*/true,
2260 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2261 StackComponents,
2262 OpenMPClauseKind) {
2263 // Variable is used if it has been marked as an array, array
2264 // section or the variable iself.
2265 return StackComponents.size() == 1 ||
2266 std::all_of(
2267 std::next(StackComponents.rbegin()),
2268 StackComponents.rend(),
2269 [](const OMPClauseMappableExprCommon::
2270 MappableComponent &MC) {
2271 return MC.getAssociatedDeclaration() ==
2272 nullptr &&
2273 (isa<OMPArraySectionExpr>(
2274 MC.getAssociatedExpression()) ||
2275 isa<ArraySubscriptExpr>(
2276 MC.getAssociatedExpression()));
2277 });
2278 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002279 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002280 // By default lambdas are captured as firstprivates.
2281 if (const auto *RD =
2282 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002283 IsFirstprivate = RD->isLambda();
2284 IsFirstprivate =
2285 IsFirstprivate ||
2286 (VD->getType().getNonReferenceType()->isScalarType() &&
Alexey Bataev92327c52018-03-26 16:40:55 +00002287 Stack->getDefaultDMA() != DMA_tofrom_scalar && !Res);
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00002288 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002289 ImplicitFirstprivate.emplace_back(E);
2290 else
2291 ImplicitMap.emplace_back(E);
2292 return;
2293 }
2294 }
2295
Alexey Bataev758e55e2013-09-06 18:03:48 +00002296 // OpenMP [2.9.3.6, Restrictions, p.2]
2297 // A list item that appears in a reduction clause of the innermost
2298 // enclosing worksharing or parallel construct may not be accessed in an
2299 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002300 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002301 VD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2302 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002303 return isOpenMPParallelDirective(K) ||
2304 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2305 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00002306 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002307 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00002308 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00002309 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002310 reportOriginalDsa(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00002311 return;
2312 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002313
2314 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002315 DVar = Stack->getImplicitDSA(VD, /*FromParent=*/false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00002316 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2317 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002318 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002319 }
2320 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002321 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002322 if (E->isTypeDependent() || E->isValueDependent() ||
2323 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2324 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002325 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002326 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Patrick Lystere13b1e32019-01-02 19:28:48 +00002327 if (auto *TE = dyn_cast<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002328 if (!FD)
2329 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002330 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002331 // Check if the variable has explicit DSA set and stop analysis if it
2332 // so.
2333 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2334 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002335
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002336 if (isOpenMPTargetExecutionDirective(DKind) &&
2337 !Stack->isLoopControlVariable(FD).first &&
2338 !Stack->checkMappableExprComponentListsForDecl(
2339 FD, /*CurrentRegionOnly=*/true,
2340 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2341 StackComponents,
2342 OpenMPClauseKind) {
2343 return isa<CXXThisExpr>(
2344 cast<MemberExpr>(
2345 StackComponents.back().getAssociatedExpression())
2346 ->getBase()
2347 ->IgnoreParens());
2348 })) {
2349 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2350 // A bit-field cannot appear in a map clause.
2351 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002352 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002353 return;
Patrick Lystere13b1e32019-01-02 19:28:48 +00002354
2355 // Check to see if the member expression is referencing a class that
2356 // has already been explicitly mapped
2357 if (Stack->isClassPreviouslyMapped(TE->getType()))
2358 return;
2359
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002360 ImplicitMap.emplace_back(E);
2361 return;
2362 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002363
Alexey Bataeve3727102018-04-18 15:57:46 +00002364 SourceLocation ELoc = E->getExprLoc();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002365 // OpenMP [2.9.3.6, Restrictions, p.2]
2366 // A list item that appears in a reduction clause of the innermost
2367 // enclosing worksharing or parallel construct may not be accessed in
2368 // an explicit task.
2369 DVar = Stack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +00002370 FD, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
2371 [](OpenMPDirectiveKind K) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002372 return isOpenMPParallelDirective(K) ||
2373 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2374 },
2375 /*FromParent=*/true);
2376 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2377 ErrorFound = true;
2378 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
Alexey Bataeve3727102018-04-18 15:57:46 +00002379 reportOriginalDsa(SemaRef, Stack, FD, DVar);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002380 return;
2381 }
2382
2383 // Define implicit data-sharing attributes for task.
Alexey Bataeve3727102018-04-18 15:57:46 +00002384 DVar = Stack->getImplicitDSA(FD, /*FromParent=*/false);
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002385 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
Alexey Bataevb40e05202018-10-24 18:53:12 +00002386 !Stack->isLoopControlVariable(FD).first) {
2387 // Check if there is a captured expression for the current field in the
2388 // region. Do not mark it as firstprivate unless there is no captured
2389 // expression.
2390 // TODO: try to make it firstprivate.
2391 if (DVar.CKind != OMPC_unknown)
2392 ImplicitFirstprivate.push_back(E);
2393 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002394 return;
2395 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002396 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002397 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataeve3727102018-04-18 15:57:46 +00002398 if (!checkMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002399 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002400 return;
Alexey Bataeve3727102018-04-18 15:57:46 +00002401 const auto *VD = cast<ValueDecl>(
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002402 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2403 if (!Stack->checkMappableExprComponentListsForDecl(
2404 VD, /*CurrentRegionOnly=*/true,
2405 [&CurComponents](
2406 OMPClauseMappableExprCommon::MappableExprComponentListRef
2407 StackComponents,
2408 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002409 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002410 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002411 for (const auto &SC : llvm::reverse(StackComponents)) {
2412 // Do both expressions have the same kind?
2413 if (CCI->getAssociatedExpression()->getStmtClass() !=
2414 SC.getAssociatedExpression()->getStmtClass())
2415 if (!(isa<OMPArraySectionExpr>(
2416 SC.getAssociatedExpression()) &&
2417 isa<ArraySubscriptExpr>(
2418 CCI->getAssociatedExpression())))
2419 return false;
2420
Alexey Bataeve3727102018-04-18 15:57:46 +00002421 const Decl *CCD = CCI->getAssociatedDeclaration();
2422 const Decl *SCD = SC.getAssociatedDeclaration();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002423 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2424 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2425 if (SCD != CCD)
2426 return false;
2427 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002428 if (CCI == CCE)
2429 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002430 }
2431 return true;
2432 })) {
2433 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002434 }
Alexey Bataeve3727102018-04-18 15:57:46 +00002435 } else {
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002436 Visit(E->getBase());
Alexey Bataeve3727102018-04-18 15:57:46 +00002437 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002438 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002439 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002440 for (OMPClause *C : S->clauses()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002441 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002442 // for task|target directives.
2443 // Skip analysis of arguments of implicitly defined map clause for target
2444 // directives.
2445 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2446 C->isImplicit())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002447 for (Stmt *CC : C->children()) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002448 if (CC)
2449 Visit(CC);
2450 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002451 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002452 }
Alexey Bataevf07946e2018-10-29 20:17:42 +00002453 // Check implicitly captured variables.
2454 VisitSubCaptures(S);
Alexey Bataev758e55e2013-09-06 18:03:48 +00002455 }
2456 void VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002457 for (Stmt *C : S->children()) {
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002458 if (C) {
Joel E. Denny0fdf5a92018-12-19 15:59:47 +00002459 // Check implicitly captured variables in the task-based directives to
2460 // check if they must be firstprivatized.
2461 Visit(C);
Alexey Bataev8fc7b5f2018-10-25 15:35:27 +00002462 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002463 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002464 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002465
Alexey Bataeve3727102018-04-18 15:57:46 +00002466 bool isErrorFound() const { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002467 ArrayRef<Expr *> getImplicitFirstprivate() const {
2468 return ImplicitFirstprivate;
2469 }
2470 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataeve3727102018-04-18 15:57:46 +00002471 const Sema::VarsWithInheritedDSAType &getVarsWithInheritedDSA() const {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002472 return VarsWithInheritedDSA;
2473 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002474
Alexey Bataev7ff55242014-06-19 09:13:45 +00002475 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2476 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002477};
Alexey Bataeved09d242014-05-28 05:53:51 +00002478} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002479
Alexey Bataevbae9a792014-06-27 10:37:06 +00002480void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002481 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002482 case OMPD_parallel:
2483 case OMPD_parallel_for:
2484 case OMPD_parallel_for_simd:
2485 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002486 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002487 case OMPD_teams_distribute:
2488 case OMPD_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002489 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Alexey Bataev2377fe92015-09-10 08:12:02 +00002490 QualType KmpInt32PtrTy =
2491 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002492 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002493 std::make_pair(".global_tid.", KmpInt32PtrTy),
2494 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2495 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002496 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002497 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2498 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002499 break;
2500 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002501 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002502 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002503 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002504 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002505 case OMPD_target_teams_distribute:
2506 case OMPD_target_teams_distribute_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002507 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2508 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2509 QualType KmpInt32PtrTy =
2510 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2511 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002512 FunctionProtoType::ExtProtoInfo EPI;
2513 EPI.Variadic = true;
2514 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2515 Sema::CapturedParamNameType Params[] = {
2516 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002517 std::make_pair(".part_id.", KmpInt32PtrTy),
2518 std::make_pair(".privates.", VoidPtrTy),
2519 std::make_pair(
2520 ".copy_fn.",
2521 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002522 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2523 std::make_pair(StringRef(), QualType()) // __context with shared vars
2524 };
2525 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2526 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002527 // Mark this captured region as inlined, because we don't use outlined
2528 // function directly.
2529 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2530 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002531 Context, AlwaysInlineAttr::Keyword_forceinline));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002532 Sema::CapturedParamNameType ParamsTarget[] = {
2533 std::make_pair(StringRef(), QualType()) // __context with shared vars
2534 };
2535 // Start a captured region for 'target' with no implicit parameters.
2536 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2537 ParamsTarget);
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002538 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002539 std::make_pair(".global_tid.", KmpInt32PtrTy),
2540 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2541 std::make_pair(StringRef(), QualType()) // __context with shared vars
2542 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002543 // Start a captured region for 'teams' or 'parallel'. Both regions have
2544 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002545 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002546 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002547 break;
2548 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002549 case OMPD_target:
2550 case OMPD_target_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002551 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2552 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2553 QualType KmpInt32PtrTy =
2554 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2555 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002556 FunctionProtoType::ExtProtoInfo EPI;
2557 EPI.Variadic = true;
2558 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2559 Sema::CapturedParamNameType Params[] = {
2560 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002561 std::make_pair(".part_id.", KmpInt32PtrTy),
2562 std::make_pair(".privates.", VoidPtrTy),
2563 std::make_pair(
2564 ".copy_fn.",
2565 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002566 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2567 std::make_pair(StringRef(), QualType()) // __context with shared vars
2568 };
2569 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2570 Params);
2571 // Mark this captured region as inlined, because we don't use outlined
2572 // function directly.
2573 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2574 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002575 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev8451efa2018-01-15 19:06:12 +00002576 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2577 std::make_pair(StringRef(), QualType()));
2578 break;
2579 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002580 case OMPD_simd:
2581 case OMPD_for:
2582 case OMPD_for_simd:
2583 case OMPD_sections:
2584 case OMPD_section:
2585 case OMPD_single:
2586 case OMPD_master:
2587 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002588 case OMPD_taskgroup:
2589 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002590 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002591 case OMPD_ordered:
2592 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002593 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002594 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002595 std::make_pair(StringRef(), QualType()) // __context with shared vars
2596 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002597 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2598 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002599 break;
2600 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002601 case OMPD_task: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002602 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2603 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2604 QualType KmpInt32PtrTy =
2605 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2606 QualType Args[] = {VoidPtrTy};
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002607 FunctionProtoType::ExtProtoInfo EPI;
2608 EPI.Variadic = true;
2609 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002610 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002611 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002612 std::make_pair(".part_id.", KmpInt32PtrTy),
2613 std::make_pair(".privates.", VoidPtrTy),
2614 std::make_pair(
2615 ".copy_fn.",
2616 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002617 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002618 std::make_pair(StringRef(), QualType()) // __context with shared vars
2619 };
2620 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2621 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002622 // Mark this captured region as inlined, because we don't use outlined
2623 // function directly.
2624 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2625 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002626 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002627 break;
2628 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002629 case OMPD_taskloop:
2630 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002631 QualType KmpInt32Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002632 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1)
2633 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002634 QualType KmpUInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002635 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0)
2636 .withConst();
Alexey Bataev7292c292016-04-25 12:22:29 +00002637 QualType KmpInt64Ty =
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002638 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1)
2639 .withConst();
2640 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2641 QualType KmpInt32PtrTy =
2642 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2643 QualType Args[] = {VoidPtrTy};
Alexey Bataev7292c292016-04-25 12:22:29 +00002644 FunctionProtoType::ExtProtoInfo EPI;
2645 EPI.Variadic = true;
2646 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002647 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002648 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002649 std::make_pair(".part_id.", KmpInt32PtrTy),
2650 std::make_pair(".privates.", VoidPtrTy),
Alexey Bataev7292c292016-04-25 12:22:29 +00002651 std::make_pair(
2652 ".copy_fn.",
2653 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2654 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2655 std::make_pair(".lb.", KmpUInt64Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002656 std::make_pair(".ub.", KmpUInt64Ty),
2657 std::make_pair(".st.", KmpInt64Ty),
Alexey Bataev7292c292016-04-25 12:22:29 +00002658 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002659 std::make_pair(".reductions.", VoidPtrTy),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002660 std::make_pair(StringRef(), QualType()) // __context with shared vars
2661 };
2662 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2663 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002664 // Mark this captured region as inlined, because we don't use outlined
2665 // function directly.
2666 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2667 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002668 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002669 break;
2670 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002671 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002672 case OMPD_distribute_parallel_for: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002673 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli9925f152016-06-27 14:55:37 +00002674 QualType KmpInt32PtrTy =
2675 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2676 Sema::CapturedParamNameType Params[] = {
2677 std::make_pair(".global_tid.", KmpInt32PtrTy),
2678 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002679 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2680 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli9925f152016-06-27 14:55:37 +00002681 std::make_pair(StringRef(), QualType()) // __context with shared vars
2682 };
2683 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2684 Params);
2685 break;
2686 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002687 case OMPD_target_teams_distribute_parallel_for:
2688 case OMPD_target_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002689 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002690 QualType KmpInt32PtrTy =
2691 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002692 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
Carlo Bertolli52978c32018-01-03 21:12:44 +00002693
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002694 QualType Args[] = {VoidPtrTy};
Alexey Bataev8451efa2018-01-15 19:06:12 +00002695 FunctionProtoType::ExtProtoInfo EPI;
2696 EPI.Variadic = true;
2697 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2698 Sema::CapturedParamNameType Params[] = {
2699 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002700 std::make_pair(".part_id.", KmpInt32PtrTy),
2701 std::make_pair(".privates.", VoidPtrTy),
2702 std::make_pair(
2703 ".copy_fn.",
2704 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev8451efa2018-01-15 19:06:12 +00002705 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2706 std::make_pair(StringRef(), QualType()) // __context with shared vars
2707 };
2708 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2709 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00002710 // Mark this captured region as inlined, because we don't use outlined
2711 // function directly.
2712 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2713 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002714 Context, AlwaysInlineAttr::Keyword_forceinline));
Carlo Bertolli52978c32018-01-03 21:12:44 +00002715 Sema::CapturedParamNameType ParamsTarget[] = {
2716 std::make_pair(StringRef(), QualType()) // __context with shared vars
2717 };
2718 // Start a captured region for 'target' with no implicit parameters.
2719 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2720 ParamsTarget);
2721
2722 Sema::CapturedParamNameType ParamsTeams[] = {
2723 std::make_pair(".global_tid.", KmpInt32PtrTy),
2724 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2725 std::make_pair(StringRef(), QualType()) // __context with shared vars
2726 };
2727 // Start a captured region for 'target' with no implicit parameters.
2728 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2729 ParamsTeams);
2730
2731 Sema::CapturedParamNameType ParamsParallel[] = {
2732 std::make_pair(".global_tid.", KmpInt32PtrTy),
2733 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002734 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2735 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli52978c32018-01-03 21:12:44 +00002736 std::make_pair(StringRef(), QualType()) // __context with shared vars
2737 };
2738 // Start a captured region for 'teams' or 'parallel'. Both regions have
2739 // the same implicit parameters.
2740 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2741 ParamsParallel);
2742 break;
2743 }
2744
Alexey Bataev46506272017-12-05 17:41:34 +00002745 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00002746 case OMPD_teams_distribute_parallel_for_simd: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002747 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
Carlo Bertolli62fae152017-11-20 20:46:39 +00002748 QualType KmpInt32PtrTy =
2749 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2750
2751 Sema::CapturedParamNameType ParamsTeams[] = {
2752 std::make_pair(".global_tid.", KmpInt32PtrTy),
2753 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2754 std::make_pair(StringRef(), QualType()) // __context with shared vars
2755 };
2756 // Start a captured region for 'target' with no implicit parameters.
2757 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2758 ParamsTeams);
2759
2760 Sema::CapturedParamNameType ParamsParallel[] = {
2761 std::make_pair(".global_tid.", KmpInt32PtrTy),
2762 std::make_pair(".bound_tid.", KmpInt32PtrTy),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002763 std::make_pair(".previous.lb.", Context.getSizeType().withConst()),
2764 std::make_pair(".previous.ub.", Context.getSizeType().withConst()),
Carlo Bertolli62fae152017-11-20 20:46:39 +00002765 std::make_pair(StringRef(), QualType()) // __context with shared vars
2766 };
2767 // Start a captured region for 'teams' or 'parallel'. Both regions have
2768 // the same implicit parameters.
2769 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2770 ParamsParallel);
2771 break;
2772 }
Alexey Bataev7828b252017-11-21 17:08:48 +00002773 case OMPD_target_update:
2774 case OMPD_target_enter_data:
2775 case OMPD_target_exit_data: {
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002776 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1).withConst();
2777 QualType VoidPtrTy = Context.VoidPtrTy.withConst().withRestrict();
2778 QualType KmpInt32PtrTy =
2779 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2780 QualType Args[] = {VoidPtrTy};
Alexey Bataev7828b252017-11-21 17:08:48 +00002781 FunctionProtoType::ExtProtoInfo EPI;
2782 EPI.Variadic = true;
2783 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2784 Sema::CapturedParamNameType Params[] = {
2785 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002786 std::make_pair(".part_id.", KmpInt32PtrTy),
2787 std::make_pair(".privates.", VoidPtrTy),
2788 std::make_pair(
2789 ".copy_fn.",
2790 Context.getPointerType(CopyFnType).withConst().withRestrict()),
Alexey Bataev7828b252017-11-21 17:08:48 +00002791 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2792 std::make_pair(StringRef(), QualType()) // __context with shared vars
2793 };
2794 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2795 Params);
2796 // Mark this captured region as inlined, because we don't use outlined
2797 // function directly.
2798 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2799 AlwaysInlineAttr::CreateImplicit(
Alexey Bataevc0f879b2018-04-10 20:10:53 +00002800 Context, AlwaysInlineAttr::Keyword_forceinline));
Alexey Bataev7828b252017-11-21 17:08:48 +00002801 break;
2802 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002803 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002804 case OMPD_taskyield:
2805 case OMPD_barrier:
2806 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002807 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002808 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002809 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002810 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002811 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002812 case OMPD_declare_target:
2813 case OMPD_end_declare_target:
Kelvin Li1408f912018-09-26 04:28:39 +00002814 case OMPD_requires:
Alexey Bataev9959db52014-05-06 10:08:46 +00002815 llvm_unreachable("OpenMP Directive is not allowed");
2816 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002817 llvm_unreachable("Unknown OpenMP directive");
2818 }
2819}
2820
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002821int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2822 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2823 getOpenMPCaptureRegions(CaptureRegions, DKind);
2824 return CaptureRegions.size();
2825}
2826
Alexey Bataev3392d762016-02-16 11:18:12 +00002827static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002828 Expr *CaptureExpr, bool WithInit,
2829 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002830 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002831 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002832 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002833 QualType Ty = Init->getType();
2834 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002835 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00002836 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002837 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00002838 Ty = C.getPointerType(Ty);
2839 ExprResult Res =
2840 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2841 if (!Res.isUsable())
2842 return nullptr;
2843 Init = Res.get();
2844 }
Alexey Bataev61205072016-03-02 04:57:40 +00002845 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002846 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002847 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002848 CaptureExpr->getBeginLoc());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002849 if (!WithInit)
Alexey Bataeve3727102018-04-18 15:57:46 +00002850 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C));
Alexey Bataev4244be22016-02-11 05:35:55 +00002851 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002852 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002853 return CED;
2854}
2855
Alexey Bataev61205072016-03-02 04:57:40 +00002856static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2857 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002858 OMPCapturedExprDecl *CD;
Alexey Bataeve3727102018-04-18 15:57:46 +00002859 if (VarDecl *VD = S.isOpenMPCapturedDecl(D))
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002860 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataeve3727102018-04-18 15:57:46 +00002861 else
Alexey Bataev5a3af132016-03-29 08:58:54 +00002862 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2863 /*AsExpression=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002864 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002865 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002866}
2867
Alexey Bataev5a3af132016-03-29 08:58:54 +00002868static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002869 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002870 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002871 OMPCapturedExprDecl *CD = buildCaptureDecl(
2872 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2873 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00002874 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2875 CaptureExpr->getExprLoc());
2876 }
2877 ExprResult Res = Ref;
2878 if (!S.getLangOpts().CPlusPlus &&
2879 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002880 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002881 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002882 if (!Res.isUsable())
2883 return ExprError();
2884 }
2885 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002886}
2887
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002888namespace {
2889// OpenMP directives parsed in this section are represented as a
2890// CapturedStatement with an associated statement. If a syntax error
2891// is detected during the parsing of the associated statement, the
2892// compiler must abort processing and close the CapturedStatement.
2893//
2894// Combined directives such as 'target parallel' have more than one
2895// nested CapturedStatements. This RAII ensures that we unwind out
2896// of all the nested CapturedStatements when an error is found.
2897class CaptureRegionUnwinderRAII {
2898private:
2899 Sema &S;
2900 bool &ErrorFound;
Alexey Bataeve3727102018-04-18 15:57:46 +00002901 OpenMPDirectiveKind DKind = OMPD_unknown;
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002902
2903public:
2904 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2905 OpenMPDirectiveKind DKind)
2906 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2907 ~CaptureRegionUnwinderRAII() {
2908 if (ErrorFound) {
2909 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2910 while (--ThisCaptureLevel >= 0)
2911 S.ActOnCapturedRegionError();
2912 }
2913 }
2914};
2915} // namespace
2916
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002917StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2918 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002919 bool ErrorFound = false;
2920 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2921 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002922 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002923 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002924 return StmtError();
2925 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002926
Alexey Bataev2ba67042017-11-28 21:11:44 +00002927 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2928 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00002929 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002930 OMPScheduleClause *SC = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00002931 SmallVector<const OMPLinearClause *, 4> LCs;
2932 SmallVector<const OMPClauseWithPreInit *, 4> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002933 // This is required for proper codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00002934 for (OMPClause *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002935 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2936 Clause->getClauseKind() == OMPC_in_reduction) {
2937 // Capture taskgroup task_reduction descriptors inside the tasking regions
2938 // with the corresponding in_reduction items.
2939 auto *IRC = cast<OMPInReductionClause>(Clause);
Alexey Bataeve3727102018-04-18 15:57:46 +00002940 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00002941 if (E)
2942 MarkDeclarationsReferencedInExpr(E);
2943 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002944 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002945 Clause->getClauseKind() == OMPC_copyprivate ||
2946 (getLangOpts().OpenMPUseTLS &&
2947 getASTContext().getTargetInfo().isTLSSupported() &&
2948 Clause->getClauseKind() == OMPC_copyin)) {
2949 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002950 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeve3727102018-04-18 15:57:46 +00002951 for (Stmt *VarRef : Clause->children()) {
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002952 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002953 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002954 }
2955 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002956 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00002957 } else if (CaptureRegions.size() > 1 ||
2958 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002959 if (auto *C = OMPClauseWithPreInit::get(Clause))
2960 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002961 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002962 if (Expr *E = C->getPostUpdateExpr())
Alexey Bataev005248a2016-02-25 05:25:57 +00002963 MarkDeclarationsReferencedInExpr(E);
2964 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002965 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002966 if (Clause->getClauseKind() == OMPC_schedule)
2967 SC = cast<OMPScheduleClause>(Clause);
2968 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002969 OC = cast<OMPOrderedClause>(Clause);
2970 else if (Clause->getClauseKind() == OMPC_linear)
2971 LCs.push_back(cast<OMPLinearClause>(Clause));
2972 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002973 // OpenMP, 2.7.1 Loop Construct, Restrictions
2974 // The nonmonotonic modifier cannot be specified if an ordered clause is
2975 // specified.
2976 if (SC &&
2977 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2978 SC->getSecondScheduleModifier() ==
2979 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2980 OC) {
2981 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2982 ? SC->getFirstScheduleModifierLoc()
2983 : SC->getSecondScheduleModifierLoc(),
2984 diag::err_omp_schedule_nonmonotonic_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002985 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev6402bca2015-12-28 07:25:51 +00002986 ErrorFound = true;
2987 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002988 if (!LCs.empty() && OC && OC->getNumForLoops()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00002989 for (const OMPLinearClause *C : LCs) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002990 Diag(C->getBeginLoc(), diag::err_omp_linear_ordered)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00002991 << SourceRange(OC->getBeginLoc(), OC->getEndLoc());
Alexey Bataev993d2802015-12-28 06:23:08 +00002992 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002993 ErrorFound = true;
2994 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002995 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2996 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2997 OC->getNumForLoops()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00002998 Diag(OC->getBeginLoc(), diag::err_omp_ordered_simd)
Alexey Bataev113438c2015-12-30 12:06:23 +00002999 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
3000 ErrorFound = true;
3001 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00003002 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00003003 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003004 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003005 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00003006 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003007 // Mark all variables in private list clauses as used in inner region.
3008 // Required for proper codegen of combined directives.
3009 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00003010 if (ThisCaptureRegion != OMPD_unknown) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003011 for (const clang::OMPClauseWithPreInit *C : PICs) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003012 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
3013 // Find the particular capture region for the clause if the
3014 // directive is a combined one with multiple capture regions.
3015 // If the directive is not a combined one, the capture region
3016 // associated with the clause is OMPD_unknown and is generated
3017 // only once.
3018 if (CaptureRegion == ThisCaptureRegion ||
3019 CaptureRegion == OMPD_unknown) {
3020 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003021 for (Decl *D : DS->decls())
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003022 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
3023 }
3024 }
3025 }
3026 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003027 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00003028 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00003029 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00003030}
3031
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003032static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
3033 OpenMPDirectiveKind CancelRegion,
3034 SourceLocation StartLoc) {
3035 // CancelRegion is only needed for cancel and cancellation_point.
3036 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
3037 return false;
3038
3039 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
3040 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
3041 return false;
3042
3043 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
3044 << getOpenMPDirectiveName(CancelRegion);
3045 return true;
3046}
3047
Alexey Bataeve3727102018-04-18 15:57:46 +00003048static bool checkNestingOfRegions(Sema &SemaRef, const DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003049 OpenMPDirectiveKind CurrentRegion,
3050 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003051 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003052 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003053 if (Stack->getCurScope()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003054 OpenMPDirectiveKind ParentRegion = Stack->getParentDirective();
3055 OpenMPDirectiveKind OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003056 bool NestingProhibited = false;
3057 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00003058 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003059 enum {
3060 NoRecommend,
3061 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00003062 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003063 ShouldBeInTargetRegion,
3064 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003065 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00003066 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003067 // OpenMP [2.16, Nesting of Regions]
3068 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003069 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00003070 // An ordered construct with the simd clause is the only OpenMP
3071 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00003072 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00003073 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
3074 // message.
3075 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
3076 ? diag::err_omp_prohibited_region_simd
3077 : diag::warn_omp_nesting_simd);
3078 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00003079 }
Alexey Bataev0162e452014-07-22 10:10:35 +00003080 if (ParentRegion == OMPD_atomic) {
3081 // OpenMP [2.16, Nesting of Regions]
3082 // OpenMP constructs may not be nested inside an atomic region.
3083 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
3084 return true;
3085 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003086 if (CurrentRegion == OMPD_section) {
3087 // OpenMP [2.7.2, sections Construct, Restrictions]
3088 // Orphaned section directives are prohibited. That is, the section
3089 // directives must appear within the sections construct and must not be
3090 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003091 if (ParentRegion != OMPD_sections &&
3092 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003093 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
3094 << (ParentRegion != OMPD_unknown)
3095 << getOpenMPDirectiveName(ParentRegion);
3096 return true;
3097 }
3098 return false;
3099 }
Alexey Bataev185e88d2019-01-08 15:53:42 +00003100 // Allow some constructs (except teams and cancellation constructs) to be
3101 // orphaned (they could be used in functions, called from OpenMP regions
3102 // with the required preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00003103 if (ParentRegion == OMPD_unknown &&
Alexey Bataev185e88d2019-01-08 15:53:42 +00003104 !isOpenMPNestingTeamsDirective(CurrentRegion) &&
3105 CurrentRegion != OMPD_cancellation_point &&
3106 CurrentRegion != OMPD_cancel)
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003107 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00003108 if (CurrentRegion == OMPD_cancellation_point ||
3109 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003110 // OpenMP [2.16, Nesting of Regions]
3111 // A cancellation point construct for which construct-type-clause is
3112 // taskgroup must be nested inside a task construct. A cancellation
3113 // point construct for which construct-type-clause is not taskgroup must
3114 // be closely nested inside an OpenMP construct that matches the type
3115 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00003116 // A cancel construct for which construct-type-clause is taskgroup must be
3117 // nested inside a task construct. A cancel construct for which
3118 // construct-type-clause is not taskgroup must be closely nested inside an
3119 // OpenMP construct that matches the type specified in
3120 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003121 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003122 !((CancelRegion == OMPD_parallel &&
3123 (ParentRegion == OMPD_parallel ||
3124 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00003125 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003126 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00003127 ParentRegion == OMPD_target_parallel_for ||
3128 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00003129 ParentRegion == OMPD_teams_distribute_parallel_for ||
3130 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003131 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
3132 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00003133 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
3134 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev185e88d2019-01-08 15:53:42 +00003135 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003136 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00003137 // OpenMP [2.16, Nesting of Regions]
3138 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003139 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00003140 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003141 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003142 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
3143 // OpenMP [2.16, Nesting of Regions]
3144 // A critical region may not be nested (closely or otherwise) inside a
3145 // critical region with the same name. Note that this restriction is not
3146 // sufficient to prevent deadlock.
3147 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00003148 bool DeadLock = Stack->hasDirective(
3149 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
3150 const DeclarationNameInfo &DNI,
Alexey Bataeve3727102018-04-18 15:57:46 +00003151 SourceLocation Loc) {
David Majnemer9d168222016-08-05 17:44:54 +00003152 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
3153 PreviousCriticalLoc = Loc;
3154 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003155 }
3156 return false;
David Majnemer9d168222016-08-05 17:44:54 +00003157 },
3158 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003159 if (DeadLock) {
3160 SemaRef.Diag(StartLoc,
3161 diag::err_omp_prohibited_region_critical_same_name)
3162 << CurrentName.getName();
3163 if (PreviousCriticalLoc.isValid())
3164 SemaRef.Diag(PreviousCriticalLoc,
3165 diag::note_omp_previous_critical_region);
3166 return true;
3167 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003168 } else if (CurrentRegion == OMPD_barrier) {
3169 // OpenMP [2.16, Nesting of Regions]
3170 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00003171 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003172 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3173 isOpenMPTaskingDirective(ParentRegion) ||
3174 ParentRegion == OMPD_master ||
3175 ParentRegion == OMPD_critical ||
3176 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00003177 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00003178 !isOpenMPParallelDirective(CurrentRegion) &&
3179 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00003180 // OpenMP [2.16, Nesting of Regions]
3181 // A worksharing region may not be closely nested inside a worksharing,
3182 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00003183 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
3184 isOpenMPTaskingDirective(ParentRegion) ||
3185 ParentRegion == OMPD_master ||
3186 ParentRegion == OMPD_critical ||
3187 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003188 Recommend = ShouldBeInParallelRegion;
3189 } else if (CurrentRegion == OMPD_ordered) {
3190 // OpenMP [2.16, Nesting of Regions]
3191 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00003192 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003193 // An ordered region must be closely nested inside a loop region (or
3194 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003195 // OpenMP [2.8.1,simd Construct, Restrictions]
3196 // An ordered construct with the simd clause is the only OpenMP construct
3197 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003198 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00003199 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00003200 !(isOpenMPSimdDirective(ParentRegion) ||
3201 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003202 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00003203 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003204 // OpenMP [2.16, Nesting of Regions]
3205 // If specified, a teams construct must be contained within a target
3206 // construct.
3207 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00003208 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003209 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003210 }
Kelvin Libf594a52016-12-17 05:48:59 +00003211 if (!NestingProhibited &&
3212 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
3213 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
3214 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00003215 // OpenMP [2.16, Nesting of Regions]
3216 // distribute, parallel, parallel sections, parallel workshare, and the
3217 // parallel loop and parallel loop SIMD constructs are the only OpenMP
3218 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003219 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
3220 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00003221 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00003222 }
David Majnemer9d168222016-08-05 17:44:54 +00003223 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00003224 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003225 // OpenMP 4.5 [2.17 Nesting of Regions]
3226 // The region associated with the distribute construct must be strictly
3227 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00003228 NestingProhibited =
3229 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003230 Recommend = ShouldBeInTeamsRegion;
3231 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003232 if (!NestingProhibited &&
3233 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
3234 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
3235 // OpenMP 4.5 [2.17 Nesting of Regions]
3236 // If a target, target update, target data, target enter data, or
3237 // target exit data construct is encountered during execution of a
3238 // target region, the behavior is unspecified.
3239 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00003240 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
Alexey Bataeve3727102018-04-18 15:57:46 +00003241 SourceLocation) {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003242 if (isOpenMPTargetExecutionDirective(K)) {
3243 OffendingRegion = K;
3244 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003245 }
3246 return false;
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00003247 },
3248 false /* don't skip top directive */);
3249 CloseNesting = false;
3250 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003251 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00003252 if (OrphanSeen) {
3253 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
3254 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
3255 } else {
3256 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
3257 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
3258 << Recommend << getOpenMPDirectiveName(CurrentRegion);
3259 }
Alexey Bataev549210e2014-06-24 04:39:47 +00003260 return true;
3261 }
3262 }
3263 return false;
3264}
3265
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003266static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
3267 ArrayRef<OMPClause *> Clauses,
3268 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
3269 bool ErrorFound = false;
3270 unsigned NamedModifiersNumber = 0;
3271 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
3272 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00003273 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00003274 for (const OMPClause *C : Clauses) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003275 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
3276 // At most one if clause without a directive-name-modifier can appear on
3277 // the directive.
3278 OpenMPDirectiveKind CurNM = IC->getNameModifier();
3279 if (FoundNameModifiers[CurNM]) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003280 S.Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003281 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
3282 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
3283 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003284 } else if (CurNM != OMPD_unknown) {
3285 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003286 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00003287 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003288 FoundNameModifiers[CurNM] = IC;
3289 if (CurNM == OMPD_unknown)
3290 continue;
3291 // Check if the specified name modifier is allowed for the current
3292 // directive.
3293 // At most one if clause with the particular directive-name-modifier can
3294 // appear on the directive.
3295 bool MatchFound = false;
3296 for (auto NM : AllowedNameModifiers) {
3297 if (CurNM == NM) {
3298 MatchFound = true;
3299 break;
3300 }
3301 }
3302 if (!MatchFound) {
3303 S.Diag(IC->getNameModifierLoc(),
3304 diag::err_omp_wrong_if_directive_name_modifier)
3305 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
3306 ErrorFound = true;
3307 }
3308 }
3309 }
3310 // If any if clause on the directive includes a directive-name-modifier then
3311 // all if clauses on the directive must include a directive-name-modifier.
3312 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
3313 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003314 S.Diag(FoundNameModifiers[OMPD_unknown]->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003315 diag::err_omp_no_more_if_clause);
3316 } else {
3317 std::string Values;
3318 std::string Sep(", ");
3319 unsigned AllowedCnt = 0;
3320 unsigned TotalAllowedNum =
3321 AllowedNameModifiers.size() - NamedModifiersNumber;
3322 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
3323 ++Cnt) {
3324 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
3325 if (!FoundNameModifiers[NM]) {
3326 Values += "'";
3327 Values += getOpenMPDirectiveName(NM);
3328 Values += "'";
3329 if (AllowedCnt + 2 == TotalAllowedNum)
3330 Values += " or ";
3331 else if (AllowedCnt + 1 != TotalAllowedNum)
3332 Values += Sep;
3333 ++AllowedCnt;
3334 }
3335 }
Stephen Kellyf2ceec42018-08-09 21:08:08 +00003336 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getBeginLoc(),
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003337 diag::err_omp_unnamed_if_clause)
3338 << (TotalAllowedNum > 1) << Values;
3339 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003340 for (SourceLocation Loc : NameModifierLoc) {
Alexey Bataevecb156a2015-09-15 17:23:56 +00003341 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
3342 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003343 ErrorFound = true;
3344 }
3345 return ErrorFound;
3346}
3347
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003348StmtResult Sema::ActOnOpenMPExecutableDirective(
3349 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
3350 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
3351 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003352 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00003353 // First check CancelRegion which is then used in checkNestingOfRegions.
3354 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
3355 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003356 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00003357 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00003358
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003359 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataeve3727102018-04-18 15:57:46 +00003360 VarsWithInheritedDSAType VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003361 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00003362 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003363 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003364 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3365
3366 // Check default data sharing attributes for referenced variables.
3367 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003368 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3369 Stmt *S = AStmt;
3370 while (--ThisCaptureLevel >= 0)
3371 S = cast<CapturedStmt>(S)->getCapturedStmt();
3372 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003373 if (DSAChecker.isErrorFound())
3374 return StmtError();
3375 // Generate list of implicitly defined firstprivate variables.
3376 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003377
Alexey Bataev88202be2017-07-27 13:20:36 +00003378 SmallVector<Expr *, 4> ImplicitFirstprivates(
3379 DSAChecker.getImplicitFirstprivate().begin(),
3380 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003381 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3382 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003383 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +00003384 for (OMPClause *C : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00003385 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00003386 for (Expr *E : IRC->taskgroup_descriptors())
Alexey Bataev88202be2017-07-27 13:20:36 +00003387 if (E)
3388 ImplicitFirstprivates.emplace_back(E);
3389 }
3390 }
3391 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003392 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00003393 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3394 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003395 ClausesWithImplicit.push_back(Implicit);
3396 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00003397 ImplicitFirstprivates.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003398 } else {
Alexey Bataev68446b72014-07-18 07:47:19 +00003399 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003400 }
Alexey Bataev68446b72014-07-18 07:47:19 +00003401 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003402 if (!ImplicitMaps.empty()) {
3403 if (OMPClause *Implicit = ActOnOpenMPMapClause(
Kelvin Lief579432018-12-18 22:18:41 +00003404 llvm::None, llvm::None, OMPC_MAP_tofrom,
3405 /*IsMapTypeImplicit=*/true, SourceLocation(), SourceLocation(),
3406 ImplicitMaps, SourceLocation(), SourceLocation(),
3407 SourceLocation())) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003408 ClausesWithImplicit.emplace_back(Implicit);
3409 ErrorFound |=
3410 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
Alexey Bataeve3727102018-04-18 15:57:46 +00003411 } else {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003412 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00003413 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003414 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003415 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003416
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003417 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003418 switch (Kind) {
3419 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003420 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3421 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003422 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003423 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003424 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003425 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3426 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003427 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003428 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003429 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3430 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003431 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003432 case OMPD_for_simd:
3433 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3434 EndLoc, VarsWithInheritedDSA);
3435 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003436 case OMPD_sections:
3437 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3438 EndLoc);
3439 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003440 case OMPD_section:
3441 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003442 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003443 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3444 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003445 case OMPD_single:
3446 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3447 EndLoc);
3448 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003449 case OMPD_master:
3450 assert(ClausesWithImplicit.empty() &&
3451 "No clauses are allowed for 'omp master' directive");
3452 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3453 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003454 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003455 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3456 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003457 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003458 case OMPD_parallel_for:
3459 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3460 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003461 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003462 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003463 case OMPD_parallel_for_simd:
3464 Res = ActOnOpenMPParallelForSimdDirective(
3465 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003466 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003467 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003468 case OMPD_parallel_sections:
3469 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3470 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003471 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003472 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003473 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003474 Res =
3475 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003476 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003477 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003478 case OMPD_taskyield:
3479 assert(ClausesWithImplicit.empty() &&
3480 "No clauses are allowed for 'omp taskyield' directive");
3481 assert(AStmt == nullptr &&
3482 "No associated statement allowed for 'omp taskyield' directive");
3483 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3484 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003485 case OMPD_barrier:
3486 assert(ClausesWithImplicit.empty() &&
3487 "No clauses are allowed for 'omp barrier' directive");
3488 assert(AStmt == nullptr &&
3489 "No associated statement allowed for 'omp barrier' directive");
3490 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3491 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003492 case OMPD_taskwait:
3493 assert(ClausesWithImplicit.empty() &&
3494 "No clauses are allowed for 'omp taskwait' directive");
3495 assert(AStmt == nullptr &&
3496 "No associated statement allowed for 'omp taskwait' directive");
3497 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3498 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003499 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003500 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3501 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003502 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003503 case OMPD_flush:
3504 assert(AStmt == nullptr &&
3505 "No associated statement allowed for 'omp flush' directive");
3506 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3507 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003508 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003509 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3510 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003511 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003512 case OMPD_atomic:
3513 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3514 EndLoc);
3515 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003516 case OMPD_teams:
3517 Res =
3518 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3519 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003520 case OMPD_target:
3521 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3522 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003523 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003524 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003525 case OMPD_target_parallel:
3526 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3527 StartLoc, EndLoc);
3528 AllowedNameModifiers.push_back(OMPD_target);
3529 AllowedNameModifiers.push_back(OMPD_parallel);
3530 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003531 case OMPD_target_parallel_for:
3532 Res = ActOnOpenMPTargetParallelForDirective(
3533 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3534 AllowedNameModifiers.push_back(OMPD_target);
3535 AllowedNameModifiers.push_back(OMPD_parallel);
3536 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003537 case OMPD_cancellation_point:
3538 assert(ClausesWithImplicit.empty() &&
3539 "No clauses are allowed for 'omp cancellation point' directive");
3540 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3541 "cancellation point' directive");
3542 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3543 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003544 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003545 assert(AStmt == nullptr &&
3546 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003547 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3548 CancelRegion);
3549 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003550 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003551 case OMPD_target_data:
3552 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3553 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003554 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003555 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003556 case OMPD_target_enter_data:
3557 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003558 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003559 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3560 break;
Samuel Antao72590762016-01-19 20:04:50 +00003561 case OMPD_target_exit_data:
3562 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003563 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003564 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3565 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003566 case OMPD_taskloop:
3567 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3568 EndLoc, VarsWithInheritedDSA);
3569 AllowedNameModifiers.push_back(OMPD_taskloop);
3570 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003571 case OMPD_taskloop_simd:
3572 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3573 EndLoc, VarsWithInheritedDSA);
3574 AllowedNameModifiers.push_back(OMPD_taskloop);
3575 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003576 case OMPD_distribute:
3577 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3578 EndLoc, VarsWithInheritedDSA);
3579 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003580 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003581 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3582 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003583 AllowedNameModifiers.push_back(OMPD_target_update);
3584 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003585 case OMPD_distribute_parallel_for:
3586 Res = ActOnOpenMPDistributeParallelForDirective(
3587 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3588 AllowedNameModifiers.push_back(OMPD_parallel);
3589 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003590 case OMPD_distribute_parallel_for_simd:
3591 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3592 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3593 AllowedNameModifiers.push_back(OMPD_parallel);
3594 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003595 case OMPD_distribute_simd:
3596 Res = ActOnOpenMPDistributeSimdDirective(
3597 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3598 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003599 case OMPD_target_parallel_for_simd:
3600 Res = ActOnOpenMPTargetParallelForSimdDirective(
3601 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3602 AllowedNameModifiers.push_back(OMPD_target);
3603 AllowedNameModifiers.push_back(OMPD_parallel);
3604 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003605 case OMPD_target_simd:
3606 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3607 EndLoc, VarsWithInheritedDSA);
3608 AllowedNameModifiers.push_back(OMPD_target);
3609 break;
Kelvin Li02532872016-08-05 14:37:37 +00003610 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003611 Res = ActOnOpenMPTeamsDistributeDirective(
3612 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003613 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003614 case OMPD_teams_distribute_simd:
3615 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3616 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3617 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003618 case OMPD_teams_distribute_parallel_for_simd:
3619 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3620 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3621 AllowedNameModifiers.push_back(OMPD_parallel);
3622 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003623 case OMPD_teams_distribute_parallel_for:
3624 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3625 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3626 AllowedNameModifiers.push_back(OMPD_parallel);
3627 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003628 case OMPD_target_teams:
3629 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3630 EndLoc);
3631 AllowedNameModifiers.push_back(OMPD_target);
3632 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003633 case OMPD_target_teams_distribute:
3634 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3635 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3636 AllowedNameModifiers.push_back(OMPD_target);
3637 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003638 case OMPD_target_teams_distribute_parallel_for:
3639 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3640 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3641 AllowedNameModifiers.push_back(OMPD_target);
3642 AllowedNameModifiers.push_back(OMPD_parallel);
3643 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003644 case OMPD_target_teams_distribute_parallel_for_simd:
3645 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3646 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3647 AllowedNameModifiers.push_back(OMPD_target);
3648 AllowedNameModifiers.push_back(OMPD_parallel);
3649 break;
Kelvin Lida681182017-01-10 18:08:18 +00003650 case OMPD_target_teams_distribute_simd:
3651 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3652 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3653 AllowedNameModifiers.push_back(OMPD_target);
3654 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003655 case OMPD_declare_target:
3656 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003657 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003658 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003659 case OMPD_declare_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00003660 case OMPD_requires:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003661 llvm_unreachable("OpenMP Directive is not allowed");
3662 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003663 llvm_unreachable("Unknown OpenMP directive");
3664 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003665
Alexey Bataeve3727102018-04-18 15:57:46 +00003666 for (const auto &P : VarsWithInheritedDSA) {
Alexey Bataev4acb8592014-07-07 13:01:15 +00003667 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3668 << P.first << P.second->getSourceRange();
3669 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003670 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3671
3672 if (!AllowedNameModifiers.empty())
3673 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3674 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003675
Alexey Bataeved09d242014-05-28 05:53:51 +00003676 if (ErrorFound)
3677 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003678 return Res;
3679}
3680
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003681Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3682 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003683 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003684 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3685 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003686 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003687 assert(Linears.size() == LinModifiers.size());
3688 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003689 if (!DG || DG.get().isNull())
3690 return DeclGroupPtrTy();
3691
3692 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003693 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003694 return DG;
3695 }
Alexey Bataeve3727102018-04-18 15:57:46 +00003696 Decl *ADecl = DG.get().getSingleDecl();
Alexey Bataev587e1de2016-03-30 10:43:55 +00003697 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3698 ADecl = FTD->getTemplatedDecl();
3699
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003700 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3701 if (!FD) {
3702 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003703 return DeclGroupPtrTy();
3704 }
3705
Alexey Bataev2af33e32016-04-07 12:45:37 +00003706 // OpenMP [2.8.2, declare simd construct, Description]
3707 // The parameter of the simdlen clause must be a constant positive integer
3708 // expression.
3709 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003710 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003711 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003712 // OpenMP [2.8.2, declare simd construct, Description]
3713 // The special this pointer can be used as if was one of the arguments to the
3714 // function in any of the linear, aligned, or uniform clauses.
3715 // The uniform clause declares one or more arguments to have an invariant
3716 // value for all concurrent invocations of the function in the execution of a
3717 // single SIMD loop.
Alexey Bataeve3727102018-04-18 15:57:46 +00003718 llvm::DenseMap<const Decl *, const Expr *> UniformedArgs;
3719 const Expr *UniformedLinearThis = nullptr;
3720 for (const Expr *E : Uniforms) {
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003721 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003722 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3723 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003724 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3725 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003726 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
Alexey Bataev43a919f2018-04-13 17:48:43 +00003727 UniformedArgs.try_emplace(PVD->getCanonicalDecl(), E);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003728 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003729 }
3730 if (isa<CXXThisExpr>(E)) {
3731 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003732 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003733 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003734 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3735 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003736 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003737 // OpenMP [2.8.2, declare simd construct, Description]
3738 // The aligned clause declares that the object to which each list item points
3739 // is aligned to the number of bytes expressed in the optional parameter of
3740 // the aligned clause.
3741 // The special this pointer can be used as if was one of the arguments to the
3742 // function in any of the linear, aligned, or uniform clauses.
3743 // The type of list items appearing in the aligned clause must be array,
3744 // pointer, reference to array, or reference to pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +00003745 llvm::DenseMap<const Decl *, const Expr *> AlignedArgs;
3746 const Expr *AlignedThis = nullptr;
3747 for (const Expr *E : Aligneds) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003748 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003749 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3750 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3751 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevd93d3762016-04-12 09:35:56 +00003752 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3753 FD->getParamDecl(PVD->getFunctionScopeIndex())
3754 ->getCanonicalDecl() == CanonPVD) {
3755 // OpenMP [2.8.1, simd construct, Restrictions]
3756 // A list-item cannot appear in more than one aligned clause.
3757 if (AlignedArgs.count(CanonPVD) > 0) {
3758 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3759 << 1 << E->getSourceRange();
3760 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3761 diag::note_omp_explicit_dsa)
3762 << getOpenMPClauseName(OMPC_aligned);
3763 continue;
3764 }
3765 AlignedArgs[CanonPVD] = E;
3766 QualType QTy = PVD->getType()
3767 .getNonReferenceType()
3768 .getUnqualifiedType()
3769 .getCanonicalType();
3770 const Type *Ty = QTy.getTypePtrOrNull();
3771 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3772 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3773 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3774 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3775 }
3776 continue;
3777 }
3778 }
3779 if (isa<CXXThisExpr>(E)) {
3780 if (AlignedThis) {
3781 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3782 << 2 << E->getSourceRange();
3783 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3784 << getOpenMPClauseName(OMPC_aligned);
3785 }
3786 AlignedThis = E;
3787 continue;
3788 }
3789 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3790 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3791 }
3792 // The optional parameter of the aligned clause, alignment, must be a constant
3793 // positive integer expression. If no optional parameter is specified,
3794 // implementation-defined default alignments for SIMD instructions on the
3795 // target platforms are assumed.
Alexey Bataeve3727102018-04-18 15:57:46 +00003796 SmallVector<const Expr *, 4> NewAligns;
3797 for (Expr *E : Alignments) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003798 ExprResult Align;
3799 if (E)
3800 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3801 NewAligns.push_back(Align.get());
3802 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003803 // OpenMP [2.8.2, declare simd construct, Description]
3804 // The linear clause declares one or more list items to be private to a SIMD
3805 // lane and to have a linear relationship with respect to the iteration space
3806 // of a loop.
3807 // The special this pointer can be used as if was one of the arguments to the
3808 // function in any of the linear, aligned, or uniform clauses.
3809 // When a linear-step expression is specified in a linear clause it must be
3810 // either a constant integer expression or an integer-typed parameter that is
3811 // specified in a uniform clause on the directive.
Alexey Bataeve3727102018-04-18 15:57:46 +00003812 llvm::DenseMap<const Decl *, const Expr *> LinearArgs;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003813 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3814 auto MI = LinModifiers.begin();
Alexey Bataeve3727102018-04-18 15:57:46 +00003815 for (const Expr *E : Linears) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003816 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3817 ++MI;
3818 E = E->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00003819 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
3820 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3821 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00003822 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3823 FD->getParamDecl(PVD->getFunctionScopeIndex())
3824 ->getCanonicalDecl() == CanonPVD) {
3825 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3826 // A list-item cannot appear in more than one linear clause.
3827 if (LinearArgs.count(CanonPVD) > 0) {
3828 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3829 << getOpenMPClauseName(OMPC_linear)
3830 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3831 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3832 diag::note_omp_explicit_dsa)
3833 << getOpenMPClauseName(OMPC_linear);
3834 continue;
3835 }
3836 // Each argument can appear in at most one uniform or linear clause.
3837 if (UniformedArgs.count(CanonPVD) > 0) {
3838 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3839 << getOpenMPClauseName(OMPC_linear)
3840 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3841 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3842 diag::note_omp_explicit_dsa)
3843 << getOpenMPClauseName(OMPC_uniform);
3844 continue;
3845 }
3846 LinearArgs[CanonPVD] = E;
3847 if (E->isValueDependent() || E->isTypeDependent() ||
3848 E->isInstantiationDependent() ||
3849 E->containsUnexpandedParameterPack())
3850 continue;
3851 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3852 PVD->getOriginalType());
3853 continue;
3854 }
3855 }
3856 if (isa<CXXThisExpr>(E)) {
3857 if (UniformedLinearThis) {
3858 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3859 << getOpenMPClauseName(OMPC_linear)
3860 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3861 << E->getSourceRange();
3862 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3863 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3864 : OMPC_linear);
3865 continue;
3866 }
3867 UniformedLinearThis = E;
3868 if (E->isValueDependent() || E->isTypeDependent() ||
3869 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3870 continue;
3871 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3872 E->getType());
3873 continue;
3874 }
3875 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3876 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3877 }
3878 Expr *Step = nullptr;
3879 Expr *NewStep = nullptr;
3880 SmallVector<Expr *, 4> NewSteps;
Alexey Bataeve3727102018-04-18 15:57:46 +00003881 for (Expr *E : Steps) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003882 // Skip the same step expression, it was checked already.
3883 if (Step == E || !E) {
3884 NewSteps.push_back(E ? NewStep : nullptr);
3885 continue;
3886 }
3887 Step = E;
Alexey Bataeve3727102018-04-18 15:57:46 +00003888 if (const auto *DRE = dyn_cast<DeclRefExpr>(Step))
3889 if (const auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3890 const VarDecl *CanonPVD = PVD->getCanonicalDecl();
Alexey Bataevecba70f2016-04-12 11:02:11 +00003891 if (UniformedArgs.count(CanonPVD) == 0) {
3892 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3893 << Step->getSourceRange();
3894 } else if (E->isValueDependent() || E->isTypeDependent() ||
3895 E->isInstantiationDependent() ||
3896 E->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00003897 CanonPVD->getType()->hasIntegerRepresentation()) {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003898 NewSteps.push_back(Step);
Alexey Bataeve3727102018-04-18 15:57:46 +00003899 } else {
Alexey Bataevecba70f2016-04-12 11:02:11 +00003900 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3901 << Step->getSourceRange();
3902 }
3903 continue;
3904 }
3905 NewStep = Step;
3906 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3907 !Step->isInstantiationDependent() &&
3908 !Step->containsUnexpandedParameterPack()) {
3909 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3910 .get();
3911 if (NewStep)
3912 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3913 }
3914 NewSteps.push_back(NewStep);
3915 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003916 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3917 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003918 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003919 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3920 const_cast<Expr **>(Linears.data()), Linears.size(),
3921 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3922 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003923 ADecl->addAttr(NewAttr);
3924 return ConvertDeclToDeclGroup(ADecl);
3925}
3926
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003927StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3928 Stmt *AStmt,
3929 SourceLocation StartLoc,
3930 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003931 if (!AStmt)
3932 return StmtError();
3933
Alexey Bataeve3727102018-04-18 15:57:46 +00003934 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9959db52014-05-06 10:08:46 +00003935 // 1.2.2 OpenMP Language Terminology
3936 // Structured block - An executable statement with a single entry at the
3937 // top and a single exit at the bottom.
3938 // The point of exit cannot be a branch out of the structured block.
3939 // longjmp() and throw() must not violate the entry/exit criteria.
3940 CS->getCapturedDecl()->setNothrow();
3941
Reid Kleckner87a31802018-03-12 21:43:02 +00003942 setFunctionHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003943
Alexey Bataev25e5b442015-09-15 12:52:43 +00003944 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3945 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003946}
3947
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003948namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003949/// Helper class for checking canonical form of the OpenMP loops and
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003950/// extracting iteration space of each loop in the loop nest, that will be used
3951/// for IR generation.
3952class OpenMPIterationSpaceChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003953 /// Reference to Sema.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003954 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003955 /// A location for diagnostics (when there is no some better location).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003956 SourceLocation DefaultLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003957 /// A location for diagnostics (when increment is not compatible).
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003958 SourceLocation ConditionLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003959 /// A source location for referring to loop init later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003960 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003961 /// A source location for referring to condition later.
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003962 SourceRange ConditionSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003963 /// A source location for referring to increment later.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003964 SourceRange IncrementSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003965 /// Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003966 ValueDecl *LCDecl = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003967 /// Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003968 Expr *LCRef = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003969 /// Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003970 Expr *LB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003971 /// Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003972 Expr *UB = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003973 /// Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003974 Expr *Step = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003975 /// This flag is true when condition is one of:
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003976 /// Var < UB
3977 /// Var <= UB
3978 /// UB > Var
3979 /// UB >= Var
Kelvin Liefbe4af2018-11-21 19:10:48 +00003980 /// This will have no value when the condition is !=
3981 llvm::Optional<bool> TestIsLessOp;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003982 /// This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003983 bool TestIsStrictOp = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003984 /// This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003985 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003986
3987public:
3988 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003989 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003990 /// Check init-expr for canonical loop form and save loop counter
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003991 /// variable - #Var and its initialization value - #LB.
Alexey Bataeve3727102018-04-18 15:57:46 +00003992 bool checkAndSetInit(Stmt *S, bool EmitDiags = true);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003993 /// Check test-expr for canonical form, save upper-bound (#UB), flags
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003994 /// for less/greater and for strict/non-strict comparison.
Alexey Bataeve3727102018-04-18 15:57:46 +00003995 bool checkAndSetCond(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003996 /// Check incr-expr for canonical loop form and return true if it
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003997 /// does not conform, otherwise save loop step (#Step).
Alexey Bataeve3727102018-04-18 15:57:46 +00003998 bool checkAndSetInc(Expr *S);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003999 /// Return the loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004000 ValueDecl *getLoopDecl() const { return LCDecl; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004001 /// Return the reference expression to loop counter variable.
Alexey Bataeve3727102018-04-18 15:57:46 +00004002 Expr *getLoopDeclRefExpr() const { return LCRef; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004003 /// Source range of the loop init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004004 SourceRange getInitSrcRange() const { return InitSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004005 /// Source range of the loop condition.
Alexey Bataeve3727102018-04-18 15:57:46 +00004006 SourceRange getConditionSrcRange() const { return ConditionSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004007 /// Source range of the loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004008 SourceRange getIncrementSrcRange() const { return IncrementSrcRange; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004009 /// True if the step should be subtracted.
Alexey Bataeve3727102018-04-18 15:57:46 +00004010 bool shouldSubtractStep() const { return SubtractStep; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004011 /// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004012 Expr *buildNumIterations(
4013 Scope *S, const bool LimitedType,
4014 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004015 /// Build the precondition expression for the loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00004016 Expr *
4017 buildPreCond(Scope *S, Expr *Cond,
4018 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004019 /// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004020 DeclRefExpr *
4021 buildCounterVar(llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4022 DSAStackTy &DSA) const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004023 /// Build reference expression to the private counter be used for
Alexey Bataeva8899172015-08-06 12:30:57 +00004024 /// codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004025 Expr *buildPrivateCounterVar() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004026 /// Build initialization of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004027 Expr *buildCounterInit() const;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004028 /// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004029 Expr *buildCounterStep() const;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004030 /// Build loop data with counter value for depend clauses in ordered
4031 /// directives.
4032 Expr *
4033 buildOrderedLoopData(Scope *S, Expr *Counter,
4034 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4035 SourceLocation Loc, Expr *Inc = nullptr,
4036 OverloadedOperatorKind OOK = OO_Amp);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004037 /// Return true if any expression is dependent.
Alexey Bataeve3727102018-04-18 15:57:46 +00004038 bool dependent() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004039
4040private:
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004041 /// Check the right-hand side of an assignment in the increment
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004042 /// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +00004043 bool checkAndSetIncRHS(Expr *RHS);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004044 /// Helper to set loop counter variable and its initializer.
Alexey Bataeve3727102018-04-18 15:57:46 +00004045 bool setLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004046 /// Helper to set upper bound.
Kelvin Liefbe4af2018-11-21 19:10:48 +00004047 bool setUB(Expr *NewUB, llvm::Optional<bool> LessOp, bool StrictOp,
4048 SourceRange SR, SourceLocation SL);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004049 /// Helper to set loop increment.
Alexey Bataeve3727102018-04-18 15:57:46 +00004050 bool setStep(Expr *NewStep, bool Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004051};
4052
Alexey Bataeve3727102018-04-18 15:57:46 +00004053bool OpenMPIterationSpaceChecker::dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004054 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004055 assert(!LB && !UB && !Step);
4056 return false;
4057 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004058 return LCDecl->getType()->isDependentType() ||
4059 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
4060 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004061}
4062
Alexey Bataeve3727102018-04-18 15:57:46 +00004063bool OpenMPIterationSpaceChecker::setLCDeclAndLB(ValueDecl *NewLCDecl,
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004064 Expr *NewLCRefExpr,
4065 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004066 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004067 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00004068 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004069 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004070 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004071 LCDecl = getCanonicalDecl(NewLCDecl);
4072 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004073 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
4074 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004075 if ((Ctor->isCopyOrMoveConstructor() ||
4076 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4077 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004078 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004079 LB = NewLB;
4080 return false;
4081}
4082
Kelvin Liefbe4af2018-11-21 19:10:48 +00004083bool OpenMPIterationSpaceChecker::setUB(Expr *NewUB, llvm::Optional<bool> LessOp,
4084 bool StrictOp, SourceRange SR,
4085 SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004086 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004087 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
4088 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004089 if (!NewUB)
4090 return true;
4091 UB = NewUB;
Kelvin Liefbe4af2018-11-21 19:10:48 +00004092 if (LessOp)
4093 TestIsLessOp = LessOp;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004094 TestIsStrictOp = StrictOp;
4095 ConditionSrcRange = SR;
4096 ConditionLoc = SL;
4097 return false;
4098}
4099
Alexey Bataeve3727102018-04-18 15:57:46 +00004100bool OpenMPIterationSpaceChecker::setStep(Expr *NewStep, bool Subtract) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004101 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004102 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004103 if (!NewStep)
4104 return true;
4105 if (!NewStep->isValueDependent()) {
4106 // Check that the step is integer expression.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004107 SourceLocation StepLoc = NewStep->getBeginLoc();
Alexey Bataev5372fb82017-08-31 23:06:52 +00004108 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
4109 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004110 if (Val.isInvalid())
4111 return true;
4112 NewStep = Val.get();
4113
4114 // OpenMP [2.6, Canonical Loop Form, Restrictions]
4115 // If test-expr is of form var relational-op b and relational-op is < or
4116 // <= then incr-expr must cause var to increase on each iteration of the
4117 // loop. If test-expr is of form var relational-op b and relational-op is
4118 // > or >= then incr-expr must cause var to decrease on each iteration of
4119 // the loop.
4120 // If test-expr is of form b relational-op var and relational-op is < or
4121 // <= then incr-expr must cause var to decrease on each iteration of the
4122 // loop. If test-expr is of form b relational-op var and relational-op is
4123 // > or >= then incr-expr must cause var to increase on each iteration of
4124 // the loop.
4125 llvm::APSInt Result;
4126 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
4127 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
4128 bool IsConstNeg =
4129 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004130 bool IsConstPos =
4131 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004132 bool IsConstZero = IsConstant && !Result.getBoolValue();
Kelvin Liefbe4af2018-11-21 19:10:48 +00004133
4134 // != with increment is treated as <; != with decrement is treated as >
4135 if (!TestIsLessOp.hasValue())
4136 TestIsLessOp = IsConstPos || (IsUnsigned && !Subtract);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004137 if (UB && (IsConstZero ||
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004138 (TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004139 (IsConstNeg || (IsUnsigned && Subtract)) :
4140 (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004141 SemaRef.Diag(NewStep->getExprLoc(),
4142 diag::err_omp_loop_incr_not_compatible)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004143 << LCDecl << TestIsLessOp.getValue() << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004144 SemaRef.Diag(ConditionLoc,
4145 diag::note_omp_loop_cond_requres_compatible_incr)
Kelvin Liefbe4af2018-11-21 19:10:48 +00004146 << TestIsLessOp.getValue() << ConditionSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004147 return true;
4148 }
Kelvin Liefbe4af2018-11-21 19:10:48 +00004149 if (TestIsLessOp.getValue() == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00004150 NewStep =
4151 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
4152 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004153 Subtract = !Subtract;
4154 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004155 }
4156
4157 Step = NewStep;
4158 SubtractStep = Subtract;
4159 return false;
4160}
4161
Alexey Bataeve3727102018-04-18 15:57:46 +00004162bool OpenMPIterationSpaceChecker::checkAndSetInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004163 // Check init-expr for canonical loop form and save loop counter
4164 // variable - #Var and its initialization value - #LB.
4165 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
4166 // var = lb
4167 // integer-type var = lb
4168 // random-access-iterator-type var = lb
4169 // pointer-type var = lb
4170 //
4171 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00004172 if (EmitDiags) {
4173 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
4174 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004175 return true;
4176 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004177 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4178 if (!ExprTemp->cleanupsHaveSideEffects())
4179 S = ExprTemp->getSubExpr();
4180
Alexander Musmana5f070a2014-10-01 06:03:56 +00004181 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004182 if (Expr *E = dyn_cast<Expr>(S))
4183 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004184 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004185 if (BO->getOpcode() == BO_Assign) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004186 Expr *LHS = BO->getLHS()->IgnoreParens();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004187 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
4188 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4189 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004190 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4191 return setLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004192 }
4193 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4194 if (ME->isArrow() &&
4195 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004196 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004197 }
4198 }
David Majnemer9d168222016-08-05 17:44:54 +00004199 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004200 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00004201 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00004202 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004203 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00004204 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004205 SemaRef.Diag(S->getBeginLoc(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004206 diag::ext_omp_loop_not_canonical_init)
4207 << S->getSourceRange();
Alexey Bataevf138fda2018-08-13 19:04:24 +00004208 return setLCDeclAndLB(
4209 Var,
4210 buildDeclRefExpr(SemaRef, Var,
4211 Var->getType().getNonReferenceType(),
4212 DS->getBeginLoc()),
4213 Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004214 }
4215 }
4216 }
David Majnemer9d168222016-08-05 17:44:54 +00004217 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004218 if (CE->getOperator() == OO_Equal) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004219 Expr *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00004220 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004221 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
4222 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
Alexey Bataeve3727102018-04-18 15:57:46 +00004223 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
4224 return setLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004225 }
4226 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
4227 if (ME->isArrow() &&
4228 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
Alexey Bataeve3727102018-04-18 15:57:46 +00004229 return setLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004230 }
4231 }
4232 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004233
Alexey Bataeve3727102018-04-18 15:57:46 +00004234 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004235 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00004236 if (EmitDiags) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004237 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_init)
Alexey Bataev9c821032015-04-30 04:23:23 +00004238 << S->getSourceRange();
4239 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004240 return true;
4241}
4242
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004243/// Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004244/// variable (which may be the loop variable) if possible.
Alexey Bataeve3727102018-04-18 15:57:46 +00004245static const ValueDecl *getInitLCDecl(const Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004246 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00004247 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004248 E = getExprAsWritten(E);
Alexey Bataeve3727102018-04-18 15:57:46 +00004249 if (const auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004250 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00004251 if ((Ctor->isCopyOrMoveConstructor() ||
4252 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
4253 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004254 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00004255 if (const auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
4256 if (const auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004257 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004258 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004259 if (const auto *ME = dyn_cast_or_null<MemberExpr>(E))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004260 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
4261 return getCanonicalDecl(ME->getMemberDecl());
4262 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004263}
4264
Alexey Bataeve3727102018-04-18 15:57:46 +00004265bool OpenMPIterationSpaceChecker::checkAndSetCond(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004266 // Check test-expr for canonical form, save upper-bound UB, flags for
4267 // less/greater and for strict/non-strict comparison.
4268 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4269 // var relational-op b
4270 // b relational-op var
4271 //
4272 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004273 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004274 return true;
4275 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004276 S = getExprAsWritten(S);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004277 SourceLocation CondLoc = S->getBeginLoc();
David Majnemer9d168222016-08-05 17:44:54 +00004278 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004279 if (BO->isRelationalOp()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004280 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4281 return setUB(BO->getRHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004282 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
4283 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4284 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004285 if (getInitLCDecl(BO->getRHS()) == LCDecl)
4286 return setUB(BO->getLHS(),
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004287 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
4288 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
4289 BO->getSourceRange(), BO->getOperatorLoc());
Kelvin Liefbe4af2018-11-21 19:10:48 +00004290 } else if (BO->getOpcode() == BO_NE)
4291 return setUB(getInitLCDecl(BO->getLHS()) == LCDecl ?
4292 BO->getRHS() : BO->getLHS(),
4293 /*LessOp=*/llvm::None,
4294 /*StrictOp=*/true,
4295 BO->getSourceRange(), BO->getOperatorLoc());
David Majnemer9d168222016-08-05 17:44:54 +00004296 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004297 if (CE->getNumArgs() == 2) {
4298 auto Op = CE->getOperator();
4299 switch (Op) {
4300 case OO_Greater:
4301 case OO_GreaterEqual:
4302 case OO_Less:
4303 case OO_LessEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004304 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4305 return setUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004306 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4307 CE->getOperatorLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +00004308 if (getInitLCDecl(CE->getArg(1)) == LCDecl)
4309 return setUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004310 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
4311 CE->getOperatorLoc());
4312 break;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004313 case OO_ExclaimEqual:
Kelvin Liefbe4af2018-11-21 19:10:48 +00004314 return setUB(getInitLCDecl(CE->getArg(0)) == LCDecl ?
4315 CE->getArg(1) : CE->getArg(0),
4316 /*LessOp=*/llvm::None,
4317 /*StrictOp=*/true,
4318 CE->getSourceRange(),
4319 CE->getOperatorLoc());
4320 break;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004321 default:
4322 break;
4323 }
4324 }
4325 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004326 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004327 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004328 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004329 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004330 return true;
4331}
4332
Alexey Bataeve3727102018-04-18 15:57:46 +00004333bool OpenMPIterationSpaceChecker::checkAndSetIncRHS(Expr *RHS) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004334 // RHS of canonical loop form increment can be:
4335 // var + incr
4336 // incr + var
4337 // var - incr
4338 //
4339 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00004340 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004341 if (BO->isAdditiveOp()) {
4342 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataeve3727102018-04-18 15:57:46 +00004343 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4344 return setStep(BO->getRHS(), !IsAdd);
4345 if (IsAdd && getInitLCDecl(BO->getRHS()) == LCDecl)
4346 return setStep(BO->getLHS(), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004347 }
David Majnemer9d168222016-08-05 17:44:54 +00004348 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004349 bool IsAdd = CE->getOperator() == OO_Plus;
4350 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004351 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4352 return setStep(CE->getArg(1), !IsAdd);
4353 if (IsAdd && getInitLCDecl(CE->getArg(1)) == LCDecl)
4354 return setStep(CE->getArg(0), /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004355 }
4356 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004357 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004358 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004359 SemaRef.Diag(RHS->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004360 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004361 return true;
4362}
4363
Alexey Bataeve3727102018-04-18 15:57:46 +00004364bool OpenMPIterationSpaceChecker::checkAndSetInc(Expr *S) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004365 // Check incr-expr for canonical loop form and return true if it
4366 // does not conform.
4367 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
4368 // ++var
4369 // var++
4370 // --var
4371 // var--
4372 // var += incr
4373 // var -= incr
4374 // var = var + incr
4375 // var = incr + var
4376 // var = var - incr
4377 //
4378 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004379 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004380 return true;
4381 }
Tim Shen4a05bb82016-06-21 20:29:17 +00004382 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
4383 if (!ExprTemp->cleanupsHaveSideEffects())
4384 S = ExprTemp->getSubExpr();
4385
Alexander Musmana5f070a2014-10-01 06:03:56 +00004386 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004387 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00004388 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004389 if (UO->isIncrementDecrementOp() &&
Alexey Bataeve3727102018-04-18 15:57:46 +00004390 getInitLCDecl(UO->getSubExpr()) == LCDecl)
4391 return setStep(SemaRef
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004392 .ActOnIntegerConstant(UO->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004393 (UO->isDecrementOp() ? -1 : 1))
4394 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004395 /*Subtract=*/false);
David Majnemer9d168222016-08-05 17:44:54 +00004396 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004397 switch (BO->getOpcode()) {
4398 case BO_AddAssign:
4399 case BO_SubAssign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004400 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4401 return setStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004402 break;
4403 case BO_Assign:
Alexey Bataeve3727102018-04-18 15:57:46 +00004404 if (getInitLCDecl(BO->getLHS()) == LCDecl)
4405 return checkAndSetIncRHS(BO->getRHS());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004406 break;
4407 default:
4408 break;
4409 }
David Majnemer9d168222016-08-05 17:44:54 +00004410 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004411 switch (CE->getOperator()) {
4412 case OO_PlusPlus:
4413 case OO_MinusMinus:
Alexey Bataeve3727102018-04-18 15:57:46 +00004414 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4415 return setStep(SemaRef
David Majnemer9d168222016-08-05 17:44:54 +00004416 .ActOnIntegerConstant(
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004417 CE->getBeginLoc(),
David Majnemer9d168222016-08-05 17:44:54 +00004418 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4419 .get(),
Alexey Bataeve3727102018-04-18 15:57:46 +00004420 /*Subtract=*/false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004421 break;
4422 case OO_PlusEqual:
4423 case OO_MinusEqual:
Alexey Bataeve3727102018-04-18 15:57:46 +00004424 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4425 return setStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004426 break;
4427 case OO_Equal:
Alexey Bataeve3727102018-04-18 15:57:46 +00004428 if (getInitLCDecl(CE->getArg(0)) == LCDecl)
4429 return checkAndSetIncRHS(CE->getArg(1));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004430 break;
4431 default:
4432 break;
4433 }
4434 }
Alexey Bataeve3727102018-04-18 15:57:46 +00004435 if (dependent() || SemaRef.CurContext->isDependentContext())
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004436 return false;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004437 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004438 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004439 return true;
4440}
Alexander Musmana5f070a2014-10-01 06:03:56 +00004441
Alexey Bataev5a3af132016-03-29 08:58:54 +00004442static ExprResult
4443tryBuildCapture(Sema &SemaRef, Expr *Capture,
Alexey Bataeve3727102018-04-18 15:57:46 +00004444 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00004445 if (SemaRef.CurContext->isDependentContext())
4446 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004447 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4448 return SemaRef.PerformImplicitConversion(
4449 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4450 /*AllowExplicit=*/true);
4451 auto I = Captures.find(Capture);
4452 if (I != Captures.end())
4453 return buildCapture(SemaRef, Capture, I->second);
4454 DeclRefExpr *Ref = nullptr;
4455 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4456 Captures[Capture] = Ref;
4457 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004458}
4459
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004460/// Build the expression to calculate the number of iterations.
Alexey Bataeve3727102018-04-18 15:57:46 +00004461Expr *OpenMPIterationSpaceChecker::buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004462 Scope *S, const bool LimitedType,
Alexey Bataeve3727102018-04-18 15:57:46 +00004463 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004464 ExprResult Diff;
Alexey Bataeve3727102018-04-18 15:57:46 +00004465 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004466 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004467 SemaRef.getLangOpts().CPlusPlus) {
4468 // Upper - Lower
Kelvin Liefbe4af2018-11-21 19:10:48 +00004469 Expr *UBExpr = TestIsLessOp.getValue() ? UB : LB;
4470 Expr *LBExpr = TestIsLessOp.getValue() ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004471 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4472 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004473 if (!Upper || !Lower)
4474 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004475
4476 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4477
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004478 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004479 // BuildBinOp already emitted error, this one is to point user to upper
4480 // and lower bound, and to tell what is passed to 'operator-'.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004481 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004482 << Upper->getSourceRange() << Lower->getSourceRange();
4483 return nullptr;
4484 }
4485 }
4486
4487 if (!Diff.isUsable())
4488 return nullptr;
4489
4490 // Upper - Lower [- 1]
4491 if (TestIsStrictOp)
4492 Diff = SemaRef.BuildBinOp(
4493 S, DefaultLoc, BO_Sub, Diff.get(),
4494 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4495 if (!Diff.isUsable())
4496 return nullptr;
4497
4498 // Upper - Lower [- 1] + Step
Alexey Bataeve3727102018-04-18 15:57:46 +00004499 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004500 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004501 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004502 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004503 if (!Diff.isUsable())
4504 return nullptr;
4505
4506 // Parentheses (for dumping/debugging purposes only).
4507 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4508 if (!Diff.isUsable())
4509 return nullptr;
4510
4511 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004512 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004513 if (!Diff.isUsable())
4514 return nullptr;
4515
Alexander Musman174b3ca2014-10-06 11:16:29 +00004516 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004517 QualType Type = Diff.get()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +00004518 ASTContext &C = SemaRef.Context;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004519 bool UseVarType = VarType->hasIntegerRepresentation() &&
4520 C.getTypeSize(Type) > C.getTypeSize(VarType);
4521 if (!Type->isIntegerType() || UseVarType) {
4522 unsigned NewSize =
4523 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4524 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4525 : Type->hasSignedIntegerRepresentation();
4526 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004527 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4528 Diff = SemaRef.PerformImplicitConversion(
4529 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4530 if (!Diff.isUsable())
4531 return nullptr;
4532 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004533 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004534 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004535 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4536 if (NewSize != C.getTypeSize(Type)) {
4537 if (NewSize < C.getTypeSize(Type)) {
4538 assert(NewSize == 64 && "incorrect loop var size");
4539 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4540 << InitSrcRange << ConditionSrcRange;
4541 }
4542 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004543 NewSize, Type->hasSignedIntegerRepresentation() ||
4544 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004545 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4546 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4547 Sema::AA_Converting, true);
4548 if (!Diff.isUsable())
4549 return nullptr;
4550 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004551 }
4552 }
4553
Alexander Musmana5f070a2014-10-01 06:03:56 +00004554 return Diff.get();
4555}
4556
Alexey Bataeve3727102018-04-18 15:57:46 +00004557Expr *OpenMPIterationSpaceChecker::buildPreCond(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004558 Scope *S, Expr *Cond,
Alexey Bataeve3727102018-04-18 15:57:46 +00004559 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004560 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4561 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4562 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004563
Alexey Bataeve3727102018-04-18 15:57:46 +00004564 ExprResult NewLB = tryBuildCapture(SemaRef, LB, Captures);
4565 ExprResult NewUB = tryBuildCapture(SemaRef, UB, Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004566 if (!NewLB.isUsable() || !NewUB.isUsable())
4567 return nullptr;
4568
Alexey Bataeve3727102018-04-18 15:57:46 +00004569 ExprResult CondExpr =
4570 SemaRef.BuildBinOp(S, DefaultLoc,
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00004571 TestIsLessOp.getValue() ?
Kelvin Liefbe4af2018-11-21 19:10:48 +00004572 (TestIsStrictOp ? BO_LT : BO_LE) :
4573 (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataeve3727102018-04-18 15:57:46 +00004574 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004575 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004576 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4577 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004578 CondExpr = SemaRef.PerformImplicitConversion(
4579 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4580 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004581 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004582 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4583 // Otherwise use original loop conditon and evaluate it in runtime.
4584 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4585}
4586
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004587/// Build reference expression to the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004588DeclRefExpr *OpenMPIterationSpaceChecker::buildCounterVar(
Alexey Bataevf138fda2018-08-13 19:04:24 +00004589 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures,
4590 DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004591 auto *VD = dyn_cast<VarDecl>(LCDecl);
4592 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004593 VD = SemaRef.isOpenMPCapturedDecl(LCDecl);
4594 DeclRefExpr *Ref = buildDeclRefExpr(
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004595 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004596 const DSAStackTy::DSAVarData Data =
4597 DSA.getTopDSA(LCDecl, /*FromParent=*/false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004598 // If the loop control decl is explicitly marked as private, do not mark it
4599 // as captured again.
4600 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4601 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004602 return Ref;
4603 }
4604 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004605 DefaultLoc);
4606}
4607
Alexey Bataeve3727102018-04-18 15:57:46 +00004608Expr *OpenMPIterationSpaceChecker::buildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004609 if (LCDecl && !LCDecl->isInvalidDecl()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004610 QualType Type = LCDecl->getType().getNonReferenceType();
4611 VarDecl *PrivateVar = buildVarDecl(
Alexey Bataev63cc8e92018-03-20 14:45:59 +00004612 SemaRef, DefaultLoc, Type, LCDecl->getName(),
4613 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr,
4614 isa<VarDecl>(LCDecl)
4615 ? buildDeclRefExpr(SemaRef, cast<VarDecl>(LCDecl), Type, DefaultLoc)
4616 : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004617 if (PrivateVar->isInvalidDecl())
4618 return nullptr;
4619 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4620 }
4621 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004622}
4623
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004624/// Build initialization of the counter to be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004625Expr *OpenMPIterationSpaceChecker::buildCounterInit() const { return LB; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004626
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004627/// Build step of the counter be used for codegen.
Alexey Bataeve3727102018-04-18 15:57:46 +00004628Expr *OpenMPIterationSpaceChecker::buildCounterStep() const { return Step; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004629
Alexey Bataevf138fda2018-08-13 19:04:24 +00004630Expr *OpenMPIterationSpaceChecker::buildOrderedLoopData(
4631 Scope *S, Expr *Counter,
4632 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures, SourceLocation Loc,
4633 Expr *Inc, OverloadedOperatorKind OOK) {
4634 Expr *Cnt = SemaRef.DefaultLvalueConversion(Counter).get();
4635 if (!Cnt)
4636 return nullptr;
4637 if (Inc) {
4638 assert((OOK == OO_Plus || OOK == OO_Minus) &&
4639 "Expected only + or - operations for depend clauses.");
4640 BinaryOperatorKind BOK = (OOK == OO_Plus) ? BO_Add : BO_Sub;
4641 Cnt = SemaRef.BuildBinOp(S, Loc, BOK, Cnt, Inc).get();
4642 if (!Cnt)
4643 return nullptr;
4644 }
4645 ExprResult Diff;
4646 QualType VarType = LCDecl->getType().getNonReferenceType();
4647 if (VarType->isIntegerType() || VarType->isPointerType() ||
4648 SemaRef.getLangOpts().CPlusPlus) {
4649 // Upper - Lower
4650 Expr *Upper =
Kelvin Liefbe4af2018-11-21 19:10:48 +00004651 TestIsLessOp.getValue() ? Cnt : tryBuildCapture(SemaRef, UB, Captures).get();
Alexey Bataevf138fda2018-08-13 19:04:24 +00004652 Expr *Lower =
Kelvin Liefbe4af2018-11-21 19:10:48 +00004653 TestIsLessOp.getValue() ? tryBuildCapture(SemaRef, LB, Captures).get() : Cnt;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004654 if (!Upper || !Lower)
4655 return nullptr;
4656
4657 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4658
4659 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
4660 // BuildBinOp already emitted error, this one is to point user to upper
4661 // and lower bound, and to tell what is passed to 'operator-'.
4662 SemaRef.Diag(Upper->getBeginLoc(), diag::err_omp_loop_diff_cxx)
4663 << Upper->getSourceRange() << Lower->getSourceRange();
4664 return nullptr;
4665 }
4666 }
4667
4668 if (!Diff.isUsable())
4669 return nullptr;
4670
4671 // Parentheses (for dumping/debugging purposes only).
4672 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4673 if (!Diff.isUsable())
4674 return nullptr;
4675
4676 ExprResult NewStep = tryBuildCapture(SemaRef, Step, Captures);
4677 if (!NewStep.isUsable())
4678 return nullptr;
4679 // (Upper - Lower) / Step
4680 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
4681 if (!Diff.isUsable())
4682 return nullptr;
4683
4684 return Diff.get();
4685}
4686
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004687/// Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004688struct LoopIterationSpace final {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004689 /// Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004690 Expr *PreCond = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004691 /// This expression calculates the number of iterations in the loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004692 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004693 Expr *NumIterations = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004694 /// The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004695 Expr *CounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004696 /// Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004697 Expr *PrivateCounterVar = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004698 /// This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004699 Expr *CounterInit = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004700 /// This is step for the #CounterVar used to generate its update:
Alexander Musmana5f070a2014-10-01 06:03:56 +00004701 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004702 Expr *CounterStep = nullptr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004703 /// Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004704 bool Subtract = false;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004705 /// Source range of the loop init.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004706 SourceRange InitSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004707 /// Source range of the loop condition.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004708 SourceRange CondSrcRange;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004709 /// Source range of the loop increment.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004710 SourceRange IncSrcRange;
4711};
4712
Alexey Bataev23b69422014-06-18 07:08:49 +00004713} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004714
Alexey Bataev9c821032015-04-30 04:23:23 +00004715void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4716 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4717 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004718 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4719 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004720 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevce901812018-12-19 18:16:37 +00004721 DSAStack->loopStart();
Alexey Bataev9c821032015-04-30 04:23:23 +00004722 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataeve3727102018-04-18 15:57:46 +00004723 if (!ISC.checkAndSetInit(Init, /*EmitDiags=*/false)) {
4724 if (ValueDecl *D = ISC.getLoopDecl()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004725 auto *VD = dyn_cast<VarDecl>(D);
4726 if (!VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +00004727 if (VarDecl *Private = isOpenMPCapturedDecl(D)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004728 VD = Private;
Alexey Bataeve3727102018-04-18 15:57:46 +00004729 } else {
4730 DeclRefExpr *Ref = buildCapture(*this, D, ISC.getLoopDeclRefExpr(),
4731 /*WithInit=*/false);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004732 VD = cast<VarDecl>(Ref->getDecl());
4733 }
4734 }
4735 DSAStack->addLoopControlVariable(D, VD);
Alexey Bataev6ab5bb12018-10-29 15:01:58 +00004736 const Decl *LD = DSAStack->getPossiblyLoopCunter();
4737 if (LD != D->getCanonicalDecl()) {
4738 DSAStack->resetPossibleLoopCounter();
4739 if (auto *Var = dyn_cast_or_null<VarDecl>(LD))
4740 MarkDeclarationsReferencedInExpr(
4741 buildDeclRefExpr(*this, const_cast<VarDecl *>(Var),
4742 Var->getType().getNonLValueExprType(Context),
4743 ForLoc, /*RefersToCapture=*/true));
4744 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004745 }
4746 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004747 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004748 }
4749}
4750
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004751/// Called on a for stmt to check and extract its iteration space
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004752/// for further processing (such as collapsing).
Alexey Bataeve3727102018-04-18 15:57:46 +00004753static bool checkOpenMPIterationSpace(
Alexey Bataev4acb8592014-07-07 13:01:15 +00004754 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4755 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataevf138fda2018-08-13 19:04:24 +00004756 unsigned TotalNestedLoopCount, Expr *CollapseLoopCountExpr,
4757 Expr *OrderedLoopCountExpr,
Alexey Bataeve3727102018-04-18 15:57:46 +00004758 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004759 LoopIterationSpace &ResultIterSpace,
Alexey Bataeve3727102018-04-18 15:57:46 +00004760 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004761 // OpenMP [2.6, Canonical Loop Form]
4762 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004763 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004764 if (!For) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004765 SemaRef.Diag(S->getBeginLoc(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004766 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
Alexey Bataevf138fda2018-08-13 19:04:24 +00004767 << getOpenMPDirectiveName(DKind) << TotalNestedLoopCount
Alexey Bataev10e775f2015-07-30 11:36:16 +00004768 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
Alexey Bataevf138fda2018-08-13 19:04:24 +00004769 if (TotalNestedLoopCount > 1) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00004770 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4771 SemaRef.Diag(DSA.getConstructLoc(),
4772 diag::note_omp_collapse_ordered_expr)
4773 << 2 << CollapseLoopCountExpr->getSourceRange()
4774 << OrderedLoopCountExpr->getSourceRange();
4775 else if (CollapseLoopCountExpr)
4776 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4777 diag::note_omp_collapse_ordered_expr)
4778 << 0 << CollapseLoopCountExpr->getSourceRange();
4779 else
4780 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4781 diag::note_omp_collapse_ordered_expr)
4782 << 1 << OrderedLoopCountExpr->getSourceRange();
4783 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004784 return true;
4785 }
4786 assert(For->getBody());
4787
4788 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4789
4790 // Check init.
Alexey Bataeve3727102018-04-18 15:57:46 +00004791 Stmt *Init = For->getInit();
4792 if (ISC.checkAndSetInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004793 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004794
4795 bool HasErrors = false;
4796
4797 // Check loop variable's type.
Alexey Bataeve3727102018-04-18 15:57:46 +00004798 if (ValueDecl *LCDecl = ISC.getLoopDecl()) {
4799 Expr *LoopDeclRefExpr = ISC.getLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004800
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004801 // OpenMP [2.6, Canonical Loop Form]
4802 // Var is one of the following:
4803 // A variable of signed or unsigned integer type.
4804 // For C++, a variable of a random access iterator type.
4805 // For C, a variable of a pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +00004806 QualType VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004807 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4808 !VarType->isPointerType() &&
4809 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004810 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_variable_type)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004811 << SemaRef.getLangOpts().CPlusPlus;
4812 HasErrors = true;
4813 }
4814
4815 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4816 // a Construct
4817 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4818 // parallel for construct is (are) private.
4819 // The loop iteration variable in the associated for-loop of a simd
4820 // construct with just one associated for-loop is linear with a
4821 // constant-linear-step that is the increment of the associated for-loop.
4822 // Exclude loop var from the list of variables with implicitly defined data
4823 // sharing attributes.
4824 VarsWithImplicitDSA.erase(LCDecl);
4825
4826 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4827 // in a Construct, C/C++].
4828 // The loop iteration variable in the associated for-loop of a simd
4829 // construct with just one associated for-loop may be listed in a linear
4830 // clause with a constant-linear-step that is the increment of the
4831 // associated for-loop.
4832 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4833 // parallel for construct may be listed in a private or lastprivate clause.
4834 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4835 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4836 // declared in the loop and it is predetermined as a private.
Alexey Bataeve3727102018-04-18 15:57:46 +00004837 OpenMPClauseKind PredeterminedCKind =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004838 isOpenMPSimdDirective(DKind)
4839 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4840 : OMPC_private;
4841 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4842 DVar.CKind != PredeterminedCKind) ||
4843 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4844 isOpenMPDistributeDirective(DKind)) &&
4845 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4846 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4847 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00004848 SemaRef.Diag(Init->getBeginLoc(), diag::err_omp_loop_var_dsa)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004849 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4850 << getOpenMPClauseName(PredeterminedCKind);
4851 if (DVar.RefExpr == nullptr)
4852 DVar.CKind = PredeterminedCKind;
Alexey Bataeve3727102018-04-18 15:57:46 +00004853 reportOriginalDsa(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004854 HasErrors = true;
4855 } else if (LoopDeclRefExpr != nullptr) {
4856 // Make the loop iteration variable private (for worksharing constructs),
4857 // linear (for simd directives with the only one associated loop) or
4858 // lastprivate (for simd directives with several collapsed or ordered
4859 // loops).
4860 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004861 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4862 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004863 /*FromParent=*/false);
4864 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4865 }
4866
4867 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4868
4869 // Check test-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00004870 HasErrors |= ISC.checkAndSetCond(For->getCond());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004871
4872 // Check incr-expr.
Alexey Bataeve3727102018-04-18 15:57:46 +00004873 HasErrors |= ISC.checkAndSetInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004874 }
4875
Alexey Bataeve3727102018-04-18 15:57:46 +00004876 if (ISC.dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004877 return HasErrors;
4878
Alexander Musmana5f070a2014-10-01 06:03:56 +00004879 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004880 ResultIterSpace.PreCond =
Alexey Bataeve3727102018-04-18 15:57:46 +00004881 ISC.buildPreCond(DSA.getCurScope(), For->getCond(), Captures);
4882 ResultIterSpace.NumIterations = ISC.buildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004883 DSA.getCurScope(),
4884 (isOpenMPWorksharingDirective(DKind) ||
4885 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4886 Captures);
Alexey Bataeve3727102018-04-18 15:57:46 +00004887 ResultIterSpace.CounterVar = ISC.buildCounterVar(Captures, DSA);
4888 ResultIterSpace.PrivateCounterVar = ISC.buildPrivateCounterVar();
4889 ResultIterSpace.CounterInit = ISC.buildCounterInit();
4890 ResultIterSpace.CounterStep = ISC.buildCounterStep();
4891 ResultIterSpace.InitSrcRange = ISC.getInitSrcRange();
4892 ResultIterSpace.CondSrcRange = ISC.getConditionSrcRange();
4893 ResultIterSpace.IncSrcRange = ISC.getIncrementSrcRange();
4894 ResultIterSpace.Subtract = ISC.shouldSubtractStep();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004895
Alexey Bataev62dbb972015-04-22 11:59:37 +00004896 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4897 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004898 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004899 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004900 ResultIterSpace.CounterInit == nullptr ||
4901 ResultIterSpace.CounterStep == nullptr);
Alexey Bataevf138fda2018-08-13 19:04:24 +00004902 if (!HasErrors && DSA.isOrderedRegion()) {
4903 if (DSA.getOrderedRegionParam().second->getNumForLoops()) {
4904 if (CurrentNestedLoopCount <
4905 DSA.getOrderedRegionParam().second->getLoopNumIterations().size()) {
4906 DSA.getOrderedRegionParam().second->setLoopNumIterations(
4907 CurrentNestedLoopCount, ResultIterSpace.NumIterations);
4908 DSA.getOrderedRegionParam().second->setLoopCounter(
4909 CurrentNestedLoopCount, ResultIterSpace.CounterVar);
4910 }
4911 }
4912 for (auto &Pair : DSA.getDoacrossDependClauses()) {
4913 if (CurrentNestedLoopCount >= Pair.first->getNumLoops()) {
4914 // Erroneous case - clause has some problems.
4915 continue;
4916 }
4917 if (Pair.first->getDependencyKind() == OMPC_DEPEND_sink &&
4918 Pair.second.size() <= CurrentNestedLoopCount) {
4919 // Erroneous case - clause has some problems.
4920 Pair.first->setLoopData(CurrentNestedLoopCount, nullptr);
4921 continue;
4922 }
4923 Expr *CntValue;
4924 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
4925 CntValue = ISC.buildOrderedLoopData(
4926 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
4927 Pair.first->getDependencyLoc());
4928 else
4929 CntValue = ISC.buildOrderedLoopData(
4930 DSA.getCurScope(), ResultIterSpace.CounterVar, Captures,
4931 Pair.first->getDependencyLoc(),
4932 Pair.second[CurrentNestedLoopCount].first,
4933 Pair.second[CurrentNestedLoopCount].second);
4934 Pair.first->setLoopData(CurrentNestedLoopCount, CntValue);
4935 }
4936 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004937
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004938 return HasErrors;
4939}
4940
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004941/// Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004942static ExprResult
Alexey Bataeve3727102018-04-18 15:57:46 +00004943buildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004944 ExprResult Start,
Alexey Bataeve3727102018-04-18 15:57:46 +00004945 llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004946 // Build 'VarRef = Start.
Alexey Bataeve3727102018-04-18 15:57:46 +00004947 ExprResult NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004948 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004949 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004950 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004951 VarRef.get()->getType())) {
4952 NewStart = SemaRef.PerformImplicitConversion(
4953 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4954 /*AllowExplicit=*/true);
4955 if (!NewStart.isUsable())
4956 return ExprError();
4957 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004958
Alexey Bataeve3727102018-04-18 15:57:46 +00004959 ExprResult Init =
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004960 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4961 return Init;
4962}
4963
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004964/// Build 'VarRef = Start + Iter * Step'.
Alexey Bataeve3727102018-04-18 15:57:46 +00004965static ExprResult buildCounterUpdate(
4966 Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4967 ExprResult Start, ExprResult Iter, ExprResult Step, bool Subtract,
4968 llvm::MapVector<const Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004969 // Add parentheses (for debugging purposes only).
4970 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4971 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4972 !Step.isUsable())
4973 return ExprError();
4974
Alexey Bataev5a3af132016-03-29 08:58:54 +00004975 ExprResult NewStep = Step;
4976 if (Captures)
4977 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004978 if (NewStep.isInvalid())
4979 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004980 ExprResult Update =
4981 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004982 if (!Update.isUsable())
4983 return ExprError();
4984
Alexey Bataevc0214e02016-02-16 12:13:49 +00004985 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4986 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004987 ExprResult NewStart = Start;
4988 if (Captures)
4989 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004990 if (NewStart.isInvalid())
4991 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004992
Alexey Bataevc0214e02016-02-16 12:13:49 +00004993 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4994 ExprResult SavedUpdate = Update;
4995 ExprResult UpdateVal;
4996 if (VarRef.get()->getType()->isOverloadableType() ||
4997 NewStart.get()->getType()->isOverloadableType() ||
4998 Update.get()->getType()->isOverloadableType()) {
4999 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
5000 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
5001 Update =
5002 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
5003 if (Update.isUsable()) {
5004 UpdateVal =
5005 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
5006 VarRef.get(), SavedUpdate.get());
5007 if (UpdateVal.isUsable()) {
5008 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
5009 UpdateVal.get());
5010 }
5011 }
5012 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
5013 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005014
Alexey Bataevc0214e02016-02-16 12:13:49 +00005015 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
5016 if (!Update.isUsable() || !UpdateVal.isUsable()) {
5017 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
5018 NewStart.get(), SavedUpdate.get());
5019 if (!Update.isUsable())
5020 return ExprError();
5021
Alexey Bataev11481f52016-02-17 10:29:05 +00005022 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
5023 VarRef.get()->getType())) {
5024 Update = SemaRef.PerformImplicitConversion(
5025 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
5026 if (!Update.isUsable())
5027 return ExprError();
5028 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00005029
5030 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
5031 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005032 return Update;
5033}
5034
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005035/// Convert integer expression \a E to make it have at least \a Bits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005036/// bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005037static ExprResult widenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005038 if (E == nullptr)
5039 return ExprError();
Alexey Bataeve3727102018-04-18 15:57:46 +00005040 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005041 QualType OldType = E->getType();
5042 unsigned HasBits = C.getTypeSize(OldType);
5043 if (HasBits >= Bits)
5044 return ExprResult(E);
5045 // OK to convert to signed, because new type has more bits than old.
5046 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
5047 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
5048 true);
5049}
5050
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005051/// Check if the given expression \a E is a constant integer that fits
Alexander Musmana5f070a2014-10-01 06:03:56 +00005052/// into \a Bits bits.
Alexey Bataeve3727102018-04-18 15:57:46 +00005053static bool fitsInto(unsigned Bits, bool Signed, const Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005054 if (E == nullptr)
5055 return false;
5056 llvm::APSInt Result;
5057 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
5058 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
5059 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005060}
5061
Alexey Bataev5a3af132016-03-29 08:58:54 +00005062/// Build preinits statement for the given declarations.
5063static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00005064 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005065 if (!PreInits.empty()) {
5066 return new (Context) DeclStmt(
5067 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
5068 SourceLocation(), SourceLocation());
5069 }
5070 return nullptr;
5071}
5072
5073/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00005074static Stmt *
5075buildPreInits(ASTContext &Context,
Alexey Bataeve3727102018-04-18 15:57:46 +00005076 const llvm::MapVector<const Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005077 if (!Captures.empty()) {
5078 SmallVector<Decl *, 16> PreInits;
Alexey Bataeve3727102018-04-18 15:57:46 +00005079 for (const auto &Pair : Captures)
Alexey Bataev5a3af132016-03-29 08:58:54 +00005080 PreInits.push_back(Pair.second->getDecl());
5081 return buildPreInits(Context, PreInits);
5082 }
5083 return nullptr;
5084}
5085
5086/// Build postupdate expression for the given list of postupdates expressions.
5087static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
5088 Expr *PostUpdate = nullptr;
5089 if (!PostUpdates.empty()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005090 for (Expr *E : PostUpdates) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005091 Expr *ConvE = S.BuildCStyleCastExpr(
5092 E->getExprLoc(),
5093 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
5094 E->getExprLoc(), E)
5095 .get();
5096 PostUpdate = PostUpdate
5097 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
5098 PostUpdate, ConvE)
5099 .get()
5100 : ConvE;
5101 }
5102 }
5103 return PostUpdate;
5104}
5105
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00005106/// Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00005107/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
5108/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005109static unsigned
Alexey Bataeve3727102018-04-18 15:57:46 +00005110checkOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
Alexey Bataev10e775f2015-07-30 11:36:16 +00005111 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
5112 DSAStackTy &DSA,
Alexey Bataeve3727102018-04-18 15:57:46 +00005113 Sema::VarsWithInheritedDSAType &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00005114 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005115 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005116 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005117 // Found 'collapse' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005118 Expr::EvalResult Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005119 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Fangrui Song407659a2018-11-30 23:41:18 +00005120 NestedLoopCount = Result.Val.getInt().getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005121 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005122 unsigned OrderedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005123 if (OrderedLoopCountExpr) {
5124 // Found 'ordered' clause - calculate collapse number.
Fangrui Song407659a2018-11-30 23:41:18 +00005125 Expr::EvalResult EVResult;
5126 if (OrderedLoopCountExpr->EvaluateAsInt(EVResult, SemaRef.getASTContext())) {
5127 llvm::APSInt Result = EVResult.Val.getInt();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005128 if (Result.getLimitedValue() < NestedLoopCount) {
5129 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
5130 diag::err_omp_wrong_ordered_loop_count)
5131 << OrderedLoopCountExpr->getSourceRange();
5132 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
5133 diag::note_collapse_loop_count)
5134 << CollapseLoopCountExpr->getSourceRange();
5135 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005136 OrderedLoopCount = Result.getLimitedValue();
Alexey Bataev7b6bc882015-11-26 07:50:39 +00005137 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005138 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005139 // This is helper routine for loop directives (e.g., 'for', 'simd',
5140 // 'for simd', etc.).
Alexey Bataeve3727102018-04-18 15:57:46 +00005141 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005142 SmallVector<LoopIterationSpace, 4> IterSpaces;
Alexey Bataevf138fda2018-08-13 19:04:24 +00005143 IterSpaces.resize(std::max(OrderedLoopCount, NestedLoopCount));
Alexander Musmana5f070a2014-10-01 06:03:56 +00005144 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005145 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00005146 if (checkOpenMPIterationSpace(
5147 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5148 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5149 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5150 Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00005151 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005152 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005153 // OpenMP [2.8.1, simd construct, Restrictions]
5154 // All loops associated with the construct must be perfectly nested; that
5155 // is, there must be no intervening code nor any OpenMP directive between
5156 // any two loops.
5157 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005158 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00005159 for (unsigned Cnt = NestedLoopCount; Cnt < OrderedLoopCount; ++Cnt) {
5160 if (checkOpenMPIterationSpace(
5161 DKind, CurStmt, SemaRef, DSA, Cnt, NestedLoopCount,
5162 std::max(OrderedLoopCount, NestedLoopCount), CollapseLoopCountExpr,
5163 OrderedLoopCountExpr, VarsWithImplicitDSA, IterSpaces[Cnt],
5164 Captures))
5165 return 0;
5166 if (Cnt > 0 && IterSpaces[Cnt].CounterVar) {
5167 // Handle initialization of captured loop iterator variables.
5168 auto *DRE = cast<DeclRefExpr>(IterSpaces[Cnt].CounterVar);
5169 if (isa<OMPCapturedExprDecl>(DRE->getDecl())) {
5170 Captures[DRE] = DRE;
5171 }
5172 }
5173 // Move on to the next nested for loop, or to the loop body.
5174 // OpenMP [2.8.1, simd construct, Restrictions]
5175 // All loops associated with the construct must be perfectly nested; that
5176 // is, there must be no intervening code nor any OpenMP directive between
5177 // any two loops.
5178 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
5179 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005180
Alexander Musmana5f070a2014-10-01 06:03:56 +00005181 Built.clear(/* size */ NestedLoopCount);
5182
5183 if (SemaRef.CurContext->isDependentContext())
5184 return NestedLoopCount;
5185
5186 // An example of what is generated for the following code:
5187 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00005188 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00005189 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00005190 // for (k = 0; k < NK; ++k)
5191 // for (j = J0; j < NJ; j+=2) {
5192 // <loop body>
5193 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005194 //
5195 // We generate the code below.
5196 // Note: the loop body may be outlined in CodeGen.
5197 // Note: some counters may be C++ classes, operator- is used to find number of
5198 // iterations and operator+= to calculate counter value.
5199 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
5200 // or i64 is currently supported).
5201 //
5202 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
5203 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
5204 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
5205 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
5206 // // similar updates for vars in clauses (e.g. 'linear')
5207 // <loop body (using local i and j)>
5208 // }
5209 // i = NI; // assign final values of counters
5210 // j = NJ;
5211 //
5212
5213 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
5214 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00005215 // Precondition tests if there is at least one iteration (all conditions are
5216 // true).
5217 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexey Bataeve3727102018-04-18 15:57:46 +00005218 Expr *N0 = IterSpaces[0].NumIterations;
5219 ExprResult LastIteration32 =
5220 widenIterationCount(/*Bits=*/32,
5221 SemaRef
5222 .PerformImplicitConversion(
5223 N0->IgnoreImpCasts(), N0->getType(),
5224 Sema::AA_Converting, /*AllowExplicit=*/true)
5225 .get(),
5226 SemaRef);
5227 ExprResult LastIteration64 = widenIterationCount(
5228 /*Bits=*/64,
5229 SemaRef
5230 .PerformImplicitConversion(N0->IgnoreImpCasts(), N0->getType(),
5231 Sema::AA_Converting,
5232 /*AllowExplicit=*/true)
5233 .get(),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005234 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005235
5236 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
5237 return NestedLoopCount;
5238
Alexey Bataeve3727102018-04-18 15:57:46 +00005239 ASTContext &C = SemaRef.Context;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005240 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
5241
5242 Scope *CurScope = DSA.getCurScope();
5243 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00005244 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00005245 PreCond =
5246 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
5247 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00005248 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005249 Expr *N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00005250 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005251 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
5252 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005253 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005254 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005255 SemaRef
5256 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5257 Sema::AA_Converting,
5258 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005259 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005260 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005261 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005262 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00005263 SemaRef
5264 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
5265 Sema::AA_Converting,
5266 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005267 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005268 }
5269
5270 // Choose either the 32-bit or 64-bit version.
5271 ExprResult LastIteration = LastIteration64;
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +00005272 if (SemaRef.getLangOpts().OpenMPOptimisticCollapse ||
5273 (LastIteration32.isUsable() &&
5274 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
5275 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
5276 fitsInto(
5277 /*Bits=*/32,
5278 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
5279 LastIteration64.get(), SemaRef))))
Alexander Musmana5f070a2014-10-01 06:03:56 +00005280 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00005281 QualType VType = LastIteration.get()->getType();
5282 QualType RealVType = VType;
5283 QualType StrideVType = VType;
5284 if (isOpenMPTaskLoopDirective(DKind)) {
5285 VType =
5286 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
5287 StrideVType =
5288 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
5289 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005290
5291 if (!LastIteration.isUsable())
5292 return 0;
5293
5294 // Save the number of iterations.
5295 ExprResult NumIterations = LastIteration;
5296 {
5297 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005298 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
5299 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005300 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5301 if (!LastIteration.isUsable())
5302 return 0;
5303 }
5304
5305 // Calculate the last iteration number beforehand instead of doing this on
5306 // each iteration. Do not do this if the number of iterations may be kfold-ed.
5307 llvm::APSInt Result;
5308 bool IsConstant =
5309 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
5310 ExprResult CalcLastIteration;
5311 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00005312 ExprResult SaveRef =
5313 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005314 LastIteration = SaveRef;
5315
5316 // Prepare SaveRef + 1.
5317 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00005318 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00005319 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
5320 if (!NumIterations.isUsable())
5321 return 0;
5322 }
5323
5324 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
5325
David Majnemer9d168222016-08-05 17:44:54 +00005326 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005327 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005328 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5329 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005330 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005331 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
5332 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005333 SemaRef.AddInitializerToDecl(LBDecl,
5334 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5335 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005336
5337 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00005338 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
5339 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00005340 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00005341 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005342
5343 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
5344 // This will be used to implement clause 'lastprivate'.
5345 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00005346 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
5347 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005348 SemaRef.AddInitializerToDecl(ILDecl,
5349 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5350 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005351
5352 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00005353 VarDecl *STDecl =
5354 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
5355 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00005356 SemaRef.AddInitializerToDecl(STDecl,
5357 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
5358 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005359
5360 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00005361 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00005362 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
5363 UB.get(), LastIteration.get());
5364 ExprResult CondOp = SemaRef.ActOnConditionalOp(
Alexey Bataev86ec3fe2018-07-25 14:40:26 +00005365 LastIteration.get()->getExprLoc(), InitLoc, IsUBGreater.get(),
5366 LastIteration.get(), UB.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00005367 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
5368 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005369 EUB = SemaRef.ActOnFinishFullExpr(EUB.get(), /*DiscardedValue*/ false);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005370
5371 // If we have a combined directive that combines 'distribute', 'for' or
5372 // 'simd' we need to be able to access the bounds of the schedule of the
5373 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
5374 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
5375 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolliffafe102017-04-20 00:39:39 +00005376 // Lower bound variable, initialized with zero.
5377 VarDecl *CombLBDecl =
5378 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
5379 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
5380 SemaRef.AddInitializerToDecl(
5381 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
5382 /*DirectInit*/ false);
5383
5384 // Upper bound variable, initialized with last iteration number.
5385 VarDecl *CombUBDecl =
5386 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
5387 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
5388 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
5389 /*DirectInit*/ false);
5390
5391 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
5392 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
5393 ExprResult CombCondOp =
5394 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
5395 LastIteration.get(), CombUB.get());
5396 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
5397 CombCondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005398 CombEUB =
5399 SemaRef.ActOnFinishFullExpr(CombEUB.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005400
Alexey Bataeve3727102018-04-18 15:57:46 +00005401 const CapturedDecl *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005402 // We expect to have at least 2 more parameters than the 'parallel'
5403 // directive does - the lower and upper bounds of the previous schedule.
5404 assert(CD->getNumParams() >= 4 &&
5405 "Unexpected number of parameters in loop combined directive");
5406
5407 // Set the proper type for the bounds given what we learned from the
5408 // enclosed loops.
Alexey Bataeve3727102018-04-18 15:57:46 +00005409 ImplicitParamDecl *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
5410 ImplicitParamDecl *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
Carlo Bertolli9925f152016-06-27 14:55:37 +00005411
5412 // Previous lower and upper bounds are obtained from the region
5413 // parameters.
5414 PrevLB =
5415 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
5416 PrevUB =
5417 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
5418 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005419 }
5420
5421 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00005422 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005423 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005424 {
Alexey Bataev7292c292016-04-25 12:22:29 +00005425 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
5426 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00005427 Expr *RHS =
5428 (isOpenMPWorksharingDirective(DKind) ||
5429 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
5430 ? LB.get()
5431 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005432 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005433 Init = SemaRef.ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005434
5435 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5436 Expr *CombRHS =
5437 (isOpenMPWorksharingDirective(DKind) ||
5438 isOpenMPTaskLoopDirective(DKind) ||
5439 isOpenMPDistributeDirective(DKind))
5440 ? CombLB.get()
5441 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
5442 CombInit =
5443 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005444 CombInit =
5445 SemaRef.ActOnFinishFullExpr(CombInit.get(), /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005446 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005447 }
5448
Alexander Musmanc6388682014-12-15 07:07:06 +00005449 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005450 SourceLocation CondLoc = AStmt->getBeginLoc();
Alexander Musmanc6388682014-12-15 07:07:06 +00005451 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005452 (isOpenMPWorksharingDirective(DKind) ||
5453 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00005454 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
5455 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
5456 NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005457 ExprResult CombDistCond;
5458 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5459 CombDistCond =
Gheorghe-Teodor Bercea9d6341f2018-10-29 19:44:25 +00005460 SemaRef.BuildBinOp(
5461 CurScope, CondLoc, BO_LT, IV.get(), NumIterations.get());
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005462 }
5463
Carlo Bertolliffafe102017-04-20 00:39:39 +00005464 ExprResult CombCond;
5465 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5466 CombCond =
5467 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
5468 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005469 // Loop increment (IV = IV + 1)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005470 SourceLocation IncLoc = AStmt->getBeginLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005471 ExprResult Inc =
5472 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
5473 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
5474 if (!Inc.isUsable())
5475 return 0;
5476 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005477 Inc = SemaRef.ActOnFinishFullExpr(Inc.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005478 if (!Inc.isUsable())
5479 return 0;
5480
5481 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
5482 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00005483 // In combined construct, add combined version that use CombLB and CombUB
5484 // base variables for the update
5485 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00005486 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
5487 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00005488 // LB + ST
5489 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
5490 if (!NextLB.isUsable())
5491 return 0;
5492 // LB = LB + ST
5493 NextLB =
5494 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005495 NextLB =
5496 SemaRef.ActOnFinishFullExpr(NextLB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005497 if (!NextLB.isUsable())
5498 return 0;
5499 // UB + ST
5500 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
5501 if (!NextUB.isUsable())
5502 return 0;
5503 // UB = UB + ST
5504 NextUB =
5505 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005506 NextUB =
5507 SemaRef.ActOnFinishFullExpr(NextUB.get(), /*DiscardedValue*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00005508 if (!NextUB.isUsable())
5509 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00005510 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5511 CombNextLB =
5512 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
5513 if (!NextLB.isUsable())
5514 return 0;
5515 // LB = LB + ST
5516 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
5517 CombNextLB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005518 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get(),
5519 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005520 if (!CombNextLB.isUsable())
5521 return 0;
5522 // UB + ST
5523 CombNextUB =
5524 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
5525 if (!CombNextUB.isUsable())
5526 return 0;
5527 // UB = UB + ST
5528 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
5529 CombNextUB.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005530 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get(),
5531 /*DiscardedValue*/ false);
Carlo Bertolliffafe102017-04-20 00:39:39 +00005532 if (!CombNextUB.isUsable())
5533 return 0;
5534 }
Alexander Musmanc6388682014-12-15 07:07:06 +00005535 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00005536
Carlo Bertolliffafe102017-04-20 00:39:39 +00005537 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00005538 // directive with for as IV = IV + ST; ensure upper bound expression based
5539 // on PrevUB instead of NumIterations - used to implement 'for' when found
5540 // in combination with 'distribute', like in 'distribute parallel for'
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005541 SourceLocation DistIncLoc = AStmt->getBeginLoc();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005542 ExprResult DistCond, DistInc, PrevEUB, ParForInDistCond;
Carlo Bertolli8429d812017-02-17 21:29:13 +00005543 if (isOpenMPLoopBoundSharingDirective(DKind)) {
5544 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
5545 assert(DistCond.isUsable() && "distribute cond expr was not built");
5546
5547 DistInc =
5548 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
5549 assert(DistInc.isUsable() && "distribute inc expr was not built");
5550 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5551 DistInc.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005552 DistInc =
5553 SemaRef.ActOnFinishFullExpr(DistInc.get(), /*DiscardedValue*/ false);
Carlo Bertolli8429d812017-02-17 21:29:13 +00005554 assert(DistInc.isUsable() && "distribute inc expr was not built");
5555
5556 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5557 // construct
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005558 SourceLocation DistEUBLoc = AStmt->getBeginLoc();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005559 ExprResult IsUBGreater =
5560 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5561 ExprResult CondOp = SemaRef.ActOnConditionalOp(
5562 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5563 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5564 CondOp.get());
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005565 PrevEUB =
5566 SemaRef.ActOnFinishFullExpr(PrevEUB.get(), /*DiscardedValue*/ false);
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005567
5568 // Build IV <= PrevUB to be used in parallel for is in combination with
5569 // a distribute directive with schedule(static, 1)
5570 ParForInDistCond =
5571 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), PrevUB.get());
Carlo Bertolli8429d812017-02-17 21:29:13 +00005572 }
5573
Alexander Musmana5f070a2014-10-01 06:03:56 +00005574 // Build updates and final values of the loop counters.
5575 bool HasErrors = false;
5576 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005577 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005578 Built.Updates.resize(NestedLoopCount);
5579 Built.Finals.resize(NestedLoopCount);
5580 {
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005581 // We implement the following algorithm for obtaining the
5582 // original loop iteration variable values based on the
5583 // value of the collapsed loop iteration variable IV.
5584 //
5585 // Let n+1 be the number of collapsed loops in the nest.
5586 // Iteration variables (I0, I1, .... In)
5587 // Iteration counts (N0, N1, ... Nn)
5588 //
5589 // Acc = IV;
5590 //
5591 // To compute Ik for loop k, 0 <= k <= n, generate:
5592 // Prod = N(k+1) * N(k+2) * ... * Nn;
5593 // Ik = Acc / Prod;
5594 // Acc -= Ik * Prod;
5595 //
5596 ExprResult Acc = IV;
5597 for (unsigned int Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00005598 LoopIterationSpace &IS = IterSpaces[Cnt];
5599 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005600 ExprResult Iter;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005601
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005602 // Compute prod
5603 ExprResult Prod =
5604 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
5605 for (unsigned int K = Cnt+1; K < NestedLoopCount; ++K)
5606 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Prod.get(),
5607 IterSpaces[K].NumIterations);
5608
5609 // Iter = Acc / Prod
5610 // If there is at least one more inner loop to avoid
5611 // multiplication by 1.
5612 if (Cnt + 1 < NestedLoopCount)
5613 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div,
5614 Acc.get(), Prod.get());
5615 else
5616 Iter = Acc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005617 if (!Iter.isUsable()) {
5618 HasErrors = true;
5619 break;
5620 }
5621
Gheorghe-Teodor Bercea677960642019-01-09 20:45:26 +00005622 // Update Acc:
5623 // Acc -= Iter * Prod
5624 // Check if there is at least one more inner loop to avoid
5625 // multiplication by 1.
5626 if (Cnt + 1 < NestedLoopCount)
5627 Prod = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul,
5628 Iter.get(), Prod.get());
5629 else
5630 Prod = Iter;
5631 Acc = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Sub,
5632 Acc.get(), Prod.get());
5633
Alexey Bataev39f915b82015-05-08 10:41:21 +00005634 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005635 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
Alexey Bataeve3727102018-04-18 15:57:46 +00005636 DeclRefExpr *CounterVar = buildDeclRefExpr(
5637 SemaRef, VD, IS.CounterVar->getType(), IS.CounterVar->getExprLoc(),
5638 /*RefersToCapture=*/true);
5639 ExprResult Init = buildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005640 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005641 if (!Init.isUsable()) {
5642 HasErrors = true;
5643 break;
5644 }
Alexey Bataeve3727102018-04-18 15:57:46 +00005645 ExprResult Update = buildCounterUpdate(
Alexey Bataev5a3af132016-03-29 08:58:54 +00005646 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5647 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005648 if (!Update.isUsable()) {
5649 HasErrors = true;
5650 break;
5651 }
5652
5653 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
Alexey Bataeve3727102018-04-18 15:57:46 +00005654 ExprResult Final = buildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00005655 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005656 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005657 if (!Final.isUsable()) {
5658 HasErrors = true;
5659 break;
5660 }
5661
Alexander Musmana5f070a2014-10-01 06:03:56 +00005662 if (!Update.isUsable() || !Final.isUsable()) {
5663 HasErrors = true;
5664 break;
5665 }
5666 // Save results
5667 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00005668 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005669 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005670 Built.Updates[Cnt] = Update.get();
5671 Built.Finals[Cnt] = Final.get();
5672 }
5673 }
5674
5675 if (HasErrors)
5676 return 0;
5677
5678 // Save results
5679 Built.IterationVarRef = IV.get();
5680 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00005681 Built.NumIterations = NumIterations.get();
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +00005682 Built.CalcLastIteration = SemaRef
5683 .ActOnFinishFullExpr(CalcLastIteration.get(),
5684 /*DiscardedValue*/ false)
5685 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005686 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00005687 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005688 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005689 Built.Init = Init.get();
5690 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005691 Built.LB = LB.get();
5692 Built.UB = UB.get();
5693 Built.IL = IL.get();
5694 Built.ST = ST.get();
5695 Built.EUB = EUB.get();
5696 Built.NLB = NextLB.get();
5697 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005698 Built.PrevLB = PrevLB.get();
5699 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005700 Built.DistInc = DistInc.get();
5701 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00005702 Built.DistCombinedFields.LB = CombLB.get();
5703 Built.DistCombinedFields.UB = CombUB.get();
5704 Built.DistCombinedFields.EUB = CombEUB.get();
5705 Built.DistCombinedFields.Init = CombInit.get();
5706 Built.DistCombinedFields.Cond = CombCond.get();
5707 Built.DistCombinedFields.NLB = CombNextLB.get();
5708 Built.DistCombinedFields.NUB = CombNextUB.get();
Gheorghe-Teodor Berceae9256762018-10-29 15:45:47 +00005709 Built.DistCombinedFields.DistCond = CombDistCond.get();
5710 Built.DistCombinedFields.ParForInDistCond = ParForInDistCond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005711
Alexey Bataevabfc0692014-06-25 06:52:00 +00005712 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005713}
5714
Alexey Bataev10e775f2015-07-30 11:36:16 +00005715static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005716 auto CollapseClauses =
5717 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5718 if (CollapseClauses.begin() != CollapseClauses.end())
5719 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005720 return nullptr;
5721}
5722
Alexey Bataev10e775f2015-07-30 11:36:16 +00005723static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005724 auto OrderedClauses =
5725 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5726 if (OrderedClauses.begin() != OrderedClauses.end())
5727 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005728 return nullptr;
5729}
5730
Kelvin Lic5609492016-07-15 04:39:07 +00005731static bool checkSimdlenSafelenSpecified(Sema &S,
5732 const ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005733 const OMPSafelenClause *Safelen = nullptr;
5734 const OMPSimdlenClause *Simdlen = nullptr;
Kelvin Lic5609492016-07-15 04:39:07 +00005735
Alexey Bataeve3727102018-04-18 15:57:46 +00005736 for (const OMPClause *Clause : Clauses) {
Kelvin Lic5609492016-07-15 04:39:07 +00005737 if (Clause->getClauseKind() == OMPC_safelen)
5738 Safelen = cast<OMPSafelenClause>(Clause);
5739 else if (Clause->getClauseKind() == OMPC_simdlen)
5740 Simdlen = cast<OMPSimdlenClause>(Clause);
5741 if (Safelen && Simdlen)
5742 break;
5743 }
5744
5745 if (Simdlen && Safelen) {
Alexey Bataeve3727102018-04-18 15:57:46 +00005746 const Expr *SimdlenLength = Simdlen->getSimdlen();
5747 const Expr *SafelenLength = Safelen->getSafelen();
Kelvin Lic5609492016-07-15 04:39:07 +00005748 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5749 SimdlenLength->isInstantiationDependent() ||
5750 SimdlenLength->containsUnexpandedParameterPack())
5751 return false;
5752 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5753 SafelenLength->isInstantiationDependent() ||
5754 SafelenLength->containsUnexpandedParameterPack())
5755 return false;
Fangrui Song407659a2018-11-30 23:41:18 +00005756 Expr::EvalResult SimdlenResult, SafelenResult;
5757 SimdlenLength->EvaluateAsInt(SimdlenResult, S.Context);
5758 SafelenLength->EvaluateAsInt(SafelenResult, S.Context);
5759 llvm::APSInt SimdlenRes = SimdlenResult.Val.getInt();
5760 llvm::APSInt SafelenRes = SafelenResult.Val.getInt();
Kelvin Lic5609492016-07-15 04:39:07 +00005761 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5762 // If both simdlen and safelen clauses are specified, the value of the
5763 // simdlen parameter must be less than or equal to the value of the safelen
5764 // parameter.
5765 if (SimdlenRes > SafelenRes) {
5766 S.Diag(SimdlenLength->getExprLoc(),
5767 diag::err_omp_wrong_simdlen_safelen_values)
5768 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5769 return true;
5770 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005771 }
5772 return false;
5773}
5774
Alexey Bataeve3727102018-04-18 15:57:46 +00005775StmtResult
5776Sema::ActOnOpenMPSimdDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5777 SourceLocation StartLoc, SourceLocation EndLoc,
5778 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005779 if (!AStmt)
5780 return StmtError();
5781
5782 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005783 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005784 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5785 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00005786 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00005787 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5788 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005789 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005790 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005791
Alexander Musmana5f070a2014-10-01 06:03:56 +00005792 assert((CurContext->isDependentContext() || B.builtAll()) &&
5793 "omp simd loop exprs were not built");
5794
Alexander Musman3276a272015-03-21 10:12:56 +00005795 if (!CurContext->isDependentContext()) {
5796 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005797 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005798 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005799 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005800 B.NumIterations, *this, CurScope,
5801 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005802 return StmtError();
5803 }
5804 }
5805
Kelvin Lic5609492016-07-15 04:39:07 +00005806 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005807 return StmtError();
5808
Reid Kleckner87a31802018-03-12 21:43:02 +00005809 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005810 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5811 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005812}
5813
Alexey Bataeve3727102018-04-18 15:57:46 +00005814StmtResult
5815Sema::ActOnOpenMPForDirective(ArrayRef<OMPClause *> Clauses, Stmt *AStmt,
5816 SourceLocation StartLoc, SourceLocation EndLoc,
5817 VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005818 if (!AStmt)
5819 return StmtError();
5820
5821 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005822 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005823 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5824 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00005825 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataev10e775f2015-07-30 11:36:16 +00005826 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5827 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005828 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005829 return StmtError();
5830
Alexander Musmana5f070a2014-10-01 06:03:56 +00005831 assert((CurContext->isDependentContext() || B.builtAll()) &&
5832 "omp for loop exprs were not built");
5833
Alexey Bataev54acd402015-08-04 11:18:19 +00005834 if (!CurContext->isDependentContext()) {
5835 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005836 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005837 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005838 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005839 B.NumIterations, *this, CurScope,
5840 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005841 return StmtError();
5842 }
5843 }
5844
Reid Kleckner87a31802018-03-12 21:43:02 +00005845 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005846 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005847 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005848}
5849
Alexander Musmanf82886e2014-09-18 05:12:34 +00005850StmtResult Sema::ActOnOpenMPForSimdDirective(
5851 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00005852 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005853 if (!AStmt)
5854 return StmtError();
5855
5856 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005857 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005858 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5859 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005860 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00005861 checkOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00005862 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5863 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005864 if (NestedLoopCount == 0)
5865 return StmtError();
5866
Alexander Musmanc6388682014-12-15 07:07:06 +00005867 assert((CurContext->isDependentContext() || B.builtAll()) &&
5868 "omp for simd loop exprs were not built");
5869
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005870 if (!CurContext->isDependentContext()) {
5871 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00005872 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005873 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005874 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005875 B.NumIterations, *this, CurScope,
5876 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005877 return StmtError();
5878 }
5879 }
5880
Kelvin Lic5609492016-07-15 04:39:07 +00005881 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005882 return StmtError();
5883
Reid Kleckner87a31802018-03-12 21:43:02 +00005884 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005885 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5886 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005887}
5888
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005889StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5890 Stmt *AStmt,
5891 SourceLocation StartLoc,
5892 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005893 if (!AStmt)
5894 return StmtError();
5895
5896 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005897 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005898 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005899 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005900 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005901 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005902 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005903 return StmtError();
5904 // All associated statements must be '#pragma omp section' except for
5905 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005906 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005907 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5908 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005909 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005910 diag::err_omp_sections_substmt_not_section);
5911 return StmtError();
5912 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005913 cast<OMPSectionDirective>(SectionStmt)
5914 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005915 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005916 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005917 Diag(AStmt->getBeginLoc(), diag::err_omp_sections_not_compound_stmt);
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005918 return StmtError();
5919 }
5920
Reid Kleckner87a31802018-03-12 21:43:02 +00005921 setFunctionHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005922
Alexey Bataev25e5b442015-09-15 12:52:43 +00005923 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5924 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005925}
5926
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005927StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5928 SourceLocation StartLoc,
5929 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005930 if (!AStmt)
5931 return StmtError();
5932
5933 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005934
Reid Kleckner87a31802018-03-12 21:43:02 +00005935 setFunctionHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005936 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005937
Alexey Bataev25e5b442015-09-15 12:52:43 +00005938 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5939 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005940}
5941
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005942StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5943 Stmt *AStmt,
5944 SourceLocation StartLoc,
5945 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005946 if (!AStmt)
5947 return StmtError();
5948
5949 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005950
Reid Kleckner87a31802018-03-12 21:43:02 +00005951 setFunctionHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005952
Alexey Bataev3255bf32015-01-19 05:20:46 +00005953 // OpenMP [2.7.3, single Construct, Restrictions]
5954 // The copyprivate clause must not be used with the nowait clause.
Alexey Bataeve3727102018-04-18 15:57:46 +00005955 const OMPClause *Nowait = nullptr;
5956 const OMPClause *Copyprivate = nullptr;
5957 for (const OMPClause *Clause : Clauses) {
Alexey Bataev3255bf32015-01-19 05:20:46 +00005958 if (Clause->getClauseKind() == OMPC_nowait)
5959 Nowait = Clause;
5960 else if (Clause->getClauseKind() == OMPC_copyprivate)
5961 Copyprivate = Clause;
5962 if (Copyprivate && Nowait) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005963 Diag(Copyprivate->getBeginLoc(),
Alexey Bataev3255bf32015-01-19 05:20:46 +00005964 diag::err_omp_single_copyprivate_with_nowait);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00005965 Diag(Nowait->getBeginLoc(), diag::note_omp_nowait_clause_here);
Alexey Bataev3255bf32015-01-19 05:20:46 +00005966 return StmtError();
5967 }
5968 }
5969
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005970 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5971}
5972
Alexander Musman80c22892014-07-17 08:54:58 +00005973StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5974 SourceLocation StartLoc,
5975 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005976 if (!AStmt)
5977 return StmtError();
5978
5979 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005980
Reid Kleckner87a31802018-03-12 21:43:02 +00005981 setFunctionHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00005982
5983 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5984}
5985
Alexey Bataev28c75412015-12-15 08:19:24 +00005986StmtResult Sema::ActOnOpenMPCriticalDirective(
5987 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5988 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005989 if (!AStmt)
5990 return StmtError();
5991
5992 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005993
Alexey Bataev28c75412015-12-15 08:19:24 +00005994 bool ErrorFound = false;
5995 llvm::APSInt Hint;
5996 SourceLocation HintLoc;
5997 bool DependentHint = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00005998 for (const OMPClause *C : Clauses) {
Alexey Bataev28c75412015-12-15 08:19:24 +00005999 if (C->getClauseKind() == OMPC_hint) {
6000 if (!DirName.getName()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006001 Diag(C->getBeginLoc(), diag::err_omp_hint_clause_no_name);
Alexey Bataev28c75412015-12-15 08:19:24 +00006002 ErrorFound = true;
6003 }
6004 Expr *E = cast<OMPHintClause>(C)->getHint();
6005 if (E->isTypeDependent() || E->isValueDependent() ||
Alexey Bataeve3727102018-04-18 15:57:46 +00006006 E->isInstantiationDependent()) {
Alexey Bataev28c75412015-12-15 08:19:24 +00006007 DependentHint = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006008 } else {
Alexey Bataev28c75412015-12-15 08:19:24 +00006009 Hint = E->EvaluateKnownConstInt(Context);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006010 HintLoc = C->getBeginLoc();
Alexey Bataev28c75412015-12-15 08:19:24 +00006011 }
6012 }
6013 }
6014 if (ErrorFound)
6015 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006016 const auto Pair = DSAStack->getCriticalWithHint(DirName);
Alexey Bataev28c75412015-12-15 08:19:24 +00006017 if (Pair.first && DirName.getName() && !DependentHint) {
6018 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
6019 Diag(StartLoc, diag::err_omp_critical_with_hint);
Alexey Bataeve3727102018-04-18 15:57:46 +00006020 if (HintLoc.isValid())
Alexey Bataev28c75412015-12-15 08:19:24 +00006021 Diag(HintLoc, diag::note_omp_critical_hint_here)
6022 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006023 else
Alexey Bataev28c75412015-12-15 08:19:24 +00006024 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
Alexey Bataeve3727102018-04-18 15:57:46 +00006025 if (const auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006026 Diag(C->getBeginLoc(), diag::note_omp_critical_hint_here)
Alexey Bataev28c75412015-12-15 08:19:24 +00006027 << 1
6028 << C->getHint()->EvaluateKnownConstInt(Context).toString(
6029 /*Radix=*/10, /*Signed=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +00006030 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006031 Diag(Pair.first->getBeginLoc(), diag::note_omp_critical_no_hint) << 1;
Alexey Bataeve3727102018-04-18 15:57:46 +00006032 }
Alexey Bataev28c75412015-12-15 08:19:24 +00006033 }
6034 }
6035
Reid Kleckner87a31802018-03-12 21:43:02 +00006036 setFunctionHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006037
Alexey Bataev28c75412015-12-15 08:19:24 +00006038 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
6039 Clauses, AStmt);
6040 if (!Pair.first && DirName.getName() && !DependentHint)
6041 DSAStack->addCriticalWithHint(Dir, Hint);
6042 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00006043}
6044
Alexey Bataev4acb8592014-07-07 13:01:15 +00006045StmtResult Sema::ActOnOpenMPParallelForDirective(
6046 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006047 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006048 if (!AStmt)
6049 return StmtError();
6050
Alexey Bataeve3727102018-04-18 15:57:46 +00006051 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006052 // 1.2.2 OpenMP Language Terminology
6053 // Structured block - An executable statement with a single entry at the
6054 // top and a single exit at the bottom.
6055 // The point of exit cannot be a branch out of the structured block.
6056 // longjmp() and throw() must not violate the entry/exit criteria.
6057 CS->getCapturedDecl()->setNothrow();
6058
Alexander Musmanc6388682014-12-15 07:07:06 +00006059 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006060 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6061 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00006062 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006063 checkOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006064 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6065 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00006066 if (NestedLoopCount == 0)
6067 return StmtError();
6068
Alexander Musmana5f070a2014-10-01 06:03:56 +00006069 assert((CurContext->isDependentContext() || B.builtAll()) &&
6070 "omp parallel for loop exprs were not built");
6071
Alexey Bataev54acd402015-08-04 11:18:19 +00006072 if (!CurContext->isDependentContext()) {
6073 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006074 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006075 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00006076 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006077 B.NumIterations, *this, CurScope,
6078 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00006079 return StmtError();
6080 }
6081 }
6082
Reid Kleckner87a31802018-03-12 21:43:02 +00006083 setFunctionHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00006084 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00006085 NestedLoopCount, Clauses, AStmt, B,
6086 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00006087}
6088
Alexander Musmane4e893b2014-09-23 09:33:00 +00006089StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
6090 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00006091 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006092 if (!AStmt)
6093 return StmtError();
6094
Alexey Bataeve3727102018-04-18 15:57:46 +00006095 auto *CS = cast<CapturedStmt>(AStmt);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006096 // 1.2.2 OpenMP Language Terminology
6097 // Structured block - An executable statement with a single entry at the
6098 // top and a single exit at the bottom.
6099 // The point of exit cannot be a branch out of the structured block.
6100 // longjmp() and throw() must not violate the entry/exit criteria.
6101 CS->getCapturedDecl()->setNothrow();
6102
Alexander Musmanc6388682014-12-15 07:07:06 +00006103 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00006104 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6105 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00006106 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00006107 checkOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev10e775f2015-07-30 11:36:16 +00006108 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
6109 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006110 if (NestedLoopCount == 0)
6111 return StmtError();
6112
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006113 if (!CurContext->isDependentContext()) {
6114 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00006115 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006116 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006117 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006118 B.NumIterations, *this, CurScope,
6119 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00006120 return StmtError();
6121 }
6122 }
6123
Kelvin Lic5609492016-07-15 04:39:07 +00006124 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00006125 return StmtError();
6126
Reid Kleckner87a31802018-03-12 21:43:02 +00006127 setFunctionHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00006128 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00006129 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00006130}
6131
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006132StmtResult
6133Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
6134 Stmt *AStmt, SourceLocation StartLoc,
6135 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006136 if (!AStmt)
6137 return StmtError();
6138
6139 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006140 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00006141 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006142 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00006143 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006144 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00006145 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006146 return StmtError();
6147 // All associated statements must be '#pragma omp section' except for
6148 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00006149 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006150 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
6151 if (SectionStmt)
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006152 Diag(SectionStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006153 diag::err_omp_parallel_sections_substmt_not_section);
6154 return StmtError();
6155 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006156 cast<OMPSectionDirective>(SectionStmt)
6157 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006158 }
6159 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006160 Diag(AStmt->getBeginLoc(),
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006161 diag::err_omp_parallel_sections_not_compound_stmt);
6162 return StmtError();
6163 }
6164
Reid Kleckner87a31802018-03-12 21:43:02 +00006165 setFunctionHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006166
Alexey Bataev25e5b442015-09-15 12:52:43 +00006167 return OMPParallelSectionsDirective::Create(
6168 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00006169}
6170
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006171StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
6172 Stmt *AStmt, SourceLocation StartLoc,
6173 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006174 if (!AStmt)
6175 return StmtError();
6176
David Majnemer9d168222016-08-05 17:44:54 +00006177 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006178 // 1.2.2 OpenMP Language Terminology
6179 // Structured block - An executable statement with a single entry at the
6180 // top and a single exit at the bottom.
6181 // The point of exit cannot be a branch out of the structured block.
6182 // longjmp() and throw() must not violate the entry/exit criteria.
6183 CS->getCapturedDecl()->setNothrow();
6184
Reid Kleckner87a31802018-03-12 21:43:02 +00006185 setFunctionHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006186
Alexey Bataev25e5b442015-09-15 12:52:43 +00006187 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
6188 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00006189}
6190
Alexey Bataev68446b72014-07-18 07:47:19 +00006191StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
6192 SourceLocation EndLoc) {
6193 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
6194}
6195
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00006196StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
6197 SourceLocation EndLoc) {
6198 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
6199}
6200
Alexey Bataev2df347a2014-07-18 10:17:07 +00006201StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
6202 SourceLocation EndLoc) {
6203 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
6204}
6205
Alexey Bataev169d96a2017-07-18 20:17:46 +00006206StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
6207 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006208 SourceLocation StartLoc,
6209 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006210 if (!AStmt)
6211 return StmtError();
6212
6213 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006214
Reid Kleckner87a31802018-03-12 21:43:02 +00006215 setFunctionHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006216
Alexey Bataev169d96a2017-07-18 20:17:46 +00006217 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00006218 AStmt,
6219 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00006220}
6221
Alexey Bataev6125da92014-07-21 11:26:11 +00006222StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
6223 SourceLocation StartLoc,
6224 SourceLocation EndLoc) {
6225 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
6226 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
6227}
6228
Alexey Bataev346265e2015-09-25 10:37:12 +00006229StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
6230 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006231 SourceLocation StartLoc,
6232 SourceLocation EndLoc) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006233 const OMPClause *DependFound = nullptr;
6234 const OMPClause *DependSourceClause = nullptr;
6235 const OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00006236 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00006237 const OMPThreadsClause *TC = nullptr;
6238 const OMPSIMDClause *SC = nullptr;
6239 for (const OMPClause *C : Clauses) {
Alexey Bataeveb482352015-12-18 05:05:56 +00006240 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
6241 DependFound = C;
6242 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
6243 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006244 Diag(C->getBeginLoc(), diag::err_omp_more_one_clause)
Alexey Bataeveb482352015-12-18 05:05:56 +00006245 << getOpenMPDirectiveName(OMPD_ordered)
6246 << getOpenMPClauseName(OMPC_depend) << 2;
6247 ErrorFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006248 } else {
Alexey Bataeveb482352015-12-18 05:05:56 +00006249 DependSourceClause = C;
Alexey Bataeve3727102018-04-18 15:57:46 +00006250 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006251 if (DependSinkClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006252 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006253 << 0;
6254 ErrorFound = true;
6255 }
6256 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
6257 if (DependSourceClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006258 Diag(C->getBeginLoc(), diag::err_omp_depend_sink_source_not_allowed)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00006259 << 1;
6260 ErrorFound = true;
6261 }
6262 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00006263 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006264 } else if (C->getClauseKind() == OMPC_threads) {
Alexey Bataev346265e2015-09-25 10:37:12 +00006265 TC = cast<OMPThreadsClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006266 } else if (C->getClauseKind() == OMPC_simd) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006267 SC = cast<OMPSIMDClause>(C);
Alexey Bataeve3727102018-04-18 15:57:46 +00006268 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006269 }
Alexey Bataeveb482352015-12-18 05:05:56 +00006270 if (!ErrorFound && !SC &&
6271 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006272 // OpenMP [2.8.1,simd Construct, Restrictions]
6273 // An ordered construct with the simd clause is the only OpenMP construct
6274 // that can appear in the simd region.
6275 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00006276 ErrorFound = true;
6277 } else if (DependFound && (TC || SC)) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006278 Diag(DependFound->getBeginLoc(), diag::err_omp_depend_clause_thread_simd)
Alexey Bataeveb482352015-12-18 05:05:56 +00006279 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
6280 ErrorFound = true;
Alexey Bataevf138fda2018-08-13 19:04:24 +00006281 } else if (DependFound && !DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006282 Diag(DependFound->getBeginLoc(),
Alexey Bataeveb482352015-12-18 05:05:56 +00006283 diag::err_omp_ordered_directive_without_param);
6284 ErrorFound = true;
6285 } else if (TC || Clauses.empty()) {
Alexey Bataevf138fda2018-08-13 19:04:24 +00006286 if (const Expr *Param = DSAStack->getParentOrderedRegionParam().first) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006287 SourceLocation ErrLoc = TC ? TC->getBeginLoc() : StartLoc;
Alexey Bataeveb482352015-12-18 05:05:56 +00006288 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
6289 << (TC != nullptr);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006290 Diag(Param->getBeginLoc(), diag::note_omp_ordered_param);
Alexey Bataeveb482352015-12-18 05:05:56 +00006291 ErrorFound = true;
6292 }
6293 }
6294 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006295 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00006296
6297 if (AStmt) {
6298 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6299
Reid Kleckner87a31802018-03-12 21:43:02 +00006300 setFunctionHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00006301 }
Alexey Bataev346265e2015-09-25 10:37:12 +00006302
6303 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00006304}
6305
Alexey Bataev1d160b12015-03-13 12:27:31 +00006306namespace {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006307/// Helper class for checking expression in 'omp atomic [update]'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006308/// construct.
6309class OpenMPAtomicUpdateChecker {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006310 /// Error results for atomic update expressions.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006311 enum ExprAnalysisErrorCode {
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006312 /// A statement is not an expression statement.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006313 NotAnExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006314 /// Expression is not builtin binary or unary operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006315 NotABinaryOrUnaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006316 /// Unary operation is not post-/pre- increment/decrement operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006317 NotAnUnaryIncDecExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006318 /// An expression is not of scalar type.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006319 NotAScalarType,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006320 /// A binary operation is not an assignment operation.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006321 NotAnAssignmentOp,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006322 /// RHS part of the binary operation is not a binary expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006323 NotABinaryExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006324 /// RHS part is not additive/multiplicative/shift/biwise binary
Alexey Bataev1d160b12015-03-13 12:27:31 +00006325 /// expression.
6326 NotABinaryOperator,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006327 /// RHS binary operation does not have reference to the updated LHS
Alexey Bataev1d160b12015-03-13 12:27:31 +00006328 /// part.
6329 NotAnUpdateExpression,
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006330 /// No errors is found.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006331 NoError
6332 };
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006333 /// Reference to Sema.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006334 Sema &SemaRef;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006335 /// A location for note diagnostics (when error is found).
Alexey Bataev1d160b12015-03-13 12:27:31 +00006336 SourceLocation NoteLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006337 /// 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006338 Expr *X;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006339 /// 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006340 Expr *E;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006341 /// Helper expression of the form
Alexey Bataevb4505a72015-03-30 05:20:59 +00006342 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6343 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6344 Expr *UpdateExpr;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006345 /// Is 'x' a LHS in a RHS part of full update expression. It is
Alexey Bataevb4505a72015-03-30 05:20:59 +00006346 /// important for non-associative operations.
6347 bool IsXLHSInRHSPart;
6348 BinaryOperatorKind Op;
6349 SourceLocation OpLoc;
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006350 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006351 /// if it is a prefix unary operation.
6352 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006353
6354public:
6355 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00006356 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00006357 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006358 /// Check specified statement that it is suitable for 'atomic update'
Alexey Bataev1d160b12015-03-13 12:27:31 +00006359 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00006360 /// expression. If DiagId and NoteId == 0, then only check is performed
6361 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006362 /// \param DiagId Diagnostic which should be emitted if error is found.
6363 /// \param NoteId Diagnostic note for the main error message.
6364 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00006365 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006366 /// Return the 'x' lvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006367 Expr *getX() const { return X; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006368 /// Return the 'expr' rvalue part of the source atomic expression.
Alexey Bataev1d160b12015-03-13 12:27:31 +00006369 Expr *getExpr() const { return E; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006370 /// Return the update expression used in calculation of the updated
Alexey Bataevb4505a72015-03-30 05:20:59 +00006371 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
6372 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
6373 Expr *getUpdateExpr() const { return UpdateExpr; }
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006374 /// Return true if 'x' is LHS in RHS part of full update expression,
Alexey Bataevb4505a72015-03-30 05:20:59 +00006375 /// false otherwise.
6376 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
6377
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00006378 /// true if the source expression is a postfix unary operation, false
Alexey Bataevb78ca832015-04-01 03:33:17 +00006379 /// if it is a prefix unary operation.
6380 bool isPostfixUpdate() const { return IsPostfixUpdate; }
6381
Alexey Bataev1d160b12015-03-13 12:27:31 +00006382private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00006383 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
6384 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00006385};
6386} // namespace
6387
6388bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
6389 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
6390 ExprAnalysisErrorCode ErrorFound = NoError;
6391 SourceLocation ErrorLoc, NoteLoc;
6392 SourceRange ErrorRange, NoteRange;
6393 // Allowed constructs are:
6394 // x = x binop expr;
6395 // x = expr binop x;
6396 if (AtomicBinOp->getOpcode() == BO_Assign) {
6397 X = AtomicBinOp->getLHS();
Alexey Bataeve3727102018-04-18 15:57:46 +00006398 if (const auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006399 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
6400 if (AtomicInnerBinOp->isMultiplicativeOp() ||
6401 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
6402 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006403 Op = AtomicInnerBinOp->getOpcode();
6404 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +00006405 Expr *LHS = AtomicInnerBinOp->getLHS();
6406 Expr *RHS = AtomicInnerBinOp->getRHS();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006407 llvm::FoldingSetNodeID XId, LHSId, RHSId;
6408 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
6409 /*Canonical=*/true);
6410 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
6411 /*Canonical=*/true);
6412 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
6413 /*Canonical=*/true);
6414 if (XId == LHSId) {
6415 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006416 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006417 } else if (XId == RHSId) {
6418 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006419 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006420 } else {
6421 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6422 ErrorRange = AtomicInnerBinOp->getSourceRange();
6423 NoteLoc = X->getExprLoc();
6424 NoteRange = X->getSourceRange();
6425 ErrorFound = NotAnUpdateExpression;
6426 }
6427 } else {
6428 ErrorLoc = AtomicInnerBinOp->getExprLoc();
6429 ErrorRange = AtomicInnerBinOp->getSourceRange();
6430 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
6431 NoteRange = SourceRange(NoteLoc, NoteLoc);
6432 ErrorFound = NotABinaryOperator;
6433 }
6434 } else {
6435 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
6436 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
6437 ErrorFound = NotABinaryExpression;
6438 }
6439 } else {
6440 ErrorLoc = AtomicBinOp->getExprLoc();
6441 ErrorRange = AtomicBinOp->getSourceRange();
6442 NoteLoc = AtomicBinOp->getOperatorLoc();
6443 NoteRange = SourceRange(NoteLoc, NoteLoc);
6444 ErrorFound = NotAnAssignmentOp;
6445 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006446 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006447 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6448 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6449 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006450 }
6451 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006452 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006453 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006454}
6455
6456bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
6457 unsigned NoteId) {
6458 ExprAnalysisErrorCode ErrorFound = NoError;
6459 SourceLocation ErrorLoc, NoteLoc;
6460 SourceRange ErrorRange, NoteRange;
6461 // Allowed constructs are:
6462 // x++;
6463 // x--;
6464 // ++x;
6465 // --x;
6466 // x binop= expr;
6467 // x = x binop expr;
6468 // x = expr binop x;
6469 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
6470 AtomicBody = AtomicBody->IgnoreParenImpCasts();
6471 if (AtomicBody->getType()->isScalarType() ||
6472 AtomicBody->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006473 if (const auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006474 AtomicBody->IgnoreParenImpCasts())) {
6475 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00006476 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00006477 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00006478 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006479 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006480 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006481 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006482 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
6483 AtomicBody->IgnoreParenImpCasts())) {
6484 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00006485 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00006486 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006487 } else if (const auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
David Majnemer9d168222016-08-05 17:44:54 +00006488 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006489 // Check for Unary Operation
6490 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006491 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006492 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
6493 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00006494 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006495 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
6496 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006497 } else {
6498 ErrorFound = NotAnUnaryIncDecExpression;
6499 ErrorLoc = AtomicUnaryOp->getExprLoc();
6500 ErrorRange = AtomicUnaryOp->getSourceRange();
6501 NoteLoc = AtomicUnaryOp->getOperatorLoc();
6502 NoteRange = SourceRange(NoteLoc, NoteLoc);
6503 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006504 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006505 ErrorFound = NotABinaryOrUnaryExpression;
6506 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
6507 NoteRange = ErrorRange = AtomicBody->getSourceRange();
6508 }
6509 } else {
6510 ErrorFound = NotAScalarType;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006511 NoteLoc = ErrorLoc = AtomicBody->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006512 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6513 }
6514 } else {
6515 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006516 NoteLoc = ErrorLoc = S->getBeginLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006517 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
6518 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006519 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006520 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
6521 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
6522 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +00006523 }
6524 if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00006525 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00006526 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006527 // Build an update expression of form 'OpaqueValueExpr(x) binop
6528 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6529 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6530 auto *OVEX = new (SemaRef.getASTContext())
6531 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6532 auto *OVEExpr = new (SemaRef.getASTContext())
6533 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
Alexey Bataeve3727102018-04-18 15:57:46 +00006534 ExprResult Update =
Alexey Bataevb4505a72015-03-30 05:20:59 +00006535 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6536 IsXLHSInRHSPart ? OVEExpr : OVEX);
6537 if (Update.isInvalid())
6538 return true;
6539 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6540 Sema::AA_Casting);
6541 if (Update.isInvalid())
6542 return true;
6543 UpdateExpr = Update.get();
6544 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00006545 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006546}
6547
Alexey Bataev0162e452014-07-22 10:10:35 +00006548StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6549 Stmt *AStmt,
6550 SourceLocation StartLoc,
6551 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006552 if (!AStmt)
6553 return StmtError();
6554
David Majnemer9d168222016-08-05 17:44:54 +00006555 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00006556 // 1.2.2 OpenMP Language Terminology
6557 // Structured block - An executable statement with a single entry at the
6558 // top and a single exit at the bottom.
6559 // The point of exit cannot be a branch out of the structured block.
6560 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00006561 OpenMPClauseKind AtomicKind = OMPC_unknown;
6562 SourceLocation AtomicKindLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00006563 for (const OMPClause *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00006564 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00006565 C->getClauseKind() == OMPC_update ||
6566 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00006567 if (AtomicKind != OMPC_unknown) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006568 Diag(C->getBeginLoc(), diag::err_omp_atomic_several_clauses)
Stephen Kelly1c301dc2018-08-09 21:09:38 +00006569 << SourceRange(C->getBeginLoc(), C->getEndLoc());
Alexey Bataevdea47612014-07-23 07:46:59 +00006570 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6571 << getOpenMPClauseName(AtomicKind);
6572 } else {
6573 AtomicKind = C->getClauseKind();
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006574 AtomicKindLoc = C->getBeginLoc();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006575 }
6576 }
6577 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006578
Alexey Bataeve3727102018-04-18 15:57:46 +00006579 Stmt *Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00006580 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6581 Body = EWC->getSubExpr();
6582
Alexey Bataev62cec442014-11-18 10:14:22 +00006583 Expr *X = nullptr;
6584 Expr *V = nullptr;
6585 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006586 Expr *UE = nullptr;
6587 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006588 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006589 // OpenMP [2.12.6, atomic Construct]
6590 // In the next expressions:
6591 // * x and v (as applicable) are both l-value expressions with scalar type.
6592 // * During the execution of an atomic region, multiple syntactic
6593 // occurrences of x must designate the same storage location.
6594 // * Neither of v and expr (as applicable) may access the storage location
6595 // designated by x.
6596 // * Neither of x and expr (as applicable) may access the storage location
6597 // designated by v.
6598 // * expr is an expression with scalar type.
6599 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6600 // * binop, binop=, ++, and -- are not overloaded operators.
6601 // * The expression x binop expr must be numerically equivalent to x binop
6602 // (expr). This requirement is satisfied if the operators in expr have
6603 // precedence greater than binop, or by using parentheses around expr or
6604 // subexpressions of expr.
6605 // * The expression expr binop x must be numerically equivalent to (expr)
6606 // binop x. This requirement is satisfied if the operators in expr have
6607 // precedence equal to or greater than binop, or by using parentheses around
6608 // expr or subexpressions of expr.
6609 // * For forms that allow multiple occurrences of x, the number of times
6610 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006611 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006612 enum {
6613 NotAnExpression,
6614 NotAnAssignmentOp,
6615 NotAScalarType,
6616 NotAnLValue,
6617 NoError
6618 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006619 SourceLocation ErrorLoc, NoteLoc;
6620 SourceRange ErrorRange, NoteRange;
6621 // If clause is read:
6622 // v = x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006623 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6624 const auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006625 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6626 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6627 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6628 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6629 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6630 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6631 if (!X->isLValue() || !V->isLValue()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006632 const Expr *NotLValueExpr = X->isLValue() ? V : X;
Alexey Bataev62cec442014-11-18 10:14:22 +00006633 ErrorFound = NotAnLValue;
6634 ErrorLoc = AtomicBinOp->getExprLoc();
6635 ErrorRange = AtomicBinOp->getSourceRange();
6636 NoteLoc = NotLValueExpr->getExprLoc();
6637 NoteRange = NotLValueExpr->getSourceRange();
6638 }
6639 } else if (!X->isInstantiationDependent() ||
6640 !V->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006641 const Expr *NotScalarExpr =
Alexey Bataev62cec442014-11-18 10:14:22 +00006642 (X->isInstantiationDependent() || X->getType()->isScalarType())
6643 ? V
6644 : X;
6645 ErrorFound = NotAScalarType;
6646 ErrorLoc = AtomicBinOp->getExprLoc();
6647 ErrorRange = AtomicBinOp->getSourceRange();
6648 NoteLoc = NotScalarExpr->getExprLoc();
6649 NoteRange = NotScalarExpr->getSourceRange();
6650 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006651 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00006652 ErrorFound = NotAnAssignmentOp;
6653 ErrorLoc = AtomicBody->getExprLoc();
6654 ErrorRange = AtomicBody->getSourceRange();
6655 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6656 : AtomicBody->getExprLoc();
6657 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6658 : AtomicBody->getSourceRange();
6659 }
6660 } else {
6661 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006662 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataev62cec442014-11-18 10:14:22 +00006663 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006664 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006665 if (ErrorFound != NoError) {
6666 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6667 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006668 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6669 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00006670 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006671 }
6672 if (CurContext->isDependentContext())
Alexey Bataev62cec442014-11-18 10:14:22 +00006673 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00006674 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006675 enum {
6676 NotAnExpression,
6677 NotAnAssignmentOp,
6678 NotAScalarType,
6679 NotAnLValue,
6680 NoError
6681 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006682 SourceLocation ErrorLoc, NoteLoc;
6683 SourceRange ErrorRange, NoteRange;
6684 // If clause is write:
6685 // x = expr;
Alexey Bataeve3727102018-04-18 15:57:46 +00006686 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
6687 const auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006688 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6689 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00006690 X = AtomicBinOp->getLHS();
6691 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00006692 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6693 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6694 if (!X->isLValue()) {
6695 ErrorFound = NotAnLValue;
6696 ErrorLoc = AtomicBinOp->getExprLoc();
6697 ErrorRange = AtomicBinOp->getSourceRange();
6698 NoteLoc = X->getExprLoc();
6699 NoteRange = X->getSourceRange();
6700 }
6701 } else if (!X->isInstantiationDependent() ||
6702 !E->isInstantiationDependent()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006703 const Expr *NotScalarExpr =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006704 (X->isInstantiationDependent() || X->getType()->isScalarType())
6705 ? E
6706 : X;
6707 ErrorFound = NotAScalarType;
6708 ErrorLoc = AtomicBinOp->getExprLoc();
6709 ErrorRange = AtomicBinOp->getSourceRange();
6710 NoteLoc = NotScalarExpr->getExprLoc();
6711 NoteRange = NotScalarExpr->getSourceRange();
6712 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006713 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00006714 ErrorFound = NotAnAssignmentOp;
6715 ErrorLoc = AtomicBody->getExprLoc();
6716 ErrorRange = AtomicBody->getSourceRange();
6717 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6718 : AtomicBody->getExprLoc();
6719 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6720 : AtomicBody->getSourceRange();
6721 }
6722 } else {
6723 ErrorFound = NotAnExpression;
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006724 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevf33eba62014-11-28 07:21:40 +00006725 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006726 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006727 if (ErrorFound != NoError) {
6728 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6729 << ErrorRange;
6730 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6731 << NoteRange;
6732 return StmtError();
Alexey Bataeve3727102018-04-18 15:57:46 +00006733 }
6734 if (CurContext->isDependentContext())
Alexey Bataevf33eba62014-11-28 07:21:40 +00006735 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006736 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006737 // If clause is update:
6738 // x++;
6739 // x--;
6740 // ++x;
6741 // --x;
6742 // x binop= expr;
6743 // x = x binop expr;
6744 // x = expr binop x;
6745 OpenMPAtomicUpdateChecker Checker(*this);
6746 if (Checker.checkStatement(
6747 Body, (AtomicKind == OMPC_update)
6748 ? diag::err_omp_atomic_update_not_expression_statement
6749 : diag::err_omp_atomic_not_expression_statement,
6750 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006751 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006752 if (!CurContext->isDependentContext()) {
6753 E = Checker.getExpr();
6754 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006755 UE = Checker.getUpdateExpr();
6756 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006757 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006758 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006759 enum {
6760 NotAnAssignmentOp,
6761 NotACompoundStatement,
6762 NotTwoSubstatements,
6763 NotASpecificExpression,
6764 NoError
6765 } ErrorFound = NoError;
6766 SourceLocation ErrorLoc, NoteLoc;
6767 SourceRange ErrorRange, NoteRange;
Alexey Bataeve3727102018-04-18 15:57:46 +00006768 if (const auto *AtomicBody = dyn_cast<Expr>(Body)) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006769 // If clause is a capture:
6770 // v = x++;
6771 // v = x--;
6772 // v = ++x;
6773 // v = --x;
6774 // v = x binop= expr;
6775 // v = x = x binop expr;
6776 // v = x = expr binop x;
Alexey Bataeve3727102018-04-18 15:57:46 +00006777 const auto *AtomicBinOp =
Alexey Bataevb78ca832015-04-01 03:33:17 +00006778 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6779 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6780 V = AtomicBinOp->getLHS();
6781 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6782 OpenMPAtomicUpdateChecker Checker(*this);
6783 if (Checker.checkStatement(
6784 Body, diag::err_omp_atomic_capture_not_expression_statement,
6785 diag::note_omp_atomic_update))
6786 return StmtError();
6787 E = Checker.getExpr();
6788 X = Checker.getX();
6789 UE = Checker.getUpdateExpr();
6790 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6791 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006792 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006793 ErrorLoc = AtomicBody->getExprLoc();
6794 ErrorRange = AtomicBody->getSourceRange();
6795 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6796 : AtomicBody->getExprLoc();
6797 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6798 : AtomicBody->getSourceRange();
6799 ErrorFound = NotAnAssignmentOp;
6800 }
6801 if (ErrorFound != NoError) {
6802 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6803 << ErrorRange;
6804 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6805 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006806 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006807 if (CurContext->isDependentContext())
6808 UE = V = E = X = nullptr;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006809 } else {
6810 // If clause is a capture:
6811 // { v = x; x = expr; }
6812 // { v = x; x++; }
6813 // { v = x; x--; }
6814 // { v = x; ++x; }
6815 // { v = x; --x; }
6816 // { v = x; x binop= expr; }
6817 // { v = x; x = x binop expr; }
6818 // { v = x; x = expr binop x; }
6819 // { x++; v = x; }
6820 // { x--; v = x; }
6821 // { ++x; v = x; }
6822 // { --x; v = x; }
6823 // { x binop= expr; v = x; }
6824 // { x = x binop expr; v = x; }
6825 // { x = expr binop x; v = x; }
6826 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6827 // Check that this is { expr1; expr2; }
6828 if (CS->size() == 2) {
Alexey Bataeve3727102018-04-18 15:57:46 +00006829 Stmt *First = CS->body_front();
6830 Stmt *Second = CS->body_back();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006831 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6832 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6833 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6834 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6835 // Need to find what subexpression is 'v' and what is 'x'.
6836 OpenMPAtomicUpdateChecker Checker(*this);
6837 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6838 BinaryOperator *BinOp = nullptr;
6839 if (IsUpdateExprFound) {
6840 BinOp = dyn_cast<BinaryOperator>(First);
6841 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6842 }
6843 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6844 // { v = x; x++; }
6845 // { v = x; x--; }
6846 // { v = x; ++x; }
6847 // { v = x; --x; }
6848 // { v = x; x binop= expr; }
6849 // { v = x; x = x binop expr; }
6850 // { v = x; x = expr binop x; }
6851 // Check that the first expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00006852 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006853 llvm::FoldingSetNodeID XId, PossibleXId;
6854 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6855 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6856 IsUpdateExprFound = XId == PossibleXId;
6857 if (IsUpdateExprFound) {
6858 V = BinOp->getLHS();
6859 X = Checker.getX();
6860 E = Checker.getExpr();
6861 UE = Checker.getUpdateExpr();
6862 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006863 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006864 }
6865 }
6866 if (!IsUpdateExprFound) {
6867 IsUpdateExprFound = !Checker.checkStatement(First);
6868 BinOp = nullptr;
6869 if (IsUpdateExprFound) {
6870 BinOp = dyn_cast<BinaryOperator>(Second);
6871 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6872 }
6873 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6874 // { x++; v = x; }
6875 // { x--; v = x; }
6876 // { ++x; v = x; }
6877 // { --x; v = x; }
6878 // { x binop= expr; v = x; }
6879 // { x = x binop expr; v = x; }
6880 // { x = expr binop x; v = x; }
6881 // Check that the second expression has form v = x.
Alexey Bataeve3727102018-04-18 15:57:46 +00006882 Expr *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006883 llvm::FoldingSetNodeID XId, PossibleXId;
6884 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6885 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6886 IsUpdateExprFound = XId == PossibleXId;
6887 if (IsUpdateExprFound) {
6888 V = BinOp->getLHS();
6889 X = Checker.getX();
6890 E = Checker.getExpr();
6891 UE = Checker.getUpdateExpr();
6892 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006893 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006894 }
6895 }
6896 }
6897 if (!IsUpdateExprFound) {
6898 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006899 auto *FirstExpr = dyn_cast<Expr>(First);
6900 auto *SecondExpr = dyn_cast<Expr>(Second);
6901 if (!FirstExpr || !SecondExpr ||
6902 !(FirstExpr->isInstantiationDependent() ||
6903 SecondExpr->isInstantiationDependent())) {
6904 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6905 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006906 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006907 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006908 : First->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00006909 NoteRange = ErrorRange = FirstBinOp
6910 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006911 : SourceRange(ErrorLoc, ErrorLoc);
6912 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006913 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6914 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6915 ErrorFound = NotAnAssignmentOp;
6916 NoteLoc = ErrorLoc = SecondBinOp
6917 ? SecondBinOp->getOperatorLoc()
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006918 : Second->getBeginLoc();
Alexey Bataev5a195472015-09-04 12:55:50 +00006919 NoteRange = ErrorRange =
6920 SecondBinOp ? SecondBinOp->getSourceRange()
6921 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006922 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00006923 Expr *PossibleXRHSInFirst =
Alexey Bataev5a195472015-09-04 12:55:50 +00006924 FirstBinOp->getRHS()->IgnoreParenImpCasts();
Alexey Bataeve3727102018-04-18 15:57:46 +00006925 Expr *PossibleXLHSInSecond =
Alexey Bataev5a195472015-09-04 12:55:50 +00006926 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6927 llvm::FoldingSetNodeID X1Id, X2Id;
6928 PossibleXRHSInFirst->Profile(X1Id, Context,
6929 /*Canonical=*/true);
6930 PossibleXLHSInSecond->Profile(X2Id, Context,
6931 /*Canonical=*/true);
6932 IsUpdateExprFound = X1Id == X2Id;
6933 if (IsUpdateExprFound) {
6934 V = FirstBinOp->getLHS();
6935 X = SecondBinOp->getLHS();
6936 E = SecondBinOp->getRHS();
6937 UE = nullptr;
6938 IsXLHSInRHSPart = false;
6939 IsPostfixUpdate = true;
6940 } else {
6941 ErrorFound = NotASpecificExpression;
6942 ErrorLoc = FirstBinOp->getExprLoc();
6943 ErrorRange = FirstBinOp->getSourceRange();
6944 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6945 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6946 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006947 }
6948 }
6949 }
6950 }
6951 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006952 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006953 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006954 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00006955 ErrorFound = NotTwoSubstatements;
6956 }
6957 } else {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006958 NoteLoc = ErrorLoc = Body->getBeginLoc();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006959 NoteRange = ErrorRange =
Stephen Kellyf2ceec42018-08-09 21:08:08 +00006960 SourceRange(Body->getBeginLoc(), Body->getBeginLoc());
Alexey Bataevb78ca832015-04-01 03:33:17 +00006961 ErrorFound = NotACompoundStatement;
6962 }
6963 if (ErrorFound != NoError) {
6964 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6965 << ErrorRange;
6966 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6967 return StmtError();
Alexey Bataevb78ca832015-04-01 03:33:17 +00006968 }
Alexey Bataeve3727102018-04-18 15:57:46 +00006969 if (CurContext->isDependentContext())
6970 UE = V = E = X = nullptr;
Alexey Bataev459dec02014-07-24 06:46:57 +00006971 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006972 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006973
Reid Kleckner87a31802018-03-12 21:43:02 +00006974 setFunctionHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00006975
Alexey Bataev62cec442014-11-18 10:14:22 +00006976 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006977 X, V, E, UE, IsXLHSInRHSPart,
6978 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006979}
6980
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006981StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6982 Stmt *AStmt,
6983 SourceLocation StartLoc,
6984 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006985 if (!AStmt)
6986 return StmtError();
6987
Alexey Bataeve3727102018-04-18 15:57:46 +00006988 auto *CS = cast<CapturedStmt>(AStmt);
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006989 // 1.2.2 OpenMP Language Terminology
6990 // Structured block - An executable statement with a single entry at the
6991 // top and a single exit at the bottom.
6992 // The point of exit cannot be a branch out of the structured block.
6993 // longjmp() and throw() must not violate the entry/exit criteria.
6994 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00006995 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
6996 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6997 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6998 // 1.2.2 OpenMP Language Terminology
6999 // Structured block - An executable statement with a single entry at the
7000 // top and a single exit at the bottom.
7001 // The point of exit cannot be a branch out of the structured block.
7002 // longjmp() and throw() must not violate the entry/exit criteria.
7003 CS->getCapturedDecl()->setNothrow();
7004 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007005
Alexey Bataev13314bf2014-10-09 04:18:56 +00007006 // OpenMP [2.16, Nesting of Regions]
7007 // If specified, a teams construct must be contained within a target
7008 // construct. That target construct must contain no statements or directives
7009 // outside of the teams construct.
7010 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007011 const Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007012 bool OMPTeamsFound = true;
Alexey Bataeve3727102018-04-18 15:57:46 +00007013 if (const auto *CS = dyn_cast<CompoundStmt>(S)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00007014 auto I = CS->body_begin();
7015 while (I != CS->body_end()) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007016 const auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007017 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
7018 OMPTeamsFound = false;
7019 break;
7020 }
7021 ++I;
7022 }
7023 assert(I != CS->body_end() && "Not found statement");
7024 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00007025 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +00007026 const auto *OED = dyn_cast<OMPExecutableDirective>(S);
Kelvin Li3834dce2016-06-27 19:15:43 +00007027 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00007028 }
7029 if (!OMPTeamsFound) {
7030 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
7031 Diag(DSAStack->getInnerTeamsRegionLoc(),
7032 diag::note_omp_nested_teams_construct_here);
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007033 Diag(S->getBeginLoc(), diag::note_omp_nested_statement_here)
Alexey Bataev13314bf2014-10-09 04:18:56 +00007034 << isa<OMPExecutableDirective>(S);
7035 return StmtError();
7036 }
7037 }
7038
Reid Kleckner87a31802018-03-12 21:43:02 +00007039 setFunctionHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00007040
7041 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7042}
7043
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007044StmtResult
7045Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
7046 Stmt *AStmt, SourceLocation StartLoc,
7047 SourceLocation EndLoc) {
7048 if (!AStmt)
7049 return StmtError();
7050
Alexey Bataeve3727102018-04-18 15:57:46 +00007051 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007052 // 1.2.2 OpenMP Language Terminology
7053 // Structured block - An executable statement with a single entry at the
7054 // top and a single exit at the bottom.
7055 // The point of exit cannot be a branch out of the structured block.
7056 // longjmp() and throw() must not violate the entry/exit criteria.
7057 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00007058 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
7059 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7060 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7061 // 1.2.2 OpenMP Language Terminology
7062 // Structured block - An executable statement with a single entry at the
7063 // top and a single exit at the bottom.
7064 // The point of exit cannot be a branch out of the structured block.
7065 // longjmp() and throw() must not violate the entry/exit criteria.
7066 CS->getCapturedDecl()->setNothrow();
7067 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007068
Reid Kleckner87a31802018-03-12 21:43:02 +00007069 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00007070
7071 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7072 AStmt);
7073}
7074
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007075StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
7076 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007077 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007078 if (!AStmt)
7079 return StmtError();
7080
Alexey Bataeve3727102018-04-18 15:57:46 +00007081 auto *CS = cast<CapturedStmt>(AStmt);
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007082 // 1.2.2 OpenMP Language Terminology
7083 // Structured block - An executable statement with a single entry at the
7084 // top and a single exit at the bottom.
7085 // The point of exit cannot be a branch out of the structured block.
7086 // longjmp() and throw() must not violate the entry/exit criteria.
7087 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007088 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7089 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7090 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7091 // 1.2.2 OpenMP Language Terminology
7092 // Structured block - An executable statement with a single entry at the
7093 // top and a single exit at the bottom.
7094 // The point of exit cannot be a branch out of the structured block.
7095 // longjmp() and throw() must not violate the entry/exit criteria.
7096 CS->getCapturedDecl()->setNothrow();
7097 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007098
7099 OMPLoopDirective::HelperExprs B;
7100 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7101 // define the nested loops number.
7102 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007103 checkOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007104 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007105 VarsWithImplicitDSA, B);
7106 if (NestedLoopCount == 0)
7107 return StmtError();
7108
7109 assert((CurContext->isDependentContext() || B.builtAll()) &&
7110 "omp target parallel for loop exprs were not built");
7111
7112 if (!CurContext->isDependentContext()) {
7113 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007114 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007115 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007116 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007117 B.NumIterations, *this, CurScope,
7118 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007119 return StmtError();
7120 }
7121 }
7122
Reid Kleckner87a31802018-03-12 21:43:02 +00007123 setFunctionHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00007124 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
7125 NestedLoopCount, Clauses, AStmt,
7126 B, DSAStack->isCancelRegion());
7127}
7128
Alexey Bataev95b64a92017-05-30 16:00:04 +00007129/// Check for existence of a map clause in the list of clauses.
7130static bool hasClauses(ArrayRef<OMPClause *> Clauses,
7131 const OpenMPClauseKind K) {
7132 return llvm::any_of(
7133 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
7134}
Samuel Antaodf67fc42016-01-19 19:15:56 +00007135
Alexey Bataev95b64a92017-05-30 16:00:04 +00007136template <typename... Params>
7137static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
7138 const Params... ClauseTypes) {
7139 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007140}
7141
Michael Wong65f367f2015-07-21 13:44:28 +00007142StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
7143 Stmt *AStmt,
7144 SourceLocation StartLoc,
7145 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007146 if (!AStmt)
7147 return StmtError();
7148
7149 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7150
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007151 // OpenMP [2.10.1, Restrictions, p. 97]
7152 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007153 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
7154 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7155 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00007156 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00007157 return StmtError();
7158 }
7159
Reid Kleckner87a31802018-03-12 21:43:02 +00007160 setFunctionHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00007161
7162 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7163 AStmt);
7164}
7165
Samuel Antaodf67fc42016-01-19 19:15:56 +00007166StmtResult
7167Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
7168 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007169 SourceLocation EndLoc, Stmt *AStmt) {
7170 if (!AStmt)
7171 return StmtError();
7172
Alexey Bataeve3727102018-04-18 15:57:46 +00007173 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007174 // 1.2.2 OpenMP Language Terminology
7175 // Structured block - An executable statement with a single entry at the
7176 // top and a single exit at the bottom.
7177 // The point of exit cannot be a branch out of the structured block.
7178 // longjmp() and throw() must not violate the entry/exit criteria.
7179 CS->getCapturedDecl()->setNothrow();
7180 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
7181 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7182 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7183 // 1.2.2 OpenMP Language Terminology
7184 // Structured block - An executable statement with a single entry at the
7185 // top and a single exit at the bottom.
7186 // The point of exit cannot be a branch out of the structured block.
7187 // longjmp() and throw() must not violate the entry/exit criteria.
7188 CS->getCapturedDecl()->setNothrow();
7189 }
7190
Samuel Antaodf67fc42016-01-19 19:15:56 +00007191 // OpenMP [2.10.2, Restrictions, p. 99]
7192 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007193 if (!hasClauses(Clauses, OMPC_map)) {
7194 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7195 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007196 return StmtError();
7197 }
7198
Alexey Bataev7828b252017-11-21 17:08:48 +00007199 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7200 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00007201}
7202
Samuel Antao72590762016-01-19 20:04:50 +00007203StmtResult
7204Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
7205 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007206 SourceLocation EndLoc, Stmt *AStmt) {
7207 if (!AStmt)
7208 return StmtError();
7209
Alexey Bataeve3727102018-04-18 15:57:46 +00007210 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007211 // 1.2.2 OpenMP Language Terminology
7212 // Structured block - An executable statement with a single entry at the
7213 // top and a single exit at the bottom.
7214 // The point of exit cannot be a branch out of the structured block.
7215 // longjmp() and throw() must not violate the entry/exit criteria.
7216 CS->getCapturedDecl()->setNothrow();
7217 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
7218 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7219 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7220 // 1.2.2 OpenMP Language Terminology
7221 // Structured block - An executable statement with a single entry at the
7222 // top and a single exit at the bottom.
7223 // The point of exit cannot be a branch out of the structured block.
7224 // longjmp() and throw() must not violate the entry/exit criteria.
7225 CS->getCapturedDecl()->setNothrow();
7226 }
7227
Samuel Antao72590762016-01-19 20:04:50 +00007228 // OpenMP [2.10.3, Restrictions, p. 102]
7229 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00007230 if (!hasClauses(Clauses, OMPC_map)) {
7231 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
7232 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00007233 return StmtError();
7234 }
7235
Alexey Bataev7828b252017-11-21 17:08:48 +00007236 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
7237 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00007238}
7239
Samuel Antao686c70c2016-05-26 17:30:50 +00007240StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
7241 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00007242 SourceLocation EndLoc,
7243 Stmt *AStmt) {
7244 if (!AStmt)
7245 return StmtError();
7246
Alexey Bataeve3727102018-04-18 15:57:46 +00007247 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev7828b252017-11-21 17:08:48 +00007248 // 1.2.2 OpenMP Language Terminology
7249 // Structured block - An executable statement with a single entry at the
7250 // top and a single exit at the bottom.
7251 // The point of exit cannot be a branch out of the structured block.
7252 // longjmp() and throw() must not violate the entry/exit criteria.
7253 CS->getCapturedDecl()->setNothrow();
7254 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
7255 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7256 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7257 // 1.2.2 OpenMP Language Terminology
7258 // Structured block - An executable statement with a single entry at the
7259 // top and a single exit at the bottom.
7260 // The point of exit cannot be a branch out of the structured block.
7261 // longjmp() and throw() must not violate the entry/exit criteria.
7262 CS->getCapturedDecl()->setNothrow();
7263 }
7264
Alexey Bataev95b64a92017-05-30 16:00:04 +00007265 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00007266 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
7267 return StmtError();
7268 }
Alexey Bataev7828b252017-11-21 17:08:48 +00007269 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
7270 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00007271}
7272
Alexey Bataev13314bf2014-10-09 04:18:56 +00007273StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
7274 Stmt *AStmt, SourceLocation StartLoc,
7275 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007276 if (!AStmt)
7277 return StmtError();
7278
Alexey Bataeve3727102018-04-18 15:57:46 +00007279 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev13314bf2014-10-09 04:18:56 +00007280 // 1.2.2 OpenMP Language Terminology
7281 // Structured block - An executable statement with a single entry at the
7282 // top and a single exit at the bottom.
7283 // The point of exit cannot be a branch out of the structured block.
7284 // longjmp() and throw() must not violate the entry/exit criteria.
7285 CS->getCapturedDecl()->setNothrow();
7286
Reid Kleckner87a31802018-03-12 21:43:02 +00007287 setFunctionHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00007288
Alexey Bataevceabd412017-11-30 18:01:54 +00007289 DSAStack->setParentTeamsRegionLoc(StartLoc);
7290
Alexey Bataev13314bf2014-10-09 04:18:56 +00007291 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
7292}
7293
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007294StmtResult
7295Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
7296 SourceLocation EndLoc,
7297 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00007298 if (DSAStack->isParentNowaitRegion()) {
7299 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
7300 return StmtError();
7301 }
7302 if (DSAStack->isParentOrderedRegion()) {
7303 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
7304 return StmtError();
7305 }
7306 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
7307 CancelRegion);
7308}
7309
Alexey Bataev87933c72015-09-18 08:07:34 +00007310StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
7311 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00007312 SourceLocation EndLoc,
7313 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00007314 if (DSAStack->isParentNowaitRegion()) {
7315 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
7316 return StmtError();
7317 }
7318 if (DSAStack->isParentOrderedRegion()) {
7319 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
7320 return StmtError();
7321 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00007322 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00007323 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
7324 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00007325}
7326
Alexey Bataev382967a2015-12-08 12:06:20 +00007327static bool checkGrainsizeNumTasksClauses(Sema &S,
7328 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007329 const OMPClause *PrevClause = nullptr;
Alexey Bataev382967a2015-12-08 12:06:20 +00007330 bool ErrorFound = false;
Alexey Bataeve3727102018-04-18 15:57:46 +00007331 for (const OMPClause *C : Clauses) {
Alexey Bataev382967a2015-12-08 12:06:20 +00007332 if (C->getClauseKind() == OMPC_grainsize ||
7333 C->getClauseKind() == OMPC_num_tasks) {
7334 if (!PrevClause)
7335 PrevClause = C;
7336 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007337 S.Diag(C->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007338 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
7339 << getOpenMPClauseName(C->getClauseKind())
7340 << getOpenMPClauseName(PrevClause->getClauseKind());
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007341 S.Diag(PrevClause->getBeginLoc(),
Alexey Bataev382967a2015-12-08 12:06:20 +00007342 diag::note_omp_previous_grainsize_num_tasks)
7343 << getOpenMPClauseName(PrevClause->getClauseKind());
7344 ErrorFound = true;
7345 }
7346 }
7347 }
7348 return ErrorFound;
7349}
7350
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007351static bool checkReductionClauseWithNogroup(Sema &S,
7352 ArrayRef<OMPClause *> Clauses) {
Alexey Bataeve3727102018-04-18 15:57:46 +00007353 const OMPClause *ReductionClause = nullptr;
7354 const OMPClause *NogroupClause = nullptr;
7355 for (const OMPClause *C : Clauses) {
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007356 if (C->getClauseKind() == OMPC_reduction) {
7357 ReductionClause = C;
7358 if (NogroupClause)
7359 break;
7360 continue;
7361 }
7362 if (C->getClauseKind() == OMPC_nogroup) {
7363 NogroupClause = C;
7364 if (ReductionClause)
7365 break;
7366 continue;
7367 }
7368 }
7369 if (ReductionClause && NogroupClause) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00007370 S.Diag(ReductionClause->getBeginLoc(), diag::err_omp_reduction_with_nogroup)
7371 << SourceRange(NogroupClause->getBeginLoc(),
Stephen Kelly1c301dc2018-08-09 21:09:38 +00007372 NogroupClause->getEndLoc());
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007373 return true;
7374 }
7375 return false;
7376}
7377
Alexey Bataev49f6e782015-12-01 04:18:41 +00007378StmtResult Sema::ActOnOpenMPTaskLoopDirective(
7379 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007380 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00007381 if (!AStmt)
7382 return StmtError();
7383
7384 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7385 OMPLoopDirective::HelperExprs B;
7386 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7387 // define the nested loops number.
7388 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007389 checkOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007390 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00007391 VarsWithImplicitDSA, B);
7392 if (NestedLoopCount == 0)
7393 return StmtError();
7394
7395 assert((CurContext->isDependentContext() || B.builtAll()) &&
7396 "omp for loop exprs were not built");
7397
Alexey Bataev382967a2015-12-08 12:06:20 +00007398 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7399 // The grainsize clause and num_tasks clause are mutually exclusive and may
7400 // not appear on the same taskloop directive.
7401 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7402 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007403 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7404 // If a reduction clause is present on the taskloop directive, the nogroup
7405 // clause must not be specified.
7406 if (checkReductionClauseWithNogroup(*this, Clauses))
7407 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007408
Reid Kleckner87a31802018-03-12 21:43:02 +00007409 setFunctionHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00007410 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
7411 NestedLoopCount, Clauses, AStmt, B);
7412}
7413
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007414StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
7415 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007416 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007417 if (!AStmt)
7418 return StmtError();
7419
7420 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7421 OMPLoopDirective::HelperExprs B;
7422 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7423 // define the nested loops number.
7424 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007425 checkOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007426 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
7427 VarsWithImplicitDSA, B);
7428 if (NestedLoopCount == 0)
7429 return StmtError();
7430
7431 assert((CurContext->isDependentContext() || B.builtAll()) &&
7432 "omp for loop exprs were not built");
7433
Alexey Bataev5a3af132016-03-29 08:58:54 +00007434 if (!CurContext->isDependentContext()) {
7435 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007436 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007437 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007438 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00007439 B.NumIterations, *this, CurScope,
7440 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00007441 return StmtError();
7442 }
7443 }
7444
Alexey Bataev382967a2015-12-08 12:06:20 +00007445 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7446 // The grainsize clause and num_tasks clause are mutually exclusive and may
7447 // not appear on the same taskloop directive.
7448 if (checkGrainsizeNumTasksClauses(*this, Clauses))
7449 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00007450 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
7451 // If a reduction clause is present on the taskloop directive, the nogroup
7452 // clause must not be specified.
7453 if (checkReductionClauseWithNogroup(*this, Clauses))
7454 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00007455 if (checkSimdlenSafelenSpecified(*this, Clauses))
7456 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00007457
Reid Kleckner87a31802018-03-12 21:43:02 +00007458 setFunctionHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00007459 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
7460 NestedLoopCount, Clauses, AStmt, B);
7461}
7462
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007463StmtResult Sema::ActOnOpenMPDistributeDirective(
7464 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007465 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007466 if (!AStmt)
7467 return StmtError();
7468
7469 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
7470 OMPLoopDirective::HelperExprs B;
7471 // In presence of clause 'collapse' with number of loops, it will
7472 // define the nested loops number.
7473 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007474 checkOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007475 nullptr /*ordered not a clause on distribute*/, AStmt,
7476 *this, *DSAStack, VarsWithImplicitDSA, B);
7477 if (NestedLoopCount == 0)
7478 return StmtError();
7479
7480 assert((CurContext->isDependentContext() || B.builtAll()) &&
7481 "omp for loop exprs were not built");
7482
Reid Kleckner87a31802018-03-12 21:43:02 +00007483 setFunctionHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00007484 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
7485 NestedLoopCount, Clauses, AStmt, B);
7486}
7487
Carlo Bertolli9925f152016-06-27 14:55:37 +00007488StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
7489 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007490 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00007491 if (!AStmt)
7492 return StmtError();
7493
Alexey Bataeve3727102018-04-18 15:57:46 +00007494 auto *CS = cast<CapturedStmt>(AStmt);
Carlo Bertolli9925f152016-06-27 14:55:37 +00007495 // 1.2.2 OpenMP Language Terminology
7496 // Structured block - An executable statement with a single entry at the
7497 // top and a single exit at the bottom.
7498 // The point of exit cannot be a branch out of the structured block.
7499 // longjmp() and throw() must not violate the entry/exit criteria.
7500 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00007501 for (int ThisCaptureLevel =
7502 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
7503 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7504 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7505 // 1.2.2 OpenMP Language Terminology
7506 // Structured block - An executable statement with a single entry at the
7507 // top and a single exit at the bottom.
7508 // The point of exit cannot be a branch out of the structured block.
7509 // longjmp() and throw() must not violate the entry/exit criteria.
7510 CS->getCapturedDecl()->setNothrow();
7511 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00007512
7513 OMPLoopDirective::HelperExprs B;
7514 // In presence of clause 'collapse' with number of loops, it will
7515 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007516 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli9925f152016-06-27 14:55:37 +00007517 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00007518 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00007519 VarsWithImplicitDSA, B);
7520 if (NestedLoopCount == 0)
7521 return StmtError();
7522
7523 assert((CurContext->isDependentContext() || B.builtAll()) &&
7524 "omp for loop exprs were not built");
7525
Reid Kleckner87a31802018-03-12 21:43:02 +00007526 setFunctionHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007527 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007528 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7529 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00007530}
7531
Kelvin Li4a39add2016-07-05 05:00:15 +00007532StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7533 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007534 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4a39add2016-07-05 05:00:15 +00007535 if (!AStmt)
7536 return StmtError();
7537
Alexey Bataeve3727102018-04-18 15:57:46 +00007538 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4a39add2016-07-05 05:00:15 +00007539 // 1.2.2 OpenMP Language Terminology
7540 // Structured block - An executable statement with a single entry at the
7541 // top and a single exit at the bottom.
7542 // The point of exit cannot be a branch out of the structured block.
7543 // longjmp() and throw() must not violate the entry/exit criteria.
7544 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00007545 for (int ThisCaptureLevel =
7546 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7547 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7548 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7549 // 1.2.2 OpenMP Language Terminology
7550 // Structured block - An executable statement with a single entry at the
7551 // top and a single exit at the bottom.
7552 // The point of exit cannot be a branch out of the structured block.
7553 // longjmp() and throw() must not violate the entry/exit criteria.
7554 CS->getCapturedDecl()->setNothrow();
7555 }
Kelvin Li4a39add2016-07-05 05:00:15 +00007556
7557 OMPLoopDirective::HelperExprs B;
7558 // In presence of clause 'collapse' with number of loops, it will
7559 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007560 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li4a39add2016-07-05 05:00:15 +00007561 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00007562 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00007563 VarsWithImplicitDSA, B);
7564 if (NestedLoopCount == 0)
7565 return StmtError();
7566
7567 assert((CurContext->isDependentContext() || B.builtAll()) &&
7568 "omp for loop exprs were not built");
7569
Alexey Bataev438388c2017-11-22 18:34:02 +00007570 if (!CurContext->isDependentContext()) {
7571 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007572 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007573 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7574 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7575 B.NumIterations, *this, CurScope,
7576 DSAStack))
7577 return StmtError();
7578 }
7579 }
7580
Kelvin Lic5609492016-07-15 04:39:07 +00007581 if (checkSimdlenSafelenSpecified(*this, Clauses))
7582 return StmtError();
7583
Reid Kleckner87a31802018-03-12 21:43:02 +00007584 setFunctionHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00007585 return OMPDistributeParallelForSimdDirective::Create(
7586 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7587}
7588
Kelvin Li787f3fc2016-07-06 04:45:38 +00007589StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7590 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007591 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li787f3fc2016-07-06 04:45:38 +00007592 if (!AStmt)
7593 return StmtError();
7594
Alexey Bataeve3727102018-04-18 15:57:46 +00007595 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007596 // 1.2.2 OpenMP Language Terminology
7597 // Structured block - An executable statement with a single entry at the
7598 // top and a single exit at the bottom.
7599 // The point of exit cannot be a branch out of the structured block.
7600 // longjmp() and throw() must not violate the entry/exit criteria.
7601 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00007602 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7603 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7604 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7605 // 1.2.2 OpenMP Language Terminology
7606 // Structured block - An executable statement with a single entry at the
7607 // top and a single exit at the bottom.
7608 // The point of exit cannot be a branch out of the structured block.
7609 // longjmp() and throw() must not violate the entry/exit criteria.
7610 CS->getCapturedDecl()->setNothrow();
7611 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007612
7613 OMPLoopDirective::HelperExprs B;
7614 // In presence of clause 'collapse' with number of loops, it will
7615 // define the nested loops number.
7616 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007617 checkOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007618 nullptr /*ordered not a clause on distribute*/, CS, *this,
7619 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007620 if (NestedLoopCount == 0)
7621 return StmtError();
7622
7623 assert((CurContext->isDependentContext() || B.builtAll()) &&
7624 "omp for loop exprs were not built");
7625
Alexey Bataev438388c2017-11-22 18:34:02 +00007626 if (!CurContext->isDependentContext()) {
7627 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007628 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00007629 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7630 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7631 B.NumIterations, *this, CurScope,
7632 DSAStack))
7633 return StmtError();
7634 }
7635 }
7636
Kelvin Lic5609492016-07-15 04:39:07 +00007637 if (checkSimdlenSafelenSpecified(*this, Clauses))
7638 return StmtError();
7639
Reid Kleckner87a31802018-03-12 21:43:02 +00007640 setFunctionHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00007641 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7642 NestedLoopCount, Clauses, AStmt, B);
7643}
7644
Kelvin Lia579b912016-07-14 02:54:56 +00007645StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7646 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007647 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lia579b912016-07-14 02:54:56 +00007648 if (!AStmt)
7649 return StmtError();
7650
Alexey Bataeve3727102018-04-18 15:57:46 +00007651 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Lia579b912016-07-14 02:54:56 +00007652 // 1.2.2 OpenMP Language Terminology
7653 // Structured block - An executable statement with a single entry at the
7654 // top and a single exit at the bottom.
7655 // The point of exit cannot be a branch out of the structured block.
7656 // longjmp() and throw() must not violate the entry/exit criteria.
7657 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007658 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7659 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7660 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7661 // 1.2.2 OpenMP Language Terminology
7662 // Structured block - An executable statement with a single entry at the
7663 // top and a single exit at the bottom.
7664 // The point of exit cannot be a branch out of the structured block.
7665 // longjmp() and throw() must not violate the entry/exit criteria.
7666 CS->getCapturedDecl()->setNothrow();
7667 }
Kelvin Lia579b912016-07-14 02:54:56 +00007668
7669 OMPLoopDirective::HelperExprs B;
7670 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7671 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007672 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lia579b912016-07-14 02:54:56 +00007673 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007674 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00007675 VarsWithImplicitDSA, B);
7676 if (NestedLoopCount == 0)
7677 return StmtError();
7678
7679 assert((CurContext->isDependentContext() || B.builtAll()) &&
7680 "omp target parallel for simd loop exprs were not built");
7681
7682 if (!CurContext->isDependentContext()) {
7683 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007684 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007685 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00007686 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7687 B.NumIterations, *this, CurScope,
7688 DSAStack))
7689 return StmtError();
7690 }
7691 }
Kelvin Lic5609492016-07-15 04:39:07 +00007692 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00007693 return StmtError();
7694
Reid Kleckner87a31802018-03-12 21:43:02 +00007695 setFunctionHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00007696 return OMPTargetParallelForSimdDirective::Create(
7697 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7698}
7699
Kelvin Li986330c2016-07-20 22:57:10 +00007700StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7701 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007702 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li986330c2016-07-20 22:57:10 +00007703 if (!AStmt)
7704 return StmtError();
7705
Alexey Bataeve3727102018-04-18 15:57:46 +00007706 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li986330c2016-07-20 22:57:10 +00007707 // 1.2.2 OpenMP Language Terminology
7708 // Structured block - An executable statement with a single entry at the
7709 // top and a single exit at the bottom.
7710 // The point of exit cannot be a branch out of the structured block.
7711 // longjmp() and throw() must not violate the entry/exit criteria.
7712 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00007713 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7714 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7715 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7716 // 1.2.2 OpenMP Language Terminology
7717 // Structured block - An executable statement with a single entry at the
7718 // top and a single exit at the bottom.
7719 // The point of exit cannot be a branch out of the structured block.
7720 // longjmp() and throw() must not violate the entry/exit criteria.
7721 CS->getCapturedDecl()->setNothrow();
7722 }
7723
Kelvin Li986330c2016-07-20 22:57:10 +00007724 OMPLoopDirective::HelperExprs B;
7725 // In presence of clause 'collapse' with number of loops, it will define the
7726 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00007727 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007728 checkOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00007729 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00007730 VarsWithImplicitDSA, B);
7731 if (NestedLoopCount == 0)
7732 return StmtError();
7733
7734 assert((CurContext->isDependentContext() || B.builtAll()) &&
7735 "omp target simd loop exprs were not built");
7736
7737 if (!CurContext->isDependentContext()) {
7738 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007739 for (OMPClause *C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007740 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00007741 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7742 B.NumIterations, *this, CurScope,
7743 DSAStack))
7744 return StmtError();
7745 }
7746 }
7747
7748 if (checkSimdlenSafelenSpecified(*this, Clauses))
7749 return StmtError();
7750
Reid Kleckner87a31802018-03-12 21:43:02 +00007751 setFunctionHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00007752 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7753 NestedLoopCount, Clauses, AStmt, B);
7754}
7755
Kelvin Li02532872016-08-05 14:37:37 +00007756StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7757 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007758 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li02532872016-08-05 14:37:37 +00007759 if (!AStmt)
7760 return StmtError();
7761
Alexey Bataeve3727102018-04-18 15:57:46 +00007762 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li02532872016-08-05 14:37:37 +00007763 // 1.2.2 OpenMP Language Terminology
7764 // Structured block - An executable statement with a single entry at the
7765 // top and a single exit at the bottom.
7766 // The point of exit cannot be a branch out of the structured block.
7767 // longjmp() and throw() must not violate the entry/exit criteria.
7768 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007769 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7770 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7771 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7772 // 1.2.2 OpenMP Language Terminology
7773 // Structured block - An executable statement with a single entry at the
7774 // top and a single exit at the bottom.
7775 // The point of exit cannot be a branch out of the structured block.
7776 // longjmp() and throw() must not violate the entry/exit criteria.
7777 CS->getCapturedDecl()->setNothrow();
7778 }
Kelvin Li02532872016-08-05 14:37:37 +00007779
7780 OMPLoopDirective::HelperExprs B;
7781 // In presence of clause 'collapse' with number of loops, it will
7782 // define the nested loops number.
7783 unsigned NestedLoopCount =
Alexey Bataeve3727102018-04-18 15:57:46 +00007784 checkOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007785 nullptr /*ordered not a clause on distribute*/, CS, *this,
7786 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00007787 if (NestedLoopCount == 0)
7788 return StmtError();
7789
7790 assert((CurContext->isDependentContext() || B.builtAll()) &&
7791 "omp teams distribute loop exprs were not built");
7792
Reid Kleckner87a31802018-03-12 21:43:02 +00007793 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007794
7795 DSAStack->setParentTeamsRegionLoc(StartLoc);
7796
David Majnemer9d168222016-08-05 17:44:54 +00007797 return OMPTeamsDistributeDirective::Create(
7798 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00007799}
7800
Kelvin Li4e325f72016-10-25 12:50:55 +00007801StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7802 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007803 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li4e325f72016-10-25 12:50:55 +00007804 if (!AStmt)
7805 return StmtError();
7806
Alexey Bataeve3727102018-04-18 15:57:46 +00007807 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li4e325f72016-10-25 12:50:55 +00007808 // 1.2.2 OpenMP Language Terminology
7809 // Structured block - An executable statement with a single entry at the
7810 // top and a single exit at the bottom.
7811 // The point of exit cannot be a branch out of the structured block.
7812 // longjmp() and throw() must not violate the entry/exit criteria.
7813 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00007814 for (int ThisCaptureLevel =
7815 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7816 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7817 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7818 // 1.2.2 OpenMP Language Terminology
7819 // Structured block - An executable statement with a single entry at the
7820 // top and a single exit at the bottom.
7821 // The point of exit cannot be a branch out of the structured block.
7822 // longjmp() and throw() must not violate the entry/exit criteria.
7823 CS->getCapturedDecl()->setNothrow();
7824 }
7825
Kelvin Li4e325f72016-10-25 12:50:55 +00007826
7827 OMPLoopDirective::HelperExprs B;
7828 // In presence of clause 'collapse' with number of loops, it will
7829 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007830 unsigned NestedLoopCount = checkOpenMPLoop(
Samuel Antao4c8035b2016-12-12 18:00:20 +00007831 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00007832 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00007833 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00007834
7835 if (NestedLoopCount == 0)
7836 return StmtError();
7837
7838 assert((CurContext->isDependentContext() || B.builtAll()) &&
7839 "omp teams distribute simd loop exprs were not built");
7840
7841 if (!CurContext->isDependentContext()) {
7842 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007843 for (OMPClause *C : Clauses) {
Kelvin Li4e325f72016-10-25 12:50:55 +00007844 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7845 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7846 B.NumIterations, *this, CurScope,
7847 DSAStack))
7848 return StmtError();
7849 }
7850 }
7851
7852 if (checkSimdlenSafelenSpecified(*this, Clauses))
7853 return StmtError();
7854
Reid Kleckner87a31802018-03-12 21:43:02 +00007855 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007856
7857 DSAStack->setParentTeamsRegionLoc(StartLoc);
7858
Kelvin Li4e325f72016-10-25 12:50:55 +00007859 return OMPTeamsDistributeSimdDirective::Create(
7860 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7861}
7862
Kelvin Li579e41c2016-11-30 23:51:03 +00007863StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7864 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007865 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li579e41c2016-11-30 23:51:03 +00007866 if (!AStmt)
7867 return StmtError();
7868
Alexey Bataeve3727102018-04-18 15:57:46 +00007869 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li579e41c2016-11-30 23:51:03 +00007870 // 1.2.2 OpenMP Language Terminology
7871 // Structured block - An executable statement with a single entry at the
7872 // top and a single exit at the bottom.
7873 // The point of exit cannot be a branch out of the structured block.
7874 // longjmp() and throw() must not violate the entry/exit criteria.
7875 CS->getCapturedDecl()->setNothrow();
7876
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007877 for (int ThisCaptureLevel =
7878 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7879 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7880 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7881 // 1.2.2 OpenMP Language Terminology
7882 // Structured block - An executable statement with a single entry at the
7883 // top and a single exit at the bottom.
7884 // The point of exit cannot be a branch out of the structured block.
7885 // longjmp() and throw() must not violate the entry/exit criteria.
7886 CS->getCapturedDecl()->setNothrow();
7887 }
7888
Kelvin Li579e41c2016-11-30 23:51:03 +00007889 OMPLoopDirective::HelperExprs B;
7890 // In presence of clause 'collapse' with number of loops, it will
7891 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007892 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li579e41c2016-11-30 23:51:03 +00007893 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007894 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00007895 VarsWithImplicitDSA, B);
7896
7897 if (NestedLoopCount == 0)
7898 return StmtError();
7899
7900 assert((CurContext->isDependentContext() || B.builtAll()) &&
7901 "omp for loop exprs were not built");
7902
7903 if (!CurContext->isDependentContext()) {
7904 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00007905 for (OMPClause *C : Clauses) {
Kelvin Li579e41c2016-11-30 23:51:03 +00007906 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7907 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7908 B.NumIterations, *this, CurScope,
7909 DSAStack))
7910 return StmtError();
7911 }
7912 }
7913
7914 if (checkSimdlenSafelenSpecified(*this, Clauses))
7915 return StmtError();
7916
Reid Kleckner87a31802018-03-12 21:43:02 +00007917 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007918
7919 DSAStack->setParentTeamsRegionLoc(StartLoc);
7920
Kelvin Li579e41c2016-11-30 23:51:03 +00007921 return OMPTeamsDistributeParallelForSimdDirective::Create(
7922 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7923}
7924
Kelvin Li7ade93f2016-12-09 03:24:30 +00007925StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7926 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00007927 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li7ade93f2016-12-09 03:24:30 +00007928 if (!AStmt)
7929 return StmtError();
7930
Alexey Bataeve3727102018-04-18 15:57:46 +00007931 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li7ade93f2016-12-09 03:24:30 +00007932 // 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
Carlo Bertolli62fae152017-11-20 20:46:39 +00007939 for (int ThisCaptureLevel =
7940 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7941 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7942 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7943 // 1.2.2 OpenMP Language Terminology
7944 // Structured block - An executable statement with a single entry at the
7945 // top and a single exit at the bottom.
7946 // The point of exit cannot be a branch out of the structured block.
7947 // longjmp() and throw() must not violate the entry/exit criteria.
7948 CS->getCapturedDecl()->setNothrow();
7949 }
7950
Kelvin Li7ade93f2016-12-09 03:24:30 +00007951 OMPLoopDirective::HelperExprs B;
7952 // In presence of clause 'collapse' with number of loops, it will
7953 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00007954 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Li7ade93f2016-12-09 03:24:30 +00007955 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00007956 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00007957 VarsWithImplicitDSA, B);
7958
7959 if (NestedLoopCount == 0)
7960 return StmtError();
7961
7962 assert((CurContext->isDependentContext() || B.builtAll()) &&
7963 "omp for loop exprs were not built");
7964
Reid Kleckner87a31802018-03-12 21:43:02 +00007965 setFunctionHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007966
7967 DSAStack->setParentTeamsRegionLoc(StartLoc);
7968
Kelvin Li7ade93f2016-12-09 03:24:30 +00007969 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007970 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7971 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00007972}
7973
Kelvin Libf594a52016-12-17 05:48:59 +00007974StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7975 Stmt *AStmt,
7976 SourceLocation StartLoc,
7977 SourceLocation EndLoc) {
7978 if (!AStmt)
7979 return StmtError();
7980
Alexey Bataeve3727102018-04-18 15:57:46 +00007981 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Libf594a52016-12-17 05:48:59 +00007982 // 1.2.2 OpenMP Language Terminology
7983 // Structured block - An executable statement with a single entry at the
7984 // top and a single exit at the bottom.
7985 // The point of exit cannot be a branch out of the structured block.
7986 // longjmp() and throw() must not violate the entry/exit criteria.
7987 CS->getCapturedDecl()->setNothrow();
7988
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00007989 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7990 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7991 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7992 // 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();
Kelvin Libf594a52016-12-17 05:48:59 +00008000
8001 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
8002 AStmt);
8003}
8004
Kelvin Li83c451e2016-12-25 04:52:54 +00008005StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
8006 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008007 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li83c451e2016-12-25 04:52:54 +00008008 if (!AStmt)
8009 return StmtError();
8010
Alexey Bataeve3727102018-04-18 15:57:46 +00008011 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li83c451e2016-12-25 04:52:54 +00008012 // 1.2.2 OpenMP Language Terminology
8013 // Structured block - An executable statement with a single entry at the
8014 // top and a single exit at the bottom.
8015 // The point of exit cannot be a branch out of the structured block.
8016 // longjmp() and throw() must not violate the entry/exit criteria.
8017 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008018 for (int ThisCaptureLevel =
8019 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
8020 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8021 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8022 // 1.2.2 OpenMP Language Terminology
8023 // Structured block - An executable statement with a single entry at the
8024 // top and a single exit at the bottom.
8025 // The point of exit cannot be a branch out of the structured block.
8026 // longjmp() and throw() must not violate the entry/exit criteria.
8027 CS->getCapturedDecl()->setNothrow();
8028 }
Kelvin Li83c451e2016-12-25 04:52:54 +00008029
8030 OMPLoopDirective::HelperExprs B;
8031 // In presence of clause 'collapse' with number of loops, it will
8032 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008033 unsigned NestedLoopCount = checkOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00008034 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
8035 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00008036 VarsWithImplicitDSA, B);
8037 if (NestedLoopCount == 0)
8038 return StmtError();
8039
8040 assert((CurContext->isDependentContext() || B.builtAll()) &&
8041 "omp target teams distribute loop exprs were not built");
8042
Reid Kleckner87a31802018-03-12 21:43:02 +00008043 setFunctionHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00008044 return OMPTargetTeamsDistributeDirective::Create(
8045 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8046}
8047
Kelvin Li80e8f562016-12-29 22:16:30 +00008048StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
8049 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008050 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li80e8f562016-12-29 22:16:30 +00008051 if (!AStmt)
8052 return StmtError();
8053
Alexey Bataeve3727102018-04-18 15:57:46 +00008054 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li80e8f562016-12-29 22:16:30 +00008055 // 1.2.2 OpenMP Language Terminology
8056 // Structured block - An executable statement with a single entry at the
8057 // top and a single exit at the bottom.
8058 // The point of exit cannot be a branch out of the structured block.
8059 // longjmp() and throw() must not violate the entry/exit criteria.
8060 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00008061 for (int ThisCaptureLevel =
8062 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
8063 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8064 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8065 // 1.2.2 OpenMP Language Terminology
8066 // Structured block - An executable statement with a single entry at the
8067 // top and a single exit at the bottom.
8068 // The point of exit cannot be a branch out of the structured block.
8069 // longjmp() and throw() must not violate the entry/exit criteria.
8070 CS->getCapturedDecl()->setNothrow();
8071 }
8072
Kelvin Li80e8f562016-12-29 22:16:30 +00008073 OMPLoopDirective::HelperExprs B;
8074 // In presence of clause 'collapse' with number of loops, it will
8075 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008076 unsigned NestedLoopCount = checkOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00008077 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
8078 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00008079 VarsWithImplicitDSA, B);
8080 if (NestedLoopCount == 0)
8081 return StmtError();
8082
8083 assert((CurContext->isDependentContext() || B.builtAll()) &&
8084 "omp target teams distribute parallel for loop exprs were not built");
8085
Alexey Bataev647dd842018-01-15 20:59:40 +00008086 if (!CurContext->isDependentContext()) {
8087 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008088 for (OMPClause *C : Clauses) {
Alexey Bataev647dd842018-01-15 20:59:40 +00008089 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8090 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8091 B.NumIterations, *this, CurScope,
8092 DSAStack))
8093 return StmtError();
8094 }
8095 }
8096
Reid Kleckner87a31802018-03-12 21:43:02 +00008097 setFunctionHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00008098 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00008099 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
8100 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00008101}
8102
Kelvin Li1851df52017-01-03 05:23:48 +00008103StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
8104 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008105 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Li1851df52017-01-03 05:23:48 +00008106 if (!AStmt)
8107 return StmtError();
8108
Alexey Bataeve3727102018-04-18 15:57:46 +00008109 auto *CS = cast<CapturedStmt>(AStmt);
Kelvin Li1851df52017-01-03 05:23:48 +00008110 // 1.2.2 OpenMP Language Terminology
8111 // Structured block - An executable statement with a single entry at the
8112 // top and a single exit at the bottom.
8113 // The point of exit cannot be a branch out of the structured block.
8114 // longjmp() and throw() must not violate the entry/exit criteria.
8115 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00008116 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
8117 OMPD_target_teams_distribute_parallel_for_simd);
8118 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8119 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8120 // 1.2.2 OpenMP Language Terminology
8121 // Structured block - An executable statement with a single entry at the
8122 // top and a single exit at the bottom.
8123 // The point of exit cannot be a branch out of the structured block.
8124 // longjmp() and throw() must not violate the entry/exit criteria.
8125 CS->getCapturedDecl()->setNothrow();
8126 }
Kelvin Li1851df52017-01-03 05:23:48 +00008127
8128 OMPLoopDirective::HelperExprs B;
8129 // In presence of clause 'collapse' with number of loops, it will
8130 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008131 unsigned NestedLoopCount =
8132 checkOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
Alexey Bataev647dd842018-01-15 20:59:40 +00008133 getCollapseNumberExpr(Clauses),
8134 nullptr /*ordered not a clause on distribute*/, CS, *this,
8135 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00008136 if (NestedLoopCount == 0)
8137 return StmtError();
8138
8139 assert((CurContext->isDependentContext() || B.builtAll()) &&
8140 "omp target teams distribute parallel for simd loop exprs were not "
8141 "built");
8142
8143 if (!CurContext->isDependentContext()) {
8144 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008145 for (OMPClause *C : Clauses) {
Kelvin Li1851df52017-01-03 05:23:48 +00008146 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8147 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8148 B.NumIterations, *this, CurScope,
8149 DSAStack))
8150 return StmtError();
8151 }
8152 }
8153
Alexey Bataev438388c2017-11-22 18:34:02 +00008154 if (checkSimdlenSafelenSpecified(*this, Clauses))
8155 return StmtError();
8156
Reid Kleckner87a31802018-03-12 21:43:02 +00008157 setFunctionHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00008158 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
8159 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8160}
8161
Kelvin Lida681182017-01-10 18:08:18 +00008162StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
8163 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
Alexey Bataeve3727102018-04-18 15:57:46 +00008164 SourceLocation EndLoc, VarsWithInheritedDSAType &VarsWithImplicitDSA) {
Kelvin Lida681182017-01-10 18:08:18 +00008165 if (!AStmt)
8166 return StmtError();
8167
8168 auto *CS = cast<CapturedStmt>(AStmt);
8169 // 1.2.2 OpenMP Language Terminology
8170 // Structured block - An executable statement with a single entry at the
8171 // top and a single exit at the bottom.
8172 // The point of exit cannot be a branch out of the structured block.
8173 // longjmp() and throw() must not violate the entry/exit criteria.
8174 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008175 for (int ThisCaptureLevel =
8176 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
8177 ThisCaptureLevel > 1; --ThisCaptureLevel) {
8178 CS = cast<CapturedStmt>(CS->getCapturedStmt());
8179 // 1.2.2 OpenMP Language Terminology
8180 // Structured block - An executable statement with a single entry at the
8181 // top and a single exit at the bottom.
8182 // The point of exit cannot be a branch out of the structured block.
8183 // longjmp() and throw() must not violate the entry/exit criteria.
8184 CS->getCapturedDecl()->setNothrow();
8185 }
Kelvin Lida681182017-01-10 18:08:18 +00008186
8187 OMPLoopDirective::HelperExprs B;
8188 // In presence of clause 'collapse' with number of loops, it will
8189 // define the nested loops number.
Alexey Bataeve3727102018-04-18 15:57:46 +00008190 unsigned NestedLoopCount = checkOpenMPLoop(
Kelvin Lida681182017-01-10 18:08:18 +00008191 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00008192 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00008193 VarsWithImplicitDSA, B);
8194 if (NestedLoopCount == 0)
8195 return StmtError();
8196
8197 assert((CurContext->isDependentContext() || B.builtAll()) &&
8198 "omp target teams distribute simd loop exprs were not built");
8199
Alexey Bataev438388c2017-11-22 18:34:02 +00008200 if (!CurContext->isDependentContext()) {
8201 // Finalize the clauses that need pre-built expressions for CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +00008202 for (OMPClause *C : Clauses) {
Alexey Bataev438388c2017-11-22 18:34:02 +00008203 if (auto *LC = dyn_cast<OMPLinearClause>(C))
8204 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
8205 B.NumIterations, *this, CurScope,
8206 DSAStack))
8207 return StmtError();
8208 }
8209 }
8210
8211 if (checkSimdlenSafelenSpecified(*this, Clauses))
8212 return StmtError();
8213
Reid Kleckner87a31802018-03-12 21:43:02 +00008214 setFunctionHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00008215 return OMPTargetTeamsDistributeSimdDirective::Create(
8216 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
8217}
8218
Alexey Bataeved09d242014-05-28 05:53:51 +00008219OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008220 SourceLocation StartLoc,
8221 SourceLocation LParenLoc,
8222 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008223 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008224 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00008225 case OMPC_final:
8226 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
8227 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00008228 case OMPC_num_threads:
8229 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
8230 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008231 case OMPC_safelen:
8232 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
8233 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00008234 case OMPC_simdlen:
8235 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
8236 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00008237 case OMPC_collapse:
8238 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
8239 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00008240 case OMPC_ordered:
8241 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
8242 break;
Michael Wonge710d542015-08-07 16:16:36 +00008243 case OMPC_device:
8244 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
8245 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00008246 case OMPC_num_teams:
8247 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
8248 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008249 case OMPC_thread_limit:
8250 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
8251 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00008252 case OMPC_priority:
8253 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
8254 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008255 case OMPC_grainsize:
8256 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
8257 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00008258 case OMPC_num_tasks:
8259 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
8260 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00008261 case OMPC_hint:
8262 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
8263 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008264 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008265 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008266 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008267 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008268 case OMPC_private:
8269 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008270 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008271 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008272 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008273 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008274 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008275 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008276 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008277 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008278 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00008279 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008280 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008281 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008282 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008283 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008284 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008285 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008286 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008287 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008288 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008289 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00008290 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008291 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008292 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00008293 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008294 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008295 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008296 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008297 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008298 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008299 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008300 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008301 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00008302 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00008303 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00008304 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00008305 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00008306 case OMPC_atomic_default_mem_order:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008307 llvm_unreachable("Clause is not allowed.");
8308 }
8309 return Res;
8310}
8311
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008312// An OpenMP directive such as 'target parallel' has two captured regions:
8313// for the 'target' and 'parallel' respectively. This function returns
8314// the region in which to capture expressions associated with a clause.
8315// A return value of OMPD_unknown signifies that the expression should not
8316// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008317static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
8318 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
8319 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008320 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008321 switch (CKind) {
8322 case OMPC_if:
8323 switch (DKind) {
8324 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008325 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008326 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008327 // If this clause applies to the nested 'parallel' region, capture within
8328 // the 'target' region, otherwise do not capture.
8329 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8330 CaptureRegion = OMPD_target;
8331 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00008332 case OMPD_target_teams_distribute_parallel_for:
8333 case OMPD_target_teams_distribute_parallel_for_simd:
8334 // If this clause applies to the nested 'parallel' region, capture within
8335 // the 'teams' region, otherwise do not capture.
8336 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
8337 CaptureRegion = OMPD_teams;
8338 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008339 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008340 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008341 CaptureRegion = OMPD_teams;
8342 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008343 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008344 case OMPD_target_enter_data:
8345 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008346 CaptureRegion = OMPD_task;
8347 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008348 case OMPD_cancel:
8349 case OMPD_parallel:
8350 case OMPD_parallel_sections:
8351 case OMPD_parallel_for:
8352 case OMPD_parallel_for_simd:
8353 case OMPD_target:
8354 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008355 case OMPD_target_teams:
8356 case OMPD_target_teams_distribute:
8357 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008358 case OMPD_distribute_parallel_for:
8359 case OMPD_distribute_parallel_for_simd:
8360 case OMPD_task:
8361 case OMPD_taskloop:
8362 case OMPD_taskloop_simd:
8363 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008364 // Do not capture if-clause expressions.
8365 break;
8366 case OMPD_threadprivate:
8367 case OMPD_taskyield:
8368 case OMPD_barrier:
8369 case OMPD_taskwait:
8370 case OMPD_cancellation_point:
8371 case OMPD_flush:
8372 case OMPD_declare_reduction:
8373 case OMPD_declare_simd:
8374 case OMPD_declare_target:
8375 case OMPD_end_declare_target:
8376 case OMPD_teams:
8377 case OMPD_simd:
8378 case OMPD_for:
8379 case OMPD_for_simd:
8380 case OMPD_sections:
8381 case OMPD_section:
8382 case OMPD_single:
8383 case OMPD_master:
8384 case OMPD_critical:
8385 case OMPD_taskgroup:
8386 case OMPD_distribute:
8387 case OMPD_ordered:
8388 case OMPD_atomic:
8389 case OMPD_distribute_simd:
8390 case OMPD_teams_distribute:
8391 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008392 case OMPD_requires:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008393 llvm_unreachable("Unexpected OpenMP directive with if-clause");
8394 case OMPD_unknown:
8395 llvm_unreachable("Unknown OpenMP directive");
8396 }
8397 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008398 case OMPC_num_threads:
8399 switch (DKind) {
8400 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008401 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00008402 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008403 CaptureRegion = OMPD_target;
8404 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00008405 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008406 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008407 case OMPD_target_teams_distribute_parallel_for:
8408 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008409 CaptureRegion = OMPD_teams;
8410 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008411 case OMPD_parallel:
8412 case OMPD_parallel_sections:
8413 case OMPD_parallel_for:
8414 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008415 case OMPD_distribute_parallel_for:
8416 case OMPD_distribute_parallel_for_simd:
8417 // Do not capture num_threads-clause expressions.
8418 break;
8419 case OMPD_target_data:
8420 case OMPD_target_enter_data:
8421 case OMPD_target_exit_data:
8422 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008423 case OMPD_target:
8424 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008425 case OMPD_target_teams:
8426 case OMPD_target_teams_distribute:
8427 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008428 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008429 case OMPD_task:
8430 case OMPD_taskloop:
8431 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008432 case OMPD_threadprivate:
8433 case OMPD_taskyield:
8434 case OMPD_barrier:
8435 case OMPD_taskwait:
8436 case OMPD_cancellation_point:
8437 case OMPD_flush:
8438 case OMPD_declare_reduction:
8439 case OMPD_declare_simd:
8440 case OMPD_declare_target:
8441 case OMPD_end_declare_target:
8442 case OMPD_teams:
8443 case OMPD_simd:
8444 case OMPD_for:
8445 case OMPD_for_simd:
8446 case OMPD_sections:
8447 case OMPD_section:
8448 case OMPD_single:
8449 case OMPD_master:
8450 case OMPD_critical:
8451 case OMPD_taskgroup:
8452 case OMPD_distribute:
8453 case OMPD_ordered:
8454 case OMPD_atomic:
8455 case OMPD_distribute_simd:
8456 case OMPD_teams_distribute:
8457 case OMPD_teams_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008458 case OMPD_requires:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008459 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
8460 case OMPD_unknown:
8461 llvm_unreachable("Unknown OpenMP directive");
8462 }
8463 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008464 case OMPC_num_teams:
8465 switch (DKind) {
8466 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008467 case OMPD_target_teams_distribute:
8468 case OMPD_target_teams_distribute_simd:
8469 case OMPD_target_teams_distribute_parallel_for:
8470 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008471 CaptureRegion = OMPD_target;
8472 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008473 case OMPD_teams_distribute_parallel_for:
8474 case OMPD_teams_distribute_parallel_for_simd:
8475 case OMPD_teams:
8476 case OMPD_teams_distribute:
8477 case OMPD_teams_distribute_simd:
8478 // Do not capture num_teams-clause expressions.
8479 break;
8480 case OMPD_distribute_parallel_for:
8481 case OMPD_distribute_parallel_for_simd:
8482 case OMPD_task:
8483 case OMPD_taskloop:
8484 case OMPD_taskloop_simd:
8485 case OMPD_target_data:
8486 case OMPD_target_enter_data:
8487 case OMPD_target_exit_data:
8488 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008489 case OMPD_cancel:
8490 case OMPD_parallel:
8491 case OMPD_parallel_sections:
8492 case OMPD_parallel_for:
8493 case OMPD_parallel_for_simd:
8494 case OMPD_target:
8495 case OMPD_target_simd:
8496 case OMPD_target_parallel:
8497 case OMPD_target_parallel_for:
8498 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008499 case OMPD_threadprivate:
8500 case OMPD_taskyield:
8501 case OMPD_barrier:
8502 case OMPD_taskwait:
8503 case OMPD_cancellation_point:
8504 case OMPD_flush:
8505 case OMPD_declare_reduction:
8506 case OMPD_declare_simd:
8507 case OMPD_declare_target:
8508 case OMPD_end_declare_target:
8509 case OMPD_simd:
8510 case OMPD_for:
8511 case OMPD_for_simd:
8512 case OMPD_sections:
8513 case OMPD_section:
8514 case OMPD_single:
8515 case OMPD_master:
8516 case OMPD_critical:
8517 case OMPD_taskgroup:
8518 case OMPD_distribute:
8519 case OMPD_ordered:
8520 case OMPD_atomic:
8521 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008522 case OMPD_requires:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00008523 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8524 case OMPD_unknown:
8525 llvm_unreachable("Unknown OpenMP directive");
8526 }
8527 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008528 case OMPC_thread_limit:
8529 switch (DKind) {
8530 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008531 case OMPD_target_teams_distribute:
8532 case OMPD_target_teams_distribute_simd:
8533 case OMPD_target_teams_distribute_parallel_for:
8534 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008535 CaptureRegion = OMPD_target;
8536 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008537 case OMPD_teams_distribute_parallel_for:
8538 case OMPD_teams_distribute_parallel_for_simd:
8539 case OMPD_teams:
8540 case OMPD_teams_distribute:
8541 case OMPD_teams_distribute_simd:
8542 // Do not capture thread_limit-clause expressions.
8543 break;
8544 case OMPD_distribute_parallel_for:
8545 case OMPD_distribute_parallel_for_simd:
8546 case OMPD_task:
8547 case OMPD_taskloop:
8548 case OMPD_taskloop_simd:
8549 case OMPD_target_data:
8550 case OMPD_target_enter_data:
8551 case OMPD_target_exit_data:
8552 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008553 case OMPD_cancel:
8554 case OMPD_parallel:
8555 case OMPD_parallel_sections:
8556 case OMPD_parallel_for:
8557 case OMPD_parallel_for_simd:
8558 case OMPD_target:
8559 case OMPD_target_simd:
8560 case OMPD_target_parallel:
8561 case OMPD_target_parallel_for:
8562 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008563 case OMPD_threadprivate:
8564 case OMPD_taskyield:
8565 case OMPD_barrier:
8566 case OMPD_taskwait:
8567 case OMPD_cancellation_point:
8568 case OMPD_flush:
8569 case OMPD_declare_reduction:
8570 case OMPD_declare_simd:
8571 case OMPD_declare_target:
8572 case OMPD_end_declare_target:
8573 case OMPD_simd:
8574 case OMPD_for:
8575 case OMPD_for_simd:
8576 case OMPD_sections:
8577 case OMPD_section:
8578 case OMPD_single:
8579 case OMPD_master:
8580 case OMPD_critical:
8581 case OMPD_taskgroup:
8582 case OMPD_distribute:
8583 case OMPD_ordered:
8584 case OMPD_atomic:
8585 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008586 case OMPD_requires:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008587 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8588 case OMPD_unknown:
8589 llvm_unreachable("Unknown OpenMP directive");
8590 }
8591 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008592 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008593 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008594 case OMPD_parallel_for:
8595 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008596 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008597 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008598 case OMPD_teams_distribute_parallel_for:
8599 case OMPD_teams_distribute_parallel_for_simd:
8600 case OMPD_target_parallel_for:
8601 case OMPD_target_parallel_for_simd:
8602 case OMPD_target_teams_distribute_parallel_for:
8603 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008604 CaptureRegion = OMPD_parallel;
8605 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008606 case OMPD_for:
8607 case OMPD_for_simd:
8608 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008609 break;
8610 case OMPD_task:
8611 case OMPD_taskloop:
8612 case OMPD_taskloop_simd:
8613 case OMPD_target_data:
8614 case OMPD_target_enter_data:
8615 case OMPD_target_exit_data:
8616 case OMPD_target_update:
8617 case OMPD_teams:
8618 case OMPD_teams_distribute:
8619 case OMPD_teams_distribute_simd:
8620 case OMPD_target_teams_distribute:
8621 case OMPD_target_teams_distribute_simd:
8622 case OMPD_target:
8623 case OMPD_target_simd:
8624 case OMPD_target_parallel:
8625 case OMPD_cancel:
8626 case OMPD_parallel:
8627 case OMPD_parallel_sections:
8628 case OMPD_threadprivate:
8629 case OMPD_taskyield:
8630 case OMPD_barrier:
8631 case OMPD_taskwait:
8632 case OMPD_cancellation_point:
8633 case OMPD_flush:
8634 case OMPD_declare_reduction:
8635 case OMPD_declare_simd:
8636 case OMPD_declare_target:
8637 case OMPD_end_declare_target:
8638 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008639 case OMPD_sections:
8640 case OMPD_section:
8641 case OMPD_single:
8642 case OMPD_master:
8643 case OMPD_critical:
8644 case OMPD_taskgroup:
8645 case OMPD_distribute:
8646 case OMPD_ordered:
8647 case OMPD_atomic:
8648 case OMPD_distribute_simd:
8649 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00008650 case OMPD_requires:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008651 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8652 case OMPD_unknown:
8653 llvm_unreachable("Unknown OpenMP directive");
8654 }
8655 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008656 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008657 switch (DKind) {
8658 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008659 case OMPD_teams_distribute_parallel_for_simd:
8660 case OMPD_teams_distribute:
8661 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008662 case OMPD_target_teams_distribute_parallel_for:
8663 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008664 case OMPD_target_teams_distribute:
8665 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008666 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008667 break;
8668 case OMPD_distribute_parallel_for:
8669 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008670 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008671 case OMPD_distribute_simd:
8672 // Do not capture thread_limit-clause expressions.
8673 break;
8674 case OMPD_parallel_for:
8675 case OMPD_parallel_for_simd:
8676 case OMPD_target_parallel_for_simd:
8677 case OMPD_target_parallel_for:
8678 case OMPD_task:
8679 case OMPD_taskloop:
8680 case OMPD_taskloop_simd:
8681 case OMPD_target_data:
8682 case OMPD_target_enter_data:
8683 case OMPD_target_exit_data:
8684 case OMPD_target_update:
8685 case OMPD_teams:
8686 case OMPD_target:
8687 case OMPD_target_simd:
8688 case OMPD_target_parallel:
8689 case OMPD_cancel:
8690 case OMPD_parallel:
8691 case OMPD_parallel_sections:
8692 case OMPD_threadprivate:
8693 case OMPD_taskyield:
8694 case OMPD_barrier:
8695 case OMPD_taskwait:
8696 case OMPD_cancellation_point:
8697 case OMPD_flush:
8698 case OMPD_declare_reduction:
8699 case OMPD_declare_simd:
8700 case OMPD_declare_target:
8701 case OMPD_end_declare_target:
8702 case OMPD_simd:
8703 case OMPD_for:
8704 case OMPD_for_simd:
8705 case OMPD_sections:
8706 case OMPD_section:
8707 case OMPD_single:
8708 case OMPD_master:
8709 case OMPD_critical:
8710 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008711 case OMPD_ordered:
8712 case OMPD_atomic:
8713 case OMPD_target_teams:
Kelvin Li1408f912018-09-26 04:28:39 +00008714 case OMPD_requires:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008715 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8716 case OMPD_unknown:
8717 llvm_unreachable("Unknown OpenMP directive");
8718 }
8719 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008720 case OMPC_device:
8721 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008722 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008723 case OMPD_target_enter_data:
8724 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00008725 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00008726 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00008727 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00008728 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00008729 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00008730 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00008731 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00008732 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00008733 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00008734 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008735 CaptureRegion = OMPD_task;
8736 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008737 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008738 // Do not capture device-clause expressions.
8739 break;
8740 case OMPD_teams_distribute_parallel_for:
8741 case OMPD_teams_distribute_parallel_for_simd:
8742 case OMPD_teams:
8743 case OMPD_teams_distribute:
8744 case OMPD_teams_distribute_simd:
8745 case OMPD_distribute_parallel_for:
8746 case OMPD_distribute_parallel_for_simd:
8747 case OMPD_task:
8748 case OMPD_taskloop:
8749 case OMPD_taskloop_simd:
8750 case OMPD_cancel:
8751 case OMPD_parallel:
8752 case OMPD_parallel_sections:
8753 case OMPD_parallel_for:
8754 case OMPD_parallel_for_simd:
8755 case OMPD_threadprivate:
8756 case OMPD_taskyield:
8757 case OMPD_barrier:
8758 case OMPD_taskwait:
8759 case OMPD_cancellation_point:
8760 case OMPD_flush:
8761 case OMPD_declare_reduction:
8762 case OMPD_declare_simd:
8763 case OMPD_declare_target:
8764 case OMPD_end_declare_target:
8765 case OMPD_simd:
8766 case OMPD_for:
8767 case OMPD_for_simd:
8768 case OMPD_sections:
8769 case OMPD_section:
8770 case OMPD_single:
8771 case OMPD_master:
8772 case OMPD_critical:
8773 case OMPD_taskgroup:
8774 case OMPD_distribute:
8775 case OMPD_ordered:
8776 case OMPD_atomic:
8777 case OMPD_distribute_simd:
Kelvin Li1408f912018-09-26 04:28:39 +00008778 case OMPD_requires:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008779 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8780 case OMPD_unknown:
8781 llvm_unreachable("Unknown OpenMP directive");
8782 }
8783 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008784 case OMPC_firstprivate:
8785 case OMPC_lastprivate:
8786 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008787 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008788 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008789 case OMPC_linear:
8790 case OMPC_default:
8791 case OMPC_proc_bind:
8792 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008793 case OMPC_safelen:
8794 case OMPC_simdlen:
8795 case OMPC_collapse:
8796 case OMPC_private:
8797 case OMPC_shared:
8798 case OMPC_aligned:
8799 case OMPC_copyin:
8800 case OMPC_copyprivate:
8801 case OMPC_ordered:
8802 case OMPC_nowait:
8803 case OMPC_untied:
8804 case OMPC_mergeable:
8805 case OMPC_threadprivate:
8806 case OMPC_flush:
8807 case OMPC_read:
8808 case OMPC_write:
8809 case OMPC_update:
8810 case OMPC_capture:
8811 case OMPC_seq_cst:
8812 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008813 case OMPC_threads:
8814 case OMPC_simd:
8815 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008816 case OMPC_priority:
8817 case OMPC_grainsize:
8818 case OMPC_nogroup:
8819 case OMPC_num_tasks:
8820 case OMPC_hint:
8821 case OMPC_defaultmap:
8822 case OMPC_unknown:
8823 case OMPC_uniform:
8824 case OMPC_to:
8825 case OMPC_from:
8826 case OMPC_use_device_ptr:
8827 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00008828 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00008829 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00008830 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00008831 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00008832 case OMPC_atomic_default_mem_order:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008833 llvm_unreachable("Unexpected OpenMP clause.");
8834 }
8835 return CaptureRegion;
8836}
8837
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008838OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8839 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008840 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008841 SourceLocation NameModifierLoc,
8842 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008843 SourceLocation EndLoc) {
8844 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008845 Stmt *HelperValStmt = nullptr;
8846 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008847 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8848 !Condition->isInstantiationDependent() &&
8849 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008850 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008851 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008852 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008853
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008854 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008855
8856 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8857 CaptureRegion =
8858 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00008859 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008860 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00008861 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008862 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8863 HelperValStmt = buildPreInits(Context, Captures);
8864 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008865 }
8866
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008867 return new (Context)
8868 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8869 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008870}
8871
Alexey Bataev3778b602014-07-17 07:32:53 +00008872OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8873 SourceLocation StartLoc,
8874 SourceLocation LParenLoc,
8875 SourceLocation EndLoc) {
8876 Expr *ValExpr = Condition;
8877 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8878 !Condition->isInstantiationDependent() &&
8879 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008880 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00008881 if (Val.isInvalid())
8882 return nullptr;
8883
Richard Smith03a4aa32016-06-23 19:02:52 +00008884 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00008885 }
8886
8887 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8888}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008889ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8890 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00008891 if (!Op)
8892 return ExprError();
8893
8894 class IntConvertDiagnoser : public ICEConvertDiagnoser {
8895 public:
8896 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00008897 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00008898 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8899 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008900 return S.Diag(Loc, diag::err_omp_not_integral) << T;
8901 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008902 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8903 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008904 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8905 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008906 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8907 QualType T,
8908 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008909 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8910 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008911 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8912 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008913 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008914 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008915 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008916 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8917 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008918 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8919 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008920 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8921 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008922 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008923 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008924 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008925 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8926 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008927 llvm_unreachable("conversion functions are permitted");
8928 }
8929 } ConvertDiagnoser;
8930 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8931}
8932
Alexey Bataeve3727102018-04-18 15:57:46 +00008933static bool isNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00008934 OpenMPClauseKind CKind,
8935 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008936 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8937 !ValExpr->isInstantiationDependent()) {
8938 SourceLocation Loc = ValExpr->getExprLoc();
8939 ExprResult Value =
8940 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8941 if (Value.isInvalid())
8942 return false;
8943
8944 ValExpr = Value.get();
8945 // The expression must evaluate to a non-negative integer value.
8946 llvm::APSInt Result;
8947 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00008948 Result.isSigned() &&
8949 !((!StrictlyPositive && Result.isNonNegative()) ||
8950 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008951 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008952 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8953 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008954 return false;
8955 }
8956 }
8957 return true;
8958}
8959
Alexey Bataev568a8332014-03-06 06:15:19 +00008960OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8961 SourceLocation StartLoc,
8962 SourceLocation LParenLoc,
8963 SourceLocation EndLoc) {
8964 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008965 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008966
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008967 // OpenMP [2.5, Restrictions]
8968 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +00008969 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
Alexey Bataeva0569352015-12-01 10:17:31 +00008970 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008971 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008972
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008973 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00008974 OpenMPDirectiveKind CaptureRegion =
8975 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8976 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008977 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00008978 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008979 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8980 HelperValStmt = buildPreInits(Context, Captures);
8981 }
8982
8983 return new (Context) OMPNumThreadsClause(
8984 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00008985}
8986
Alexey Bataev62c87d22014-03-21 04:51:18 +00008987ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008988 OpenMPClauseKind CKind,
8989 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008990 if (!E)
8991 return ExprError();
8992 if (E->isValueDependent() || E->isTypeDependent() ||
8993 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008994 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008995 llvm::APSInt Result;
8996 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8997 if (ICE.isInvalid())
8998 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008999 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
9000 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00009001 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009002 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
9003 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00009004 return ExprError();
9005 }
Alexander Musman09184fe2014-09-30 05:29:28 +00009006 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
9007 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
9008 << E->getSourceRange();
9009 return ExprError();
9010 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009011 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
9012 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00009013 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00009014 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00009015 return ICE;
9016}
9017
9018OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
9019 SourceLocation LParenLoc,
9020 SourceLocation EndLoc) {
9021 // OpenMP [2.8.1, simd construct, Description]
9022 // The parameter of the safelen clause must be a constant
9023 // positive integer expression.
9024 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
9025 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009026 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00009027 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00009028 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00009029}
9030
Alexey Bataev66b15b52015-08-21 11:14:16 +00009031OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
9032 SourceLocation LParenLoc,
9033 SourceLocation EndLoc) {
9034 // OpenMP [2.8.1, simd construct, Description]
9035 // The parameter of the simdlen clause must be a constant
9036 // positive integer expression.
9037 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
9038 if (Simdlen.isInvalid())
9039 return nullptr;
9040 return new (Context)
9041 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
9042}
9043
Alexander Musman64d33f12014-06-04 07:53:32 +00009044OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
9045 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00009046 SourceLocation LParenLoc,
9047 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00009048 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009049 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00009050 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00009051 // The parameter of the collapse clause must be a constant
9052 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00009053 ExprResult NumForLoopsResult =
9054 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
9055 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00009056 return nullptr;
9057 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00009058 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00009059}
9060
Alexey Bataev10e775f2015-07-30 11:36:16 +00009061OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
9062 SourceLocation EndLoc,
9063 SourceLocation LParenLoc,
9064 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00009065 // OpenMP [2.7.1, loop construct, Description]
9066 // OpenMP [2.8.1, simd construct, Description]
9067 // OpenMP [2.9.6, distribute construct, Description]
9068 // The parameter of the ordered clause must be a constant
9069 // positive integer expression if any.
9070 if (NumForLoops && LParenLoc.isValid()) {
9071 ExprResult NumForLoopsResult =
9072 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
9073 if (NumForLoopsResult.isInvalid())
9074 return nullptr;
9075 NumForLoops = NumForLoopsResult.get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009076 } else {
Alexey Bataev346265e2015-09-25 10:37:12 +00009077 NumForLoops = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +00009078 }
Alexey Bataevf138fda2018-08-13 19:04:24 +00009079 auto *Clause = OMPOrderedClause::Create(
9080 Context, NumForLoops, NumForLoops ? DSAStack->getAssociatedLoops() : 0,
9081 StartLoc, LParenLoc, EndLoc);
9082 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops, Clause);
9083 return Clause;
Alexey Bataev10e775f2015-07-30 11:36:16 +00009084}
9085
Alexey Bataeved09d242014-05-28 05:53:51 +00009086OMPClause *Sema::ActOnOpenMPSimpleClause(
9087 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
9088 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009089 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009090 switch (Kind) {
9091 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009092 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00009093 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
9094 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009095 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009096 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00009097 Res = ActOnOpenMPProcBindClause(
9098 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
9099 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009100 break;
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009101 case OMPC_atomic_default_mem_order:
9102 Res = ActOnOpenMPAtomicDefaultMemOrderClause(
9103 static_cast<OpenMPAtomicDefaultMemOrderClauseKind>(Argument),
9104 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
9105 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009106 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009107 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009108 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009109 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009110 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009111 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009112 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009113 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009114 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00009115 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00009116 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00009117 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009118 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009119 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00009120 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009121 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009122 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009123 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009124 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009125 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009126 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009127 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009128 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009129 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009130 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009131 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009132 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009133 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009134 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009135 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009136 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009137 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009138 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009139 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009140 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009141 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009142 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009143 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009144 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009145 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009146 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009147 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009148 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009149 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009150 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009151 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009152 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009153 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009154 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009155 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009156 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009157 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009158 case OMPC_dynamic_allocators:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009159 llvm_unreachable("Clause is not allowed.");
9160 }
9161 return Res;
9162}
9163
Alexey Bataev6402bca2015-12-28 07:25:51 +00009164static std::string
9165getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
9166 ArrayRef<unsigned> Exclude = llvm::None) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009167 SmallString<256> Buffer;
9168 llvm::raw_svector_ostream Out(Buffer);
Alexey Bataev6402bca2015-12-28 07:25:51 +00009169 unsigned Bound = Last >= 2 ? Last - 2 : 0;
9170 unsigned Skipped = Exclude.size();
9171 auto S = Exclude.begin(), E = Exclude.end();
Alexey Bataeve3727102018-04-18 15:57:46 +00009172 for (unsigned I = First; I < Last; ++I) {
9173 if (std::find(S, E, I) != E) {
Alexey Bataev6402bca2015-12-28 07:25:51 +00009174 --Skipped;
9175 continue;
9176 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009177 Out << "'" << getOpenMPSimpleClauseTypeName(K, I) << "'";
9178 if (I == Bound - Skipped)
9179 Out << " or ";
9180 else if (I != Bound + 1 - Skipped)
9181 Out << ", ";
Alexey Bataev6402bca2015-12-28 07:25:51 +00009182 }
Alexey Bataeve3727102018-04-18 15:57:46 +00009183 return Out.str();
Alexey Bataev6402bca2015-12-28 07:25:51 +00009184}
9185
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009186OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
9187 SourceLocation KindKwLoc,
9188 SourceLocation StartLoc,
9189 SourceLocation LParenLoc,
9190 SourceLocation EndLoc) {
9191 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00009192 static_assert(OMPC_DEFAULT_unknown > 0,
9193 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009194 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009195 << getListOfPossibleValues(OMPC_default, /*First=*/0,
9196 /*Last=*/OMPC_DEFAULT_unknown)
9197 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009198 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009199 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00009200 switch (Kind) {
9201 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009202 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009203 break;
9204 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009205 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009206 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009207 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009208 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00009209 break;
9210 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009211 return new (Context)
9212 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009213}
9214
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009215OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
9216 SourceLocation KindKwLoc,
9217 SourceLocation StartLoc,
9218 SourceLocation LParenLoc,
9219 SourceLocation EndLoc) {
9220 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009221 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00009222 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
9223 /*Last=*/OMPC_PROC_BIND_unknown)
9224 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009225 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009226 }
Alexey Bataeved09d242014-05-28 05:53:51 +00009227 return new (Context)
9228 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009229}
9230
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009231OMPClause *Sema::ActOnOpenMPAtomicDefaultMemOrderClause(
9232 OpenMPAtomicDefaultMemOrderClauseKind Kind, SourceLocation KindKwLoc,
9233 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
9234 if (Kind == OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown) {
9235 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
9236 << getListOfPossibleValues(
9237 OMPC_atomic_default_mem_order, /*First=*/0,
9238 /*Last=*/OMPC_ATOMIC_DEFAULT_MEM_ORDER_unknown)
9239 << getOpenMPClauseName(OMPC_atomic_default_mem_order);
9240 return nullptr;
9241 }
9242 return new (Context) OMPAtomicDefaultMemOrderClause(Kind, KindKwLoc, StartLoc,
9243 LParenLoc, EndLoc);
9244}
9245
Alexey Bataev56dafe82014-06-20 07:16:17 +00009246OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009247 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009248 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009249 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009250 SourceLocation EndLoc) {
9251 OMPClause *Res = nullptr;
9252 switch (Kind) {
9253 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009254 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
9255 assert(Argument.size() == NumberOfElements &&
9256 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009257 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009258 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
9259 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
9260 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
9261 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
9262 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009263 break;
9264 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00009265 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
9266 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
9267 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
9268 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00009269 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00009270 case OMPC_dist_schedule:
9271 Res = ActOnOpenMPDistScheduleClause(
9272 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
9273 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
9274 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009275 case OMPC_defaultmap:
9276 enum { Modifier, DefaultmapKind };
9277 Res = ActOnOpenMPDefaultmapClause(
9278 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
9279 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00009280 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
9281 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009282 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00009283 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009284 case OMPC_num_threads:
9285 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009286 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009287 case OMPC_collapse:
9288 case OMPC_default:
9289 case OMPC_proc_bind:
9290 case OMPC_private:
9291 case OMPC_firstprivate:
9292 case OMPC_lastprivate:
9293 case OMPC_shared:
9294 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009295 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009296 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009297 case OMPC_linear:
9298 case OMPC_aligned:
9299 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009300 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009301 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009302 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009303 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009304 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009305 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009306 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009307 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009308 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009309 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009310 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009311 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009312 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009313 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009314 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009315 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009316 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009317 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009318 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009319 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009320 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009321 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009322 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009323 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009324 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009325 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009326 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009327 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009328 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009329 case OMPC_is_device_ptr:
Kelvin Li1408f912018-09-26 04:28:39 +00009330 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009331 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009332 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009333 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009334 case OMPC_atomic_default_mem_order:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009335 llvm_unreachable("Clause is not allowed.");
9336 }
9337 return Res;
9338}
9339
Alexey Bataev6402bca2015-12-28 07:25:51 +00009340static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
9341 OpenMPScheduleClauseModifier M2,
9342 SourceLocation M1Loc, SourceLocation M2Loc) {
9343 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
9344 SmallVector<unsigned, 2> Excluded;
9345 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
9346 Excluded.push_back(M2);
9347 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
9348 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
9349 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
9350 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
9351 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
9352 << getListOfPossibleValues(OMPC_schedule,
9353 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
9354 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9355 Excluded)
9356 << getOpenMPClauseName(OMPC_schedule);
9357 return true;
9358 }
9359 return false;
9360}
9361
Alexey Bataev56dafe82014-06-20 07:16:17 +00009362OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00009363 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00009364 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00009365 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
9366 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
9367 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
9368 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
9369 return nullptr;
9370 // OpenMP, 2.7.1, Loop Construct, Restrictions
9371 // Either the monotonic modifier or the nonmonotonic modifier can be specified
9372 // but not both.
9373 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
9374 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
9375 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
9376 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
9377 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
9378 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
9379 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
9380 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
9381 return nullptr;
9382 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009383 if (Kind == OMPC_SCHEDULE_unknown) {
9384 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00009385 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
9386 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
9387 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9388 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
9389 Exclude);
9390 } else {
9391 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
9392 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009393 }
9394 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
9395 << Values << getOpenMPClauseName(OMPC_schedule);
9396 return nullptr;
9397 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00009398 // OpenMP, 2.7.1, Loop Construct, Restrictions
9399 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
9400 // schedule(guided).
9401 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
9402 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
9403 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
9404 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
9405 diag::err_omp_schedule_nonmonotonic_static);
9406 return nullptr;
9407 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00009408 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00009409 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00009410 if (ChunkSize) {
9411 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
9412 !ChunkSize->isInstantiationDependent() &&
9413 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +00009414 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Alexey Bataev56dafe82014-06-20 07:16:17 +00009415 ExprResult Val =
9416 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
9417 if (Val.isInvalid())
9418 return nullptr;
9419
9420 ValExpr = Val.get();
9421
9422 // OpenMP [2.7.1, Restrictions]
9423 // chunk_size must be a loop invariant integer expression with a positive
9424 // value.
9425 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00009426 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
9427 if (Result.isSigned() && !Result.isStrictlyPositive()) {
9428 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00009429 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00009430 return nullptr;
9431 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00009432 } else if (getOpenMPCaptureRegionForClause(
9433 DSAStack->getCurrentDirective(), OMPC_schedule) !=
9434 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00009435 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00009436 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +00009437 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +00009438 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
9439 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009440 }
9441 }
9442 }
9443
Alexey Bataev6402bca2015-12-28 07:25:51 +00009444 return new (Context)
9445 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00009446 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00009447}
9448
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009449OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
9450 SourceLocation StartLoc,
9451 SourceLocation EndLoc) {
9452 OMPClause *Res = nullptr;
9453 switch (Kind) {
9454 case OMPC_ordered:
9455 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
9456 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00009457 case OMPC_nowait:
9458 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
9459 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009460 case OMPC_untied:
9461 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
9462 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009463 case OMPC_mergeable:
9464 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
9465 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009466 case OMPC_read:
9467 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
9468 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00009469 case OMPC_write:
9470 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
9471 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00009472 case OMPC_update:
9473 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
9474 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00009475 case OMPC_capture:
9476 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
9477 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009478 case OMPC_seq_cst:
9479 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
9480 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00009481 case OMPC_threads:
9482 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
9483 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009484 case OMPC_simd:
9485 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
9486 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00009487 case OMPC_nogroup:
9488 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
9489 break;
Kelvin Li1408f912018-09-26 04:28:39 +00009490 case OMPC_unified_address:
9491 Res = ActOnOpenMPUnifiedAddressClause(StartLoc, EndLoc);
9492 break;
Patrick Lyster4a370b92018-10-01 13:47:43 +00009493 case OMPC_unified_shared_memory:
9494 Res = ActOnOpenMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9495 break;
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009496 case OMPC_reverse_offload:
9497 Res = ActOnOpenMPReverseOffloadClause(StartLoc, EndLoc);
9498 break;
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009499 case OMPC_dynamic_allocators:
9500 Res = ActOnOpenMPDynamicAllocatorsClause(StartLoc, EndLoc);
9501 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009502 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009503 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009504 case OMPC_num_threads:
9505 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009506 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009507 case OMPC_collapse:
9508 case OMPC_schedule:
9509 case OMPC_private:
9510 case OMPC_firstprivate:
9511 case OMPC_lastprivate:
9512 case OMPC_shared:
9513 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00009514 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00009515 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009516 case OMPC_linear:
9517 case OMPC_aligned:
9518 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00009519 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009520 case OMPC_default:
9521 case OMPC_proc_bind:
9522 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00009523 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009524 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00009525 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00009526 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009527 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009528 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009529 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009530 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00009531 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009532 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009533 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009534 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009535 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009536 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00009537 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00009538 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00009539 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00009540 case OMPC_is_device_ptr:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009541 case OMPC_atomic_default_mem_order:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009542 llvm_unreachable("Clause is not allowed.");
9543 }
9544 return Res;
9545}
9546
Alexey Bataev236070f2014-06-20 11:19:47 +00009547OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
9548 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00009549 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00009550 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
9551}
9552
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009553OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
9554 SourceLocation EndLoc) {
9555 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
9556}
9557
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009558OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
9559 SourceLocation EndLoc) {
9560 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
9561}
9562
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009563OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
9564 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009565 return new (Context) OMPReadClause(StartLoc, EndLoc);
9566}
9567
Alexey Bataevdea47612014-07-23 07:46:59 +00009568OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
9569 SourceLocation EndLoc) {
9570 return new (Context) OMPWriteClause(StartLoc, EndLoc);
9571}
9572
Alexey Bataev67a4f222014-07-23 10:25:33 +00009573OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9574 SourceLocation EndLoc) {
9575 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9576}
9577
Alexey Bataev459dec02014-07-24 06:46:57 +00009578OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9579 SourceLocation EndLoc) {
9580 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
9581}
9582
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009583OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9584 SourceLocation EndLoc) {
9585 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
9586}
9587
Alexey Bataev346265e2015-09-25 10:37:12 +00009588OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9589 SourceLocation EndLoc) {
9590 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
9591}
9592
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009593OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9594 SourceLocation EndLoc) {
9595 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
9596}
9597
Alexey Bataevb825de12015-12-07 10:51:44 +00009598OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9599 SourceLocation EndLoc) {
9600 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
9601}
9602
Kelvin Li1408f912018-09-26 04:28:39 +00009603OMPClause *Sema::ActOnOpenMPUnifiedAddressClause(SourceLocation StartLoc,
9604 SourceLocation EndLoc) {
9605 return new (Context) OMPUnifiedAddressClause(StartLoc, EndLoc);
9606}
9607
Patrick Lyster4a370b92018-10-01 13:47:43 +00009608OMPClause *Sema::ActOnOpenMPUnifiedSharedMemoryClause(SourceLocation StartLoc,
9609 SourceLocation EndLoc) {
9610 return new (Context) OMPUnifiedSharedMemoryClause(StartLoc, EndLoc);
9611}
9612
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009613OMPClause *Sema::ActOnOpenMPReverseOffloadClause(SourceLocation StartLoc,
9614 SourceLocation EndLoc) {
9615 return new (Context) OMPReverseOffloadClause(StartLoc, EndLoc);
9616}
9617
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009618OMPClause *Sema::ActOnOpenMPDynamicAllocatorsClause(SourceLocation StartLoc,
9619 SourceLocation EndLoc) {
9620 return new (Context) OMPDynamicAllocatorsClause(StartLoc, EndLoc);
9621}
9622
Alexey Bataevc5e02582014-06-16 07:08:35 +00009623OMPClause *Sema::ActOnOpenMPVarListClause(
9624 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
9625 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
9626 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009627 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Kelvin Lief579432018-12-18 22:18:41 +00009628 OpenMPLinearClauseKind LinKind,
9629 ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
9630 ArrayRef<SourceLocation> MapTypeModifiersLoc,
Samuel Antao23abd722016-01-19 20:40:49 +00009631 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9632 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009633 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009634 switch (Kind) {
9635 case OMPC_private:
9636 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9637 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009638 case OMPC_firstprivate:
9639 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9640 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009641 case OMPC_lastprivate:
9642 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9643 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009644 case OMPC_shared:
9645 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
9646 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009647 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00009648 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9649 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009650 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00009651 case OMPC_task_reduction:
9652 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9653 EndLoc, ReductionIdScopeSpec,
9654 ReductionId);
9655 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00009656 case OMPC_in_reduction:
9657 Res =
9658 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9659 EndLoc, ReductionIdScopeSpec, ReductionId);
9660 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00009661 case OMPC_linear:
9662 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009663 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00009664 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009665 case OMPC_aligned:
9666 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9667 ColonLoc, EndLoc);
9668 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009669 case OMPC_copyin:
9670 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9671 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009672 case OMPC_copyprivate:
9673 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9674 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00009675 case OMPC_flush:
9676 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9677 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009678 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00009679 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009680 StartLoc, LParenLoc, EndLoc);
9681 break;
9682 case OMPC_map:
Kelvin Lief579432018-12-18 22:18:41 +00009683 Res = ActOnOpenMPMapClause(MapTypeModifiers, MapTypeModifiersLoc, MapType,
9684 IsMapTypeImplicit, DepLinMapLoc, ColonLoc,
9685 VarList, StartLoc, LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009686 break;
Samuel Antao661c0902016-05-26 17:39:58 +00009687 case OMPC_to:
9688 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
9689 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00009690 case OMPC_from:
9691 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
9692 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00009693 case OMPC_use_device_ptr:
9694 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9695 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00009696 case OMPC_is_device_ptr:
9697 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9698 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009699 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009700 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009701 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009702 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009703 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009704 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009705 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009706 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009707 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009708 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009709 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009710 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009711 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009712 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009713 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009714 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009715 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009716 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009717 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00009718 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009719 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009720 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009721 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009722 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009723 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009724 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009725 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009726 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009727 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009728 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009729 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009730 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009731 case OMPC_uniform:
Kelvin Li1408f912018-09-26 04:28:39 +00009732 case OMPC_unified_address:
Patrick Lyster4a370b92018-10-01 13:47:43 +00009733 case OMPC_unified_shared_memory:
Patrick Lyster6bdf63b2018-10-03 20:07:58 +00009734 case OMPC_reverse_offload:
Patrick Lyster3fe9e392018-10-11 14:41:10 +00009735 case OMPC_dynamic_allocators:
Patrick Lyster7a2a27c2018-11-02 12:18:11 +00009736 case OMPC_atomic_default_mem_order:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009737 llvm_unreachable("Clause is not allowed.");
9738 }
9739 return Res;
9740}
9741
Alexey Bataev90c228f2016-02-08 09:29:13 +00009742ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00009743 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00009744 ExprResult Res = BuildDeclRefExpr(
9745 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9746 if (!Res.isUsable())
9747 return ExprError();
9748 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9749 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9750 if (!Res.isUsable())
9751 return ExprError();
9752 }
9753 if (VK != VK_LValue && Res.get()->isGLValue()) {
9754 Res = DefaultLvalueConversion(Res.get());
9755 if (!Res.isUsable())
9756 return ExprError();
9757 }
9758 return Res;
9759}
9760
Alexey Bataev60da77e2016-02-29 05:54:20 +00009761static std::pair<ValueDecl *, bool>
9762getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9763 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009764 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9765 RefExpr->containsUnexpandedParameterPack())
9766 return std::make_pair(nullptr, true);
9767
Alexey Bataevd985eda2016-02-10 11:29:16 +00009768 // OpenMP [3.1, C/C++]
9769 // A list item is a variable name.
9770 // OpenMP [2.9.3.3, Restrictions, p.1]
9771 // A variable that is part of another variable (as an array or
9772 // structure element) cannot appear in a private clause.
9773 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009774 enum {
9775 NoArrayExpr = -1,
9776 ArraySubscript = 0,
9777 OMPArraySection = 1
9778 } IsArrayExpr = NoArrayExpr;
9779 if (AllowArraySection) {
9780 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009781 Expr *Base = ASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009782 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9783 Base = TempASE->getBase()->IgnoreParenImpCasts();
9784 RefExpr = Base;
9785 IsArrayExpr = ArraySubscript;
9786 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009787 Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009788 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9789 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9790 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9791 Base = TempASE->getBase()->IgnoreParenImpCasts();
9792 RefExpr = Base;
9793 IsArrayExpr = OMPArraySection;
9794 }
9795 }
9796 ELoc = RefExpr->getExprLoc();
9797 ERange = RefExpr->getSourceRange();
9798 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009799 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9800 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9801 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9802 (S.getCurrentThisType().isNull() || !ME ||
9803 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9804 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataeve3727102018-04-18 15:57:46 +00009805 if (IsArrayExpr != NoArrayExpr) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009806 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9807 << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +00009808 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009809 S.Diag(ELoc,
9810 AllowArraySection
9811 ? diag::err_omp_expected_var_name_member_expr_or_array_item
9812 : diag::err_omp_expected_var_name_member_expr)
9813 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9814 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009815 return std::make_pair(nullptr, false);
9816 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009817 return std::make_pair(
9818 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009819}
9820
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009821OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9822 SourceLocation StartLoc,
9823 SourceLocation LParenLoc,
9824 SourceLocation EndLoc) {
9825 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00009826 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeve3727102018-04-18 15:57:46 +00009827 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009828 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009829 SourceLocation ELoc;
9830 SourceRange ERange;
9831 Expr *SimpleRefExpr = RefExpr;
9832 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009833 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009834 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009835 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009836 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009837 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009838 ValueDecl *D = Res.first;
9839 if (!D)
9840 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009841
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009842 QualType Type = D->getType();
9843 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009844
9845 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9846 // A variable that appears in a private clause must not have an incomplete
9847 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009848 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009849 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009850 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009851
Joel E. Dennye6234d1422019-01-04 22:11:31 +00009852 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
9853 // A variable that is privatized must not have a const-qualified type
9854 // unless it is of class type with a mutable member. This restriction does
9855 // not apply to the firstprivate clause.
9856 //
9857 // OpenMP 3.1 [2.9.3.3, private clause, Restrictions]
9858 // A variable that appears in a private clause must not have a
9859 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +00009860 if (rejectConstNotMutableType(*this, D, Type, OMPC_private, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +00009861 continue;
9862
Alexey Bataev758e55e2013-09-06 18:03:48 +00009863 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9864 // in a Construct]
9865 // Variables with the predetermined data-sharing attributes may not be
9866 // listed in data-sharing attributes clauses, except for the cases
9867 // listed below. For these exceptions only, listing a predetermined
9868 // variable in a data-sharing attribute clause is allowed and overrides
9869 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +00009870 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009871 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009872 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9873 << getOpenMPClauseName(OMPC_private);
Alexey Bataeve3727102018-04-18 15:57:46 +00009874 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009875 continue;
9876 }
9877
Alexey Bataeve3727102018-04-18 15:57:46 +00009878 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009879 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009880 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00009881 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009882 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9883 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00009884 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009885 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009886 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009887 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009888 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009889 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009890 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009891 continue;
9892 }
9893
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009894 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9895 // A list item cannot appear in both a map clause and a data-sharing
9896 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +00009897 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +00009898 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009899 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009900 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009901 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9902 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9903 ConflictKind = WhereFoundClauseKind;
9904 return true;
9905 })) {
9906 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009907 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00009908 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00009909 << getOpenMPDirectiveName(CurrDir);
Alexey Bataeve3727102018-04-18 15:57:46 +00009910 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009911 continue;
9912 }
9913 }
9914
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009915 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9916 // A variable of class type (or array thereof) that appears in a private
9917 // clause requires an accessible, unambiguous default constructor for the
9918 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00009919 // Generate helper private variable and initialize it with the default
9920 // value. The address of the original variable is replaced by the address of
9921 // the new private variable in CodeGen. This new variable is not added to
9922 // IdResolver, so the code in the OpenMP region uses original variable for
9923 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009924 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +00009925 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +00009926 buildVarDecl(*this, ELoc, Type, D->getName(),
9927 D->hasAttrs() ? &D->getAttrs() : nullptr,
9928 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00009929 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009930 if (VDPrivate->isInvalidDecl())
9931 continue;
Alexey Bataeve3727102018-04-18 15:57:46 +00009932 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009933 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009934
Alexey Bataev90c228f2016-02-08 09:29:13 +00009935 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009936 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009937 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00009938 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009939 Vars.push_back((VD || CurContext->isDependentContext())
9940 ? RefExpr->IgnoreParens()
9941 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009942 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009943 }
9944
Alexey Bataeved09d242014-05-28 05:53:51 +00009945 if (Vars.empty())
9946 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009947
Alexey Bataev03b340a2014-10-21 03:16:40 +00009948 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9949 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009950}
9951
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009952namespace {
9953class DiagsUninitializedSeveretyRAII {
9954private:
9955 DiagnosticsEngine &Diags;
9956 SourceLocation SavedLoc;
Alexey Bataeve3727102018-04-18 15:57:46 +00009957 bool IsIgnored = false;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009958
9959public:
9960 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9961 bool IsIgnored)
9962 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9963 if (!IsIgnored) {
9964 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9965 /*Map*/ diag::Severity::Ignored, Loc);
9966 }
9967 }
9968 ~DiagsUninitializedSeveretyRAII() {
9969 if (!IsIgnored)
9970 Diags.popMappings(SavedLoc);
9971 }
9972};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009973}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009974
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009975OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9976 SourceLocation StartLoc,
9977 SourceLocation LParenLoc,
9978 SourceLocation EndLoc) {
9979 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009980 SmallVector<Expr *, 8> PrivateCopies;
9981 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00009982 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009983 bool IsImplicitClause =
9984 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
Alexey Bataeve3727102018-04-18 15:57:46 +00009985 SourceLocation ImplicitClauseLoc = DSAStack->getConstructLoc();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009986
Alexey Bataeve3727102018-04-18 15:57:46 +00009987 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009988 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009989 SourceLocation ELoc;
9990 SourceRange ERange;
9991 Expr *SimpleRefExpr = RefExpr;
9992 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009993 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009994 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009995 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009996 PrivateCopies.push_back(nullptr);
9997 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009998 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009999 ValueDecl *D = Res.first;
10000 if (!D)
10001 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010002
Alexey Bataev60da77e2016-02-29 05:54:20 +000010003 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010004 QualType Type = D->getType();
10005 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010006
10007 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10008 // A variable that appears in a private clause must not have an incomplete
10009 // type or a reference type.
10010 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +000010011 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010012 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010013 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010014
10015 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
10016 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +000010017 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010018 // class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000010019 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010020
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010021 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +000010022 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010023 if (!IsImplicitClause) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010024 DSAStackTy::DSAVarData DVar =
10025 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +000010026 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010027 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010028 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010029 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
10030 // A list item that specifies a given variable may not appear in more
10031 // than one clause on the same directive, except that a variable may be
10032 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010033 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10034 // A list item may appear in a firstprivate or lastprivate clause but not
10035 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010036 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010037 (isOpenMPDistributeDirective(CurrDir) ||
10038 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010039 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010040 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010041 << getOpenMPClauseName(DVar.CKind)
10042 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010043 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010044 continue;
10045 }
10046
10047 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10048 // in a Construct]
10049 // Variables with the predetermined data-sharing attributes may not be
10050 // listed in data-sharing attributes clauses, except for the cases
10051 // listed below. For these exceptions only, listing a predetermined
10052 // variable in a data-sharing attribute clause is allowed and overrides
10053 // the variable's predetermined data-sharing attributes.
10054 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10055 // in a Construct, C/C++, p.2]
10056 // Variables with const-qualified type having no mutable member may be
10057 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +000010058 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010059 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
10060 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +000010061 << getOpenMPClauseName(DVar.CKind)
10062 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010063 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010064 continue;
10065 }
10066
10067 // OpenMP [2.9.3.4, Restrictions, p.2]
10068 // A list item that is private within a parallel region must not appear
10069 // in a firstprivate clause on a worksharing construct if any of the
10070 // worksharing regions arising from the worksharing construct ever bind
10071 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010072 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10073 // A list item that is private within a teams region must not appear in a
10074 // firstprivate clause on a distribute construct if any of the distribute
10075 // regions arising from the distribute construct ever bind to any of the
10076 // teams regions arising from the teams construct.
10077 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
10078 // A list item that appears in a reduction clause of a teams construct
10079 // must not appear in a firstprivate clause on a distribute construct if
10080 // any of the distribute regions arising from the distribute construct
10081 // ever bind to any of the teams regions arising from the teams construct.
10082 if ((isOpenMPWorksharingDirective(CurrDir) ||
10083 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010084 !isOpenMPParallelDirective(CurrDir) &&
10085 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010086 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010087 if (DVar.CKind != OMPC_shared &&
10088 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010089 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010090 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +000010091 Diag(ELoc, diag::err_omp_required_access)
10092 << getOpenMPClauseName(OMPC_firstprivate)
10093 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010094 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010095 continue;
10096 }
10097 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010098 // OpenMP [2.9.3.4, Restrictions, p.3]
10099 // A list item that appears in a reduction clause of a parallel construct
10100 // must not appear in a firstprivate clause on a worksharing or task
10101 // construct if any of the worksharing or task regions arising from the
10102 // worksharing or task construct ever bind to any of the parallel regions
10103 // arising from the parallel construct.
10104 // OpenMP [2.9.3.4, Restrictions, p.4]
10105 // A list item that appears in a reduction clause in worksharing
10106 // construct must not appear in a firstprivate clause in a task construct
10107 // encountered during execution of any of the worksharing regions arising
10108 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +000010109 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010110 DVar = DSAStack->hasInnermostDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010111 D, [](OpenMPClauseKind C) { return C == OMPC_reduction; },
10112 [](OpenMPDirectiveKind K) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010113 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010114 isOpenMPWorksharingDirective(K) ||
10115 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010116 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010117 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010118 if (DVar.CKind == OMPC_reduction &&
10119 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010120 isOpenMPWorksharingDirective(DVar.DKind) ||
10121 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010122 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
10123 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000010124 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +000010125 continue;
10126 }
10127 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +000010128
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010129 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
10130 // A list item cannot appear in both a map clause and a data-sharing
10131 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +000010132 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +000010133 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +000010134 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000010135 VD, /*CurrentRegionOnly=*/true,
Alexey Bataeve3727102018-04-18 15:57:46 +000010136 [&ConflictKind](
10137 OMPClauseMappableExprCommon::MappableExprComponentListRef,
10138 OpenMPClauseKind WhereFoundClauseKind) {
Samuel Antao6890b092016-07-28 14:25:09 +000010139 ConflictKind = WhereFoundClauseKind;
10140 return true;
10141 })) {
10142 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010143 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +000010144 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010145 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000010146 reportOriginalDsa(*this, DSAStack, D, DVar);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000010147 continue;
10148 }
10149 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010150 }
10151
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010152 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000010153 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +000010154 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010155 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
10156 << getOpenMPClauseName(OMPC_firstprivate) << Type
10157 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
10158 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010159 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010160 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +000010161 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010162 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +000010163 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +000010164 continue;
10165 }
10166
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010167 Type = Type.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010168 VarDecl *VDPrivate =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000010169 buildVarDecl(*this, ELoc, Type, D->getName(),
10170 D->hasAttrs() ? &D->getAttrs() : nullptr,
10171 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010172 // Generate helper private variable and initialize it with the value of the
10173 // original variable. The address of the original variable is replaced by
10174 // the address of the new private variable in the CodeGen. This new variable
10175 // is not added to IdResolver, so the code in the OpenMP region uses
10176 // original variable for proper diagnostics and variable capturing.
10177 Expr *VDInitRefExpr = nullptr;
10178 // For arrays generate initializer for single element and replace it by the
10179 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010180 if (Type->isArrayType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010181 VarDecl *VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +000010182 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010183 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010184 Expr *Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +000010185 ElemType = ElemType.getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010186 VarDecl *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
10187 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +000010188 InitializedEntity Entity =
10189 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010190 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
10191
10192 InitializationSequence InitSeq(*this, Entity, Kind, Init);
10193 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
10194 if (Result.isInvalid())
10195 VDPrivate->setInvalidDecl();
10196 else
10197 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010198 // Remove temp variable declaration.
10199 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010200 } else {
Alexey Bataeve3727102018-04-18 15:57:46 +000010201 VarDecl *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
10202 ".firstprivate.temp");
Alexey Bataevd985eda2016-02-10 11:29:16 +000010203 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
10204 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +000010205 AddInitializerToDecl(VDPrivate,
10206 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010207 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010208 }
10209 if (VDPrivate->isInvalidDecl()) {
10210 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +000010211 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010212 diag::note_omp_task_predetermined_firstprivate_here);
10213 }
10214 continue;
10215 }
10216 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010217 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +000010218 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
10219 RefExpr->getExprLoc());
10220 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010221 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010222 if (TopDVar.CKind == OMPC_lastprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010223 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010224 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010225 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010226 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010227 ExprCaptures.push_back(Ref->getDecl());
10228 }
Alexey Bataev417089f2016-02-17 13:19:37 +000010229 }
Alexey Bataevd985eda2016-02-10 11:29:16 +000010230 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010231 Vars.push_back((VD || CurContext->isDependentContext())
10232 ? RefExpr->IgnoreParens()
10233 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +000010234 PrivateCopies.push_back(VDPrivateRefExpr);
10235 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010236 }
10237
Alexey Bataeved09d242014-05-28 05:53:51 +000010238 if (Vars.empty())
10239 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010240
10241 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010242 Vars, PrivateCopies, Inits,
10243 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +000010244}
10245
Alexander Musman1bb328c2014-06-04 13:06:39 +000010246OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
10247 SourceLocation StartLoc,
10248 SourceLocation LParenLoc,
10249 SourceLocation EndLoc) {
10250 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +000010251 SmallVector<Expr *, 8> SrcExprs;
10252 SmallVector<Expr *, 8> DstExprs;
10253 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +000010254 SmallVector<Decl *, 4> ExprCaptures;
10255 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataeve3727102018-04-18 15:57:46 +000010256 for (Expr *RefExpr : VarList) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010257 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010258 SourceLocation ELoc;
10259 SourceRange ERange;
10260 Expr *SimpleRefExpr = RefExpr;
10261 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +000010262 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +000010263 // It will be analyzed later.
10264 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010265 SrcExprs.push_back(nullptr);
10266 DstExprs.push_back(nullptr);
10267 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010268 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010269 ValueDecl *D = Res.first;
10270 if (!D)
10271 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010272
Alexey Bataev74caaf22016-02-20 04:09:36 +000010273 QualType Type = D->getType();
10274 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010275
10276 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
10277 // A variable that appears in a lastprivate clause must not have an
10278 // incomplete type or a reference type.
10279 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +000010280 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +000010281 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010282 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010283
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010284 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
10285 // A variable that is privatized must not have a const-qualified type
10286 // unless it is of class type with a mutable member. This restriction does
10287 // not apply to the firstprivate clause.
10288 //
10289 // OpenMP 3.1 [2.9.3.5, lastprivate clause, Restrictions]
10290 // A variable that appears in a lastprivate clause must not have a
10291 // const-qualified type unless it is of class type with a mutable member.
Joel E. Dennyd2649292019-01-04 22:11:56 +000010292 if (rejectConstNotMutableType(*this, D, Type, OMPC_lastprivate, ELoc))
Joel E. Dennye6234d1422019-01-04 22:11:31 +000010293 continue;
10294
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010295 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +000010296 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10297 // in a Construct]
10298 // Variables with the predetermined data-sharing attributes may not be
10299 // listed in data-sharing attributes clauses, except for the cases
10300 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010301 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
10302 // A list item may appear in a firstprivate or lastprivate clause but not
10303 // both.
Alexey Bataeve3727102018-04-18 15:57:46 +000010304 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010305 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +000010306 (isOpenMPDistributeDirective(CurrDir) ||
10307 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +000010308 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
10309 Diag(ELoc, diag::err_omp_wrong_dsa)
10310 << getOpenMPClauseName(DVar.CKind)
10311 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000010312 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +000010313 continue;
10314 }
10315
Alexey Bataevf29276e2014-06-18 04:14:57 +000010316 // OpenMP [2.14.3.5, Restrictions, p.2]
10317 // A list item that is private within a parallel region, or that appears in
10318 // the reduction clause of a parallel construct, must not appear in a
10319 // lastprivate clause on a worksharing construct if any of the corresponding
10320 // worksharing regions ever binds to any of the corresponding parallel
10321 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +000010322 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +000010323 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010324 !isOpenMPParallelDirective(CurrDir) &&
10325 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +000010326 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010327 if (DVar.CKind != OMPC_shared) {
10328 Diag(ELoc, diag::err_omp_required_access)
10329 << getOpenMPClauseName(OMPC_lastprivate)
10330 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010331 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +000010332 continue;
10333 }
10334 }
Alexey Bataev74caaf22016-02-20 04:09:36 +000010335
Alexander Musman1bb328c2014-06-04 13:06:39 +000010336 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +000010337 // A variable of class type (or array thereof) that appears in a
10338 // lastprivate clause requires an accessible, unambiguous default
10339 // constructor for the class type, unless the list item is also specified
10340 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +000010341 // A variable of class type (or array thereof) that appears in a
10342 // lastprivate clause requires an accessible, unambiguous copy assignment
10343 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +000010344 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010345 VarDecl *SrcVD = buildVarDecl(*this, ERange.getBegin(),
10346 Type.getUnqualifiedType(), ".lastprivate.src",
10347 D->hasAttrs() ? &D->getAttrs() : nullptr);
10348 DeclRefExpr *PseudoSrcExpr =
Alexey Bataev74caaf22016-02-20 04:09:36 +000010349 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataeve3727102018-04-18 15:57:46 +000010350 VarDecl *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010351 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +000010352 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000010353 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +000010354 // For arrays generate assignment operation for single element and replace
10355 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000010356 ExprResult AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
10357 PseudoDstExpr, PseudoSrcExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +000010358 if (AssignmentOp.isInvalid())
10359 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000010360 AssignmentOp =
10361 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataev38e89532015-04-16 04:54:05 +000010362 if (AssignmentOp.isInvalid())
10363 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +000010364
Alexey Bataev74caaf22016-02-20 04:09:36 +000010365 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010366 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010367 if (TopDVar.CKind == OMPC_firstprivate) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010368 Ref = TopDVar.PrivateCopy;
Alexey Bataeve3727102018-04-18 15:57:46 +000010369 } else {
Alexey Bataev61205072016-03-02 04:57:40 +000010370 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000010371 if (!isOpenMPCapturedDecl(D))
Alexey Bataev005248a2016-02-25 05:25:57 +000010372 ExprCaptures.push_back(Ref->getDecl());
10373 }
10374 if (TopDVar.CKind == OMPC_firstprivate ||
Alexey Bataeve3727102018-04-18 15:57:46 +000010375 (!isOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010376 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +000010377 ExprResult RefRes = DefaultLvalueConversion(Ref);
10378 if (!RefRes.isUsable())
10379 continue;
10380 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +000010381 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10382 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010383 if (!PostUpdateRes.isUsable())
10384 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010385 ExprPostUpdates.push_back(
10386 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +000010387 }
10388 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010389 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010390 Vars.push_back((VD || CurContext->isDependentContext())
10391 ? RefExpr->IgnoreParens()
10392 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +000010393 SrcExprs.push_back(PseudoSrcExpr);
10394 DstExprs.push_back(PseudoDstExpr);
10395 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +000010396 }
10397
10398 if (Vars.empty())
10399 return nullptr;
10400
10401 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +000010402 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010403 buildPreInits(Context, ExprCaptures),
10404 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +000010405}
10406
Alexey Bataev758e55e2013-09-06 18:03:48 +000010407OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
10408 SourceLocation StartLoc,
10409 SourceLocation LParenLoc,
10410 SourceLocation EndLoc) {
10411 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000010412 for (Expr *RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010413 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +000010414 SourceLocation ELoc;
10415 SourceRange ERange;
10416 Expr *SimpleRefExpr = RefExpr;
10417 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010418 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +000010419 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010420 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010421 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010422 ValueDecl *D = Res.first;
10423 if (!D)
10424 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010425
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010426 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010427 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
10428 // in a Construct]
10429 // Variables with the predetermined data-sharing attributes may not be
10430 // listed in data-sharing attributes clauses, except for the cases
10431 // listed below. For these exceptions only, listing a predetermined
10432 // variable in a data-sharing attribute clause is allowed and overrides
10433 // the variable's predetermined data-sharing attributes.
Alexey Bataeve3727102018-04-18 15:57:46 +000010434 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeved09d242014-05-28 05:53:51 +000010435 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
10436 DVar.RefExpr) {
10437 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10438 << getOpenMPClauseName(OMPC_shared);
Alexey Bataeve3727102018-04-18 15:57:46 +000010439 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010440 continue;
10441 }
10442
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010443 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010444 if (!VD && isOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +000010445 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +000010446 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010447 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
10448 ? RefExpr->IgnoreParens()
10449 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +000010450 }
10451
Alexey Bataeved09d242014-05-28 05:53:51 +000010452 if (Vars.empty())
10453 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000010454
10455 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
10456}
10457
Alexey Bataevc5e02582014-06-16 07:08:35 +000010458namespace {
10459class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
10460 DSAStackTy *Stack;
10461
10462public:
10463 bool VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010464 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
10465 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, /*FromParent=*/false);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010466 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
10467 return false;
10468 if (DVar.CKind != OMPC_unknown)
10469 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +000010470 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
Alexey Bataeve3727102018-04-18 15:57:46 +000010471 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +000010472 /*FromParent=*/true);
Alexey Bataeve3727102018-04-18 15:57:46 +000010473 return DVarPrivate.CKind != OMPC_unknown;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010474 }
10475 return false;
10476 }
10477 bool VisitStmt(Stmt *S) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010478 for (Stmt *Child : S->children()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010479 if (Child && Visit(Child))
10480 return true;
10481 }
10482 return false;
10483 }
Alexey Bataev23b69422014-06-18 07:08:49 +000010484 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010485};
Alexey Bataev23b69422014-06-18 07:08:49 +000010486} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +000010487
Alexey Bataev60da77e2016-02-29 05:54:20 +000010488namespace {
10489// Transform MemberExpression for specified FieldDecl of current class to
10490// DeclRefExpr to specified OMPCapturedExprDecl.
10491class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
10492 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
Alexey Bataeve3727102018-04-18 15:57:46 +000010493 ValueDecl *Field = nullptr;
10494 DeclRefExpr *CapturedExpr = nullptr;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010495
10496public:
10497 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
10498 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
10499
10500 ExprResult TransformMemberExpr(MemberExpr *E) {
10501 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
10502 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +000010503 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010504 return CapturedExpr;
10505 }
10506 return BaseTransform::TransformMemberExpr(E);
10507 }
10508 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
10509};
10510} // namespace
10511
Alexey Bataev97d18bf2018-04-11 19:21:00 +000010512template <typename T, typename U>
10513static T filterLookupForUDR(SmallVectorImpl<U> &Lookups,
10514 const llvm::function_ref<T(ValueDecl *)> Gen) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010515 for (U &Set : Lookups) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010516 for (auto *D : Set) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010517 if (T Res = Gen(cast<ValueDecl>(D)))
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010518 return Res;
10519 }
10520 }
10521 return T();
10522}
10523
Alexey Bataev43b90b72018-09-12 16:31:59 +000010524static NamedDecl *findAcceptableDecl(Sema &SemaRef, NamedDecl *D) {
10525 assert(!LookupResult::isVisible(SemaRef, D) && "not in slow case");
10526
10527 for (auto RD : D->redecls()) {
10528 // Don't bother with extra checks if we already know this one isn't visible.
10529 if (RD == D)
10530 continue;
10531
10532 auto ND = cast<NamedDecl>(RD);
10533 if (LookupResult::isVisible(SemaRef, ND))
10534 return ND;
10535 }
10536
10537 return nullptr;
10538}
10539
10540static void
10541argumentDependentLookup(Sema &SemaRef, const DeclarationNameInfo &ReductionId,
10542 SourceLocation Loc, QualType Ty,
10543 SmallVectorImpl<UnresolvedSet<8>> &Lookups) {
10544 // Find all of the associated namespaces and classes based on the
10545 // arguments we have.
10546 Sema::AssociatedNamespaceSet AssociatedNamespaces;
10547 Sema::AssociatedClassSet AssociatedClasses;
10548 OpaqueValueExpr OVE(Loc, Ty, VK_LValue);
10549 SemaRef.FindAssociatedClassesAndNamespaces(Loc, &OVE, AssociatedNamespaces,
10550 AssociatedClasses);
10551
10552 // C++ [basic.lookup.argdep]p3:
10553 // Let X be the lookup set produced by unqualified lookup (3.4.1)
10554 // and let Y be the lookup set produced by argument dependent
10555 // lookup (defined as follows). If X contains [...] then Y is
10556 // empty. Otherwise Y is the set of declarations found in the
10557 // namespaces associated with the argument types as described
10558 // below. The set of declarations found by the lookup of the name
10559 // is the union of X and Y.
10560 //
10561 // Here, we compute Y and add its members to the overloaded
10562 // candidate set.
10563 for (auto *NS : AssociatedNamespaces) {
10564 // When considering an associated namespace, the lookup is the
10565 // same as the lookup performed when the associated namespace is
10566 // used as a qualifier (3.4.3.2) except that:
10567 //
10568 // -- Any using-directives in the associated namespace are
10569 // ignored.
10570 //
10571 // -- Any namespace-scope friend functions declared in
10572 // associated classes are visible within their respective
10573 // namespaces even if they are not visible during an ordinary
10574 // lookup (11.4).
10575 DeclContext::lookup_result R = NS->lookup(ReductionId.getName());
10576 for (auto *D : R) {
10577 auto *Underlying = D;
10578 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10579 Underlying = USD->getTargetDecl();
10580
10581 if (!isa<OMPDeclareReductionDecl>(Underlying))
10582 continue;
10583
10584 if (!SemaRef.isVisible(D)) {
10585 D = findAcceptableDecl(SemaRef, D);
10586 if (!D)
10587 continue;
10588 if (auto *USD = dyn_cast<UsingShadowDecl>(D))
10589 Underlying = USD->getTargetDecl();
10590 }
10591 Lookups.emplace_back();
10592 Lookups.back().addDecl(Underlying);
10593 }
10594 }
10595}
10596
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010597static ExprResult
10598buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
10599 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
10600 const DeclarationNameInfo &ReductionId, QualType Ty,
10601 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
10602 if (ReductionIdScopeSpec.isInvalid())
10603 return ExprError();
10604 SmallVector<UnresolvedSet<8>, 4> Lookups;
10605 if (S) {
10606 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10607 Lookup.suppressDiagnostics();
10608 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010609 NamedDecl *D = Lookup.getRepresentativeDecl();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010610 do {
10611 S = S->getParent();
10612 } while (S && !S->isDeclScope(D));
10613 if (S)
10614 S = S->getParent();
Alexey Bataev43b90b72018-09-12 16:31:59 +000010615 Lookups.emplace_back();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010616 Lookups.back().append(Lookup.begin(), Lookup.end());
10617 Lookup.clear();
10618 }
10619 } else if (auto *ULE =
10620 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
10621 Lookups.push_back(UnresolvedSet<8>());
10622 Decl *PrevD = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000010623 for (NamedDecl *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010624 if (D == PrevD)
10625 Lookups.push_back(UnresolvedSet<8>());
10626 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
10627 Lookups.back().addDecl(DRD);
10628 PrevD = D;
10629 }
10630 }
Alexey Bataevfdc20352017-08-25 15:43:55 +000010631 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
10632 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010633 Ty->containsUnexpandedParameterPack() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000010634 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010635 return !D->isInvalidDecl() &&
10636 (D->getType()->isDependentType() ||
10637 D->getType()->isInstantiationDependentType() ||
10638 D->getType()->containsUnexpandedParameterPack());
10639 })) {
10640 UnresolvedSet<8> ResSet;
Alexey Bataeve3727102018-04-18 15:57:46 +000010641 for (const UnresolvedSet<8> &Set : Lookups) {
Alexey Bataev43b90b72018-09-12 16:31:59 +000010642 if (Set.empty())
10643 continue;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010644 ResSet.append(Set.begin(), Set.end());
10645 // The last item marks the end of all declarations at the specified scope.
10646 ResSet.addDecl(Set[Set.size() - 1]);
10647 }
10648 return UnresolvedLookupExpr::Create(
10649 SemaRef.Context, /*NamingClass=*/nullptr,
10650 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
10651 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
10652 }
Alexey Bataev43b90b72018-09-12 16:31:59 +000010653 // Lookup inside the classes.
10654 // C++ [over.match.oper]p3:
10655 // For a unary operator @ with an operand of a type whose
10656 // cv-unqualified version is T1, and for a binary operator @ with
10657 // a left operand of a type whose cv-unqualified version is T1 and
10658 // a right operand of a type whose cv-unqualified version is T2,
10659 // three sets of candidate functions, designated member
10660 // candidates, non-member candidates and built-in candidates, are
10661 // constructed as follows:
10662 // -- If T1 is a complete class type or a class currently being
10663 // defined, the set of member candidates is the result of the
10664 // qualified lookup of T1::operator@ (13.3.1.1.1); otherwise,
10665 // the set of member candidates is empty.
10666 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
10667 Lookup.suppressDiagnostics();
10668 if (const auto *TyRec = Ty->getAs<RecordType>()) {
10669 // Complete the type if it can be completed.
10670 // If the type is neither complete nor being defined, bail out now.
10671 if (SemaRef.isCompleteType(Loc, Ty) || TyRec->isBeingDefined() ||
10672 TyRec->getDecl()->getDefinition()) {
10673 Lookup.clear();
10674 SemaRef.LookupQualifiedName(Lookup, TyRec->getDecl());
10675 if (Lookup.empty()) {
10676 Lookups.emplace_back();
10677 Lookups.back().append(Lookup.begin(), Lookup.end());
10678 }
10679 }
10680 }
10681 // Perform ADL.
10682 argumentDependentLookup(SemaRef, ReductionId, Loc, Ty, Lookups);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010683 if (auto *VD = filterLookupForUDR<ValueDecl *>(
10684 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
10685 if (!D->isInvalidDecl() &&
10686 SemaRef.Context.hasSameType(D->getType(), Ty))
10687 return D;
10688 return nullptr;
10689 }))
10690 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
10691 if (auto *VD = filterLookupForUDR<ValueDecl *>(
10692 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
10693 if (!D->isInvalidDecl() &&
10694 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
10695 !Ty.isMoreQualifiedThan(D->getType()))
10696 return D;
10697 return nullptr;
10698 })) {
10699 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
10700 /*DetectVirtual=*/false);
10701 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
10702 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
10703 VD->getType().getUnqualifiedType()))) {
10704 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
10705 /*DiagID=*/0) !=
10706 Sema::AR_inaccessible) {
10707 SemaRef.BuildBasePathArray(Paths, BasePath);
10708 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
10709 }
10710 }
10711 }
10712 }
10713 if (ReductionIdScopeSpec.isSet()) {
10714 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
10715 return ExprError();
10716 }
10717 return ExprEmpty();
10718}
10719
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010720namespace {
10721/// Data for the reduction-based clauses.
10722struct ReductionData {
10723 /// List of original reduction items.
10724 SmallVector<Expr *, 8> Vars;
10725 /// List of private copies of the reduction items.
10726 SmallVector<Expr *, 8> Privates;
10727 /// LHS expressions for the reduction_op expressions.
10728 SmallVector<Expr *, 8> LHSs;
10729 /// RHS expressions for the reduction_op expressions.
10730 SmallVector<Expr *, 8> RHSs;
10731 /// Reduction operation expression.
10732 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000010733 /// Taskgroup descriptors for the corresponding reduction items in
10734 /// in_reduction clauses.
10735 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010736 /// List of captures for clause.
10737 SmallVector<Decl *, 4> ExprCaptures;
10738 /// List of postupdate expressions.
10739 SmallVector<Expr *, 4> ExprPostUpdates;
10740 ReductionData() = delete;
10741 /// Reserves required memory for the reduction data.
10742 ReductionData(unsigned Size) {
10743 Vars.reserve(Size);
10744 Privates.reserve(Size);
10745 LHSs.reserve(Size);
10746 RHSs.reserve(Size);
10747 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000010748 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010749 ExprCaptures.reserve(Size);
10750 ExprPostUpdates.reserve(Size);
10751 }
10752 /// Stores reduction item and reduction operation only (required for dependent
10753 /// reduction item).
10754 void push(Expr *Item, Expr *ReductionOp) {
10755 Vars.emplace_back(Item);
10756 Privates.emplace_back(nullptr);
10757 LHSs.emplace_back(nullptr);
10758 RHSs.emplace_back(nullptr);
10759 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010760 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010761 }
10762 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000010763 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
10764 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010765 Vars.emplace_back(Item);
10766 Privates.emplace_back(Private);
10767 LHSs.emplace_back(LHS);
10768 RHSs.emplace_back(RHS);
10769 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010770 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010771 }
10772};
10773} // namespace
10774
Alexey Bataeve3727102018-04-18 15:57:46 +000010775static bool checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010776 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
10777 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
10778 const Expr *Length = OASE->getLength();
10779 if (Length == nullptr) {
10780 // For array sections of the form [1:] or [:], we would need to analyze
10781 // the lower bound...
10782 if (OASE->getColonLoc().isValid())
10783 return false;
10784
10785 // This is an array subscript which has implicit length 1!
10786 SingleElement = true;
10787 ArraySizes.push_back(llvm::APSInt::get(1));
10788 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000010789 Expr::EvalResult Result;
10790 if (!Length->EvaluateAsInt(Result, Context))
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010791 return false;
10792
Fangrui Song407659a2018-11-30 23:41:18 +000010793 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010794 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
10795 ArraySizes.push_back(ConstantLengthValue);
10796 }
10797
10798 // Get the base of this array section and walk up from there.
10799 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10800
10801 // We require length = 1 for all array sections except the right-most to
10802 // guarantee that the memory region is contiguous and has no holes in it.
10803 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10804 Length = TempOASE->getLength();
10805 if (Length == nullptr) {
10806 // For array sections of the form [1:] or [:], we would need to analyze
10807 // the lower bound...
10808 if (OASE->getColonLoc().isValid())
10809 return false;
10810
10811 // This is an array subscript which has implicit length 1!
10812 ArraySizes.push_back(llvm::APSInt::get(1));
10813 } else {
Fangrui Song407659a2018-11-30 23:41:18 +000010814 Expr::EvalResult Result;
10815 if (!Length->EvaluateAsInt(Result, Context))
10816 return false;
10817
10818 llvm::APSInt ConstantLengthValue = Result.Val.getInt();
10819 if (ConstantLengthValue.getSExtValue() != 1)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010820 return false;
10821
10822 ArraySizes.push_back(ConstantLengthValue);
10823 }
10824 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10825 }
10826
10827 // If we have a single element, we don't need to add the implicit lengths.
10828 if (!SingleElement) {
10829 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10830 // Has implicit length 1!
10831 ArraySizes.push_back(llvm::APSInt::get(1));
10832 Base = TempASE->getBase()->IgnoreParenImpCasts();
10833 }
10834 }
10835
10836 // This array section can be privatized as a single value or as a constant
10837 // sized array.
10838 return true;
10839}
10840
Alexey Bataeve3727102018-04-18 15:57:46 +000010841static bool actOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000010842 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10843 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10844 SourceLocation ColonLoc, SourceLocation EndLoc,
10845 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010846 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000010847 DeclarationName DN = ReductionId.getName();
10848 OverloadedOperatorKind OOK = DN.getCXXOverloadedOperator();
Alexey Bataevc5e02582014-06-16 07:08:35 +000010849 BinaryOperatorKind BOK = BO_Comma;
10850
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010851 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010852 // OpenMP [2.14.3.6, reduction clause]
10853 // C
10854 // reduction-identifier is either an identifier or one of the following
10855 // operators: +, -, *, &, |, ^, && and ||
10856 // C++
10857 // reduction-identifier is either an id-expression or one of the following
10858 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000010859 switch (OOK) {
10860 case OO_Plus:
10861 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010862 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010863 break;
10864 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010865 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010866 break;
10867 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010868 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010869 break;
10870 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010871 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010872 break;
10873 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010874 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010875 break;
10876 case OO_AmpAmp:
10877 BOK = BO_LAnd;
10878 break;
10879 case OO_PipePipe:
10880 BOK = BO_LOr;
10881 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010882 case OO_New:
10883 case OO_Delete:
10884 case OO_Array_New:
10885 case OO_Array_Delete:
10886 case OO_Slash:
10887 case OO_Percent:
10888 case OO_Tilde:
10889 case OO_Exclaim:
10890 case OO_Equal:
10891 case OO_Less:
10892 case OO_Greater:
10893 case OO_LessEqual:
10894 case OO_GreaterEqual:
10895 case OO_PlusEqual:
10896 case OO_MinusEqual:
10897 case OO_StarEqual:
10898 case OO_SlashEqual:
10899 case OO_PercentEqual:
10900 case OO_CaretEqual:
10901 case OO_AmpEqual:
10902 case OO_PipeEqual:
10903 case OO_LessLess:
10904 case OO_GreaterGreater:
10905 case OO_LessLessEqual:
10906 case OO_GreaterGreaterEqual:
10907 case OO_EqualEqual:
10908 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000010909 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010910 case OO_PlusPlus:
10911 case OO_MinusMinus:
10912 case OO_Comma:
10913 case OO_ArrowStar:
10914 case OO_Arrow:
10915 case OO_Call:
10916 case OO_Subscript:
10917 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000010918 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010919 case NUM_OVERLOADED_OPERATORS:
10920 llvm_unreachable("Unexpected reduction identifier");
10921 case OO_None:
Alexey Bataeve3727102018-04-18 15:57:46 +000010922 if (IdentifierInfo *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010923 if (II->isStr("max"))
10924 BOK = BO_GT;
10925 else if (II->isStr("min"))
10926 BOK = BO_LT;
10927 }
10928 break;
10929 }
10930 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010931 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000010932 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010933 else
10934 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000010935 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000010936
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010937 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
10938 bool FirstIter = true;
Alexey Bataeve3727102018-04-18 15:57:46 +000010939 for (Expr *RefExpr : VarList) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010940 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000010941 // OpenMP [2.1, C/C++]
10942 // A list item is a variable or array section, subject to the restrictions
10943 // specified in Section 2.4 on page 42 and in each of the sections
10944 // describing clauses and directives for which a list appears.
10945 // OpenMP [2.14.3.3, Restrictions, p.1]
10946 // A variable that is part of another variable (as an array or
10947 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010948 if (!FirstIter && IR != ER)
10949 ++IR;
10950 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010951 SourceLocation ELoc;
10952 SourceRange ERange;
10953 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010954 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000010955 /*AllowArraySection=*/true);
10956 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010957 // Try to find 'declare reduction' corresponding construct before using
10958 // builtin/overloaded operators.
10959 QualType Type = Context.DependentTy;
10960 CXXCastPath BasePath;
10961 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010962 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010963 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010964 Expr *ReductionOp = nullptr;
10965 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010966 (DeclareReductionRef.isUnset() ||
10967 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010968 ReductionOp = DeclareReductionRef.get();
10969 // It will be analyzed later.
10970 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010971 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010972 ValueDecl *D = Res.first;
10973 if (!D)
10974 continue;
10975
Alexey Bataev88202be2017-07-27 13:20:36 +000010976 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000010977 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010978 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
10979 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
Alexey Bataeve3727102018-04-18 15:57:46 +000010980 if (ASE) {
Alexey Bataev31300ed2016-02-04 11:27:03 +000010981 Type = ASE->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010982 } else if (OASE) {
10983 QualType BaseType =
10984 OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
10985 if (const auto *ATy = BaseType->getAsArrayTypeUnsafe())
Alexey Bataeva1764212015-09-30 09:22:36 +000010986 Type = ATy->getElementType();
10987 else
10988 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000010989 Type = Type.getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000010990 } else {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010991 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
Alexey Bataeve3727102018-04-18 15:57:46 +000010992 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010993 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000010994
Alexey Bataevc5e02582014-06-16 07:08:35 +000010995 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10996 // A variable that appears in a private clause must not have an incomplete
10997 // type or a reference type.
Joel E. Denny3cabf732018-06-28 19:54:49 +000010998 if (S.RequireCompleteType(ELoc, D->getType(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010999 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011000 continue;
11001 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000011002 // A list item that appears in a reduction clause must not be
11003 // const-qualified.
Joel E. Dennyd2649292019-01-04 22:11:56 +000011004 if (rejectConstNotMutableType(S, D, Type, ClauseKind, ELoc,
11005 /*AcceptIfMutable*/ false, ASE || OASE))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011006 continue;
Alexey Bataevbc529672018-09-28 19:33:14 +000011007
11008 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011009 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
11010 // If a list-item is a reference type then it must bind to the same object
11011 // for all threads of the team.
Alexey Bataevbc529672018-09-28 19:33:14 +000011012 if (!ASE && !OASE) {
11013 if (VD) {
11014 VarDecl *VDDef = VD->getDefinition();
11015 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
11016 DSARefChecker Check(Stack);
11017 if (Check.Visit(VDDef->getInit())) {
11018 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
11019 << getOpenMPClauseName(ClauseKind) << ERange;
11020 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
11021 continue;
11022 }
Alexey Bataeva1764212015-09-30 09:22:36 +000011023 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000011024 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011025
Alexey Bataevbc529672018-09-28 19:33:14 +000011026 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
11027 // in a Construct]
11028 // Variables with the predetermined data-sharing attributes may not be
11029 // listed in data-sharing attributes clauses, except for the cases
11030 // listed below. For these exceptions only, listing a predetermined
11031 // variable in a data-sharing attribute clause is allowed and overrides
11032 // the variable's predetermined data-sharing attributes.
11033 // OpenMP [2.14.3.6, Restrictions, p.3]
11034 // Any number of reduction clauses can be specified on the directive,
11035 // but a list item can appear only once in the reduction clauses for that
11036 // directive.
11037 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(D, /*FromParent=*/false);
11038 if (DVar.CKind == OMPC_reduction) {
11039 S.Diag(ELoc, diag::err_omp_once_referenced)
11040 << getOpenMPClauseName(ClauseKind);
11041 if (DVar.RefExpr)
11042 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
11043 continue;
11044 }
11045 if (DVar.CKind != OMPC_unknown) {
11046 S.Diag(ELoc, diag::err_omp_wrong_dsa)
11047 << getOpenMPClauseName(DVar.CKind)
11048 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataeve3727102018-04-18 15:57:46 +000011049 reportOriginalDsa(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011050 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000011051 }
Alexey Bataevbc529672018-09-28 19:33:14 +000011052
11053 // OpenMP [2.14.3.6, Restrictions, p.1]
11054 // A list item that appears in a reduction clause of a worksharing
11055 // construct must be shared in the parallel regions to which any of the
11056 // worksharing regions arising from the worksharing construct bind.
11057 if (isOpenMPWorksharingDirective(CurrDir) &&
11058 !isOpenMPParallelDirective(CurrDir) &&
11059 !isOpenMPTeamsDirective(CurrDir)) {
11060 DVar = Stack->getImplicitDSA(D, true);
11061 if (DVar.CKind != OMPC_shared) {
11062 S.Diag(ELoc, diag::err_omp_required_access)
11063 << getOpenMPClauseName(OMPC_reduction)
11064 << getOpenMPClauseName(OMPC_shared);
11065 reportOriginalDsa(S, Stack, D, DVar);
11066 continue;
11067 }
11068 }
Alexey Bataevf29276e2014-06-18 04:14:57 +000011069 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011070
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011071 // Try to find 'declare reduction' corresponding construct before using
11072 // builtin/overloaded operators.
11073 CXXCastPath BasePath;
11074 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011075 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011076 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
11077 if (DeclareReductionRef.isInvalid())
11078 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011079 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011080 (DeclareReductionRef.isUnset() ||
11081 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011082 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011083 continue;
11084 }
11085 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
11086 // Not allowed reduction identifier is found.
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011087 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011088 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011089 << Type << ReductionIdRange;
11090 continue;
11091 }
11092
11093 // OpenMP [2.14.3.6, reduction clause, Restrictions]
11094 // The type of a list item that appears in a reduction clause must be valid
11095 // for the reduction-identifier. For a max or min reduction in C, the type
11096 // of the list item must be an allowed arithmetic data type: char, int,
11097 // float, double, or _Bool, possibly modified with long, short, signed, or
11098 // unsigned. For a max or min reduction in C++, the type of the list item
11099 // must be an allowed arithmetic data type: char, wchar_t, int, float,
11100 // double, or bool, possibly modified with long, short, signed, or unsigned.
11101 if (DeclareReductionRef.isUnset()) {
11102 if ((BOK == BO_GT || BOK == BO_LT) &&
11103 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011104 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
11105 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000011106 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011107 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011108 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11109 VarDecl::DeclarationOnly;
11110 S.Diag(D->getLocation(),
11111 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011112 << D;
11113 }
11114 continue;
11115 }
11116 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011117 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000011118 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
11119 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011120 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011121 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11122 VarDecl::DeclarationOnly;
11123 S.Diag(D->getLocation(),
11124 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011125 << D;
11126 }
11127 continue;
11128 }
11129 }
11130
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011131 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011132 VarDecl *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
11133 D->hasAttrs() ? &D->getAttrs() : nullptr);
11134 VarDecl *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
11135 D->hasAttrs() ? &D->getAttrs() : nullptr);
11136 QualType PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011137
11138 // Try if we can determine constant lengths for all array sections and avoid
11139 // the VLA.
11140 bool ConstantLengthOASE = false;
11141 if (OASE) {
11142 bool SingleElement;
11143 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
Alexey Bataeve3727102018-04-18 15:57:46 +000011144 ConstantLengthOASE = checkOMPArraySectionConstantForReduction(
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011145 Context, OASE, SingleElement, ArraySizes);
11146
11147 // If we don't have a single element, we must emit a constant array type.
11148 if (ConstantLengthOASE && !SingleElement) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011149 for (llvm::APSInt &Size : ArraySizes)
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011150 PrivateTy = Context.getConstantArrayType(
11151 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000011152 }
11153 }
11154
11155 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000011156 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000011157 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000011158 if (!Context.getTargetInfo().isVLASupported() &&
11159 S.shouldDiagnoseTargetSupportFromOpenMP()) {
11160 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
11161 S.Diag(ELoc, diag::note_vla_unsupported);
11162 continue;
11163 }
David Majnemer9d168222016-08-05 17:44:54 +000011164 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011165 // Create pseudo array type for private copy. The size for this array will
11166 // be generated during codegen.
11167 // For array subscripts or single variables Private Ty is the same as Type
11168 // (type of the variable or single array element).
11169 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011170 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000011171 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011172 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000011173 } else if (!ASE && !OASE &&
Alexey Bataeve3727102018-04-18 15:57:46 +000011174 Context.getAsArrayType(D->getType().getNonReferenceType())) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011175 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataeve3727102018-04-18 15:57:46 +000011176 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011177 // Private copy.
Alexey Bataeve3727102018-04-18 15:57:46 +000011178 VarDecl *PrivateVD =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011179 buildVarDecl(S, ELoc, PrivateTy, D->getName(),
11180 D->hasAttrs() ? &D->getAttrs() : nullptr,
11181 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011182 // Add initializer for private variable.
11183 Expr *Init = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011184 DeclRefExpr *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
11185 DeclRefExpr *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011186 if (DeclareReductionRef.isUsable()) {
11187 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
11188 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
11189 if (DRD->getInitializer()) {
11190 Init = DRDRef;
11191 RHSVD->setInit(DRDRef);
11192 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011193 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011194 } else {
11195 switch (BOK) {
11196 case BO_Add:
11197 case BO_Xor:
11198 case BO_Or:
11199 case BO_LOr:
11200 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
11201 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011202 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011203 break;
11204 case BO_Mul:
11205 case BO_LAnd:
11206 if (Type->isScalarType() || Type->isAnyComplexType()) {
11207 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011208 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000011209 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011210 break;
11211 case BO_And: {
11212 // '&' reduction op - initializer is '~0'.
11213 QualType OrigType = Type;
11214 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
11215 Type = ComplexTy->getElementType();
11216 if (Type->isRealFloatingType()) {
11217 llvm::APFloat InitValue =
11218 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
11219 /*isIEEE=*/true);
11220 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11221 Type, ELoc);
11222 } else if (Type->isScalarType()) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011223 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011224 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
11225 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
11226 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11227 }
11228 if (Init && OrigType->isAnyComplexType()) {
11229 // Init = 0xFFFF + 0xFFFFi;
11230 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011231 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011232 }
11233 Type = OrigType;
11234 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011235 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011236 case BO_LT:
11237 case BO_GT: {
11238 // 'min' reduction op - initializer is 'Largest representable number in
11239 // the reduction list item type'.
11240 // 'max' reduction op - initializer is 'Least representable number in
11241 // the reduction list item type'.
11242 if (Type->isIntegerType() || Type->isPointerType()) {
11243 bool IsSigned = Type->hasSignedIntegerRepresentation();
Alexey Bataeve3727102018-04-18 15:57:46 +000011244 uint64_t Size = Context.getTypeSize(Type);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011245 QualType IntTy =
11246 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
11247 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011248 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
11249 : llvm::APInt::getMinValue(Size)
11250 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
11251 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011252 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
11253 if (Type->isPointerType()) {
11254 // Cast to pointer type.
Alexey Bataeve3727102018-04-18 15:57:46 +000011255 ExprResult CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000011256 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011257 if (CastExpr.isInvalid())
11258 continue;
11259 Init = CastExpr.get();
11260 }
11261 } else if (Type->isRealFloatingType()) {
11262 llvm::APFloat InitValue = llvm::APFloat::getLargest(
11263 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
11264 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
11265 Type, ELoc);
11266 }
11267 break;
11268 }
11269 case BO_PtrMemD:
11270 case BO_PtrMemI:
11271 case BO_MulAssign:
11272 case BO_Div:
11273 case BO_Rem:
11274 case BO_Sub:
11275 case BO_Shl:
11276 case BO_Shr:
11277 case BO_LE:
11278 case BO_GE:
11279 case BO_EQ:
11280 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000011281 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011282 case BO_AndAssign:
11283 case BO_XorAssign:
11284 case BO_OrAssign:
11285 case BO_Assign:
11286 case BO_AddAssign:
11287 case BO_SubAssign:
11288 case BO_DivAssign:
11289 case BO_RemAssign:
11290 case BO_ShlAssign:
11291 case BO_ShrAssign:
11292 case BO_Comma:
11293 llvm_unreachable("Unexpected reduction operation");
11294 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011295 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011296 if (Init && DeclareReductionRef.isUnset())
11297 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
11298 else if (!Init)
11299 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011300 if (RHSVD->isInvalidDecl())
11301 continue;
11302 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011303 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
11304 << Type << ReductionIdRange;
11305 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
11306 VarDecl::DeclarationOnly;
11307 S.Diag(D->getLocation(),
11308 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000011309 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011310 continue;
11311 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000011312 // Store initializer for single element in private copy. Will be used during
11313 // codegen.
11314 PrivateVD->setInit(RHSVD->getInit());
11315 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataeve3727102018-04-18 15:57:46 +000011316 DeclRefExpr *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011317 ExprResult ReductionOp;
11318 if (DeclareReductionRef.isUsable()) {
11319 QualType RedTy = DeclareReductionRef.get()->getType();
11320 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011321 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
11322 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011323 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011324 LHS = S.DefaultLvalueConversion(LHS.get());
11325 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011326 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11327 CK_UncheckedDerivedToBase, LHS.get(),
11328 &BasePath, LHS.get()->getValueKind());
11329 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
11330 CK_UncheckedDerivedToBase, RHS.get(),
11331 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000011332 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011333 FunctionProtoType::ExtProtoInfo EPI;
11334 QualType Params[] = {PtrRedTy, PtrRedTy};
11335 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
11336 auto *OVE = new (Context) OpaqueValueExpr(
11337 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011338 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011339 Expr *Args[] = {LHS.get(), RHS.get()};
Bruno Riccic5885cf2018-12-21 15:20:32 +000011340 ReductionOp =
11341 CallExpr::Create(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011342 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011343 ReductionOp = S.BuildBinOp(
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011344 Stack->getCurScope(), ReductionId.getBeginLoc(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011345 if (ReductionOp.isUsable()) {
11346 if (BOK != BO_LT && BOK != BO_GT) {
11347 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011348 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011349 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011350 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000011351 auto *ConditionalOp = new (Context)
11352 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
11353 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011354 ReductionOp =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011355 S.BuildBinOp(Stack->getCurScope(), ReductionId.getBeginLoc(),
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011356 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011357 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011358 if (ReductionOp.isUsable())
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011359 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get(),
11360 /*DiscardedValue*/ false);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011361 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000011362 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000011363 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000011364 }
11365
Alexey Bataevfa312f32017-07-21 18:48:21 +000011366 // OpenMP [2.15.4.6, Restrictions, p.2]
11367 // A list item that appears in an in_reduction clause of a task construct
11368 // must appear in a task_reduction clause of a construct associated with a
11369 // taskgroup region that includes the participating task in its taskgroup
11370 // set. The construct associated with the innermost region that meets this
11371 // condition must specify the same reduction-identifier as the in_reduction
11372 // clause.
11373 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000011374 SourceRange ParentSR;
11375 BinaryOperatorKind ParentBOK;
11376 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000011377 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000011378 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011379 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
11380 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011381 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000011382 Stack->getTopMostTaskgroupReductionData(
11383 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011384 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
11385 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
11386 if (!IsParentBOK && !IsParentReductionOp) {
11387 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
11388 continue;
11389 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000011390 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
11391 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
11392 IsParentReductionOp) {
11393 bool EmitError = true;
11394 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
11395 llvm::FoldingSetNodeID RedId, ParentRedId;
11396 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
11397 DeclareReductionRef.get()->Profile(RedId, Context,
11398 /*Canonical=*/true);
11399 EmitError = RedId != ParentRedId;
11400 }
11401 if (EmitError) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011402 S.Diag(ReductionId.getBeginLoc(),
Alexey Bataevfa312f32017-07-21 18:48:21 +000011403 diag::err_omp_reduction_identifier_mismatch)
11404 << ReductionIdRange << RefExpr->getSourceRange();
11405 S.Diag(ParentSR.getBegin(),
11406 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000011407 << ParentSR
11408 << (IsParentBOK ? ParentBOKDSA.RefExpr
11409 : ParentReductionOpDSA.RefExpr)
11410 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000011411 continue;
11412 }
11413 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011414 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
11415 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000011416 }
11417
Alexey Bataev60da77e2016-02-29 05:54:20 +000011418 DeclRefExpr *Ref = nullptr;
11419 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011420 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000011421 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011422 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000011423 VarsExpr =
11424 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
11425 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000011426 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011427 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011428 }
Alexey Bataeve3727102018-04-18 15:57:46 +000011429 if (!S.isOpenMPCapturedDecl(D)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011430 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011431 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011432 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000011433 if (!RefRes.isUsable())
11434 continue;
11435 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011436 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
11437 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000011438 if (!PostUpdateRes.isUsable())
11439 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011440 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
11441 Stack->getCurrentDirective() == OMPD_taskgroup) {
11442 S.Diag(RefExpr->getExprLoc(),
11443 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000011444 << RefExpr->getSourceRange();
11445 continue;
11446 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011447 RD.ExprPostUpdates.emplace_back(
11448 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000011449 }
11450 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000011451 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000011452 // All reduction items are still marked as reduction (to do not increase
11453 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011454 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011455 if (CurrDir == OMPD_taskgroup) {
11456 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011457 Stack->addTaskgroupReductionData(D, ReductionIdRange,
11458 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000011459 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000011460 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000011461 }
Alexey Bataev88202be2017-07-27 13:20:36 +000011462 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
11463 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000011464 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011465 return RD.Vars.empty();
11466}
Alexey Bataevc5e02582014-06-16 07:08:35 +000011467
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011468OMPClause *Sema::ActOnOpenMPReductionClause(
11469 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11470 SourceLocation ColonLoc, SourceLocation EndLoc,
11471 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11472 ArrayRef<Expr *> UnresolvedReductions) {
11473 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011474 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011475 StartLoc, LParenLoc, ColonLoc, EndLoc,
11476 ReductionIdScopeSpec, ReductionId,
11477 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000011478 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000011479
Alexey Bataevc5e02582014-06-16 07:08:35 +000011480 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000011481 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11482 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11483 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11484 buildPreInits(Context, RD.ExprCaptures),
11485 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000011486}
11487
Alexey Bataev169d96a2017-07-18 20:17:46 +000011488OMPClause *Sema::ActOnOpenMPTaskReductionClause(
11489 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11490 SourceLocation ColonLoc, SourceLocation EndLoc,
11491 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11492 ArrayRef<Expr *> UnresolvedReductions) {
11493 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011494 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction, VarList,
11495 StartLoc, LParenLoc, ColonLoc, EndLoc,
11496 ReductionIdScopeSpec, ReductionId,
Alexey Bataev169d96a2017-07-18 20:17:46 +000011497 UnresolvedReductions, RD))
11498 return nullptr;
11499
11500 return OMPTaskReductionClause::Create(
11501 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11502 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
11503 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
11504 buildPreInits(Context, RD.ExprCaptures),
11505 buildPostUpdate(*this, RD.ExprPostUpdates));
11506}
11507
Alexey Bataevfa312f32017-07-21 18:48:21 +000011508OMPClause *Sema::ActOnOpenMPInReductionClause(
11509 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
11510 SourceLocation ColonLoc, SourceLocation EndLoc,
11511 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
11512 ArrayRef<Expr *> UnresolvedReductions) {
11513 ReductionData RD(VarList.size());
Alexey Bataeve3727102018-04-18 15:57:46 +000011514 if (actOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011515 StartLoc, LParenLoc, ColonLoc, EndLoc,
11516 ReductionIdScopeSpec, ReductionId,
11517 UnresolvedReductions, RD))
11518 return nullptr;
11519
11520 return OMPInReductionClause::Create(
11521 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
11522 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000011523 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000011524 buildPreInits(Context, RD.ExprCaptures),
11525 buildPostUpdate(*this, RD.ExprPostUpdates));
11526}
11527
Alexey Bataevecba70f2016-04-12 11:02:11 +000011528bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
11529 SourceLocation LinLoc) {
11530 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
11531 LinKind == OMPC_LINEAR_unknown) {
11532 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
11533 return true;
11534 }
11535 return false;
11536}
11537
Alexey Bataeve3727102018-04-18 15:57:46 +000011538bool Sema::CheckOpenMPLinearDecl(const ValueDecl *D, SourceLocation ELoc,
Alexey Bataevecba70f2016-04-12 11:02:11 +000011539 OpenMPLinearClauseKind LinKind,
11540 QualType Type) {
Alexey Bataeve3727102018-04-18 15:57:46 +000011541 const auto *VD = dyn_cast_or_null<VarDecl>(D);
Alexey Bataevecba70f2016-04-12 11:02:11 +000011542 // A variable must not have an incomplete type or a reference type.
11543 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
11544 return true;
11545 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
11546 !Type->isReferenceType()) {
11547 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
11548 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
11549 return true;
11550 }
11551 Type = Type.getNonReferenceType();
11552
Joel E. Dennybae586f2019-01-04 22:12:13 +000011553 // OpenMP 5.0 [2.19.3, List Item Privatization, Restrictions]
11554 // A variable that is privatized must not have a const-qualified type
11555 // unless it is of class type with a mutable member. This restriction does
11556 // not apply to the firstprivate clause.
11557 if (rejectConstNotMutableType(*this, D, Type, OMPC_linear, ELoc))
Alexey Bataevecba70f2016-04-12 11:02:11 +000011558 return true;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011559
11560 // A list item must be of integral or pointer type.
11561 Type = Type.getUnqualifiedType().getCanonicalType();
11562 const auto *Ty = Type.getTypePtrOrNull();
11563 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
11564 !Ty->isPointerType())) {
11565 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
11566 if (D) {
11567 bool IsDecl =
11568 !VD ||
11569 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
11570 Diag(D->getLocation(),
11571 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
11572 << D;
11573 }
11574 return true;
11575 }
11576 return false;
11577}
11578
Alexey Bataev182227b2015-08-20 10:54:39 +000011579OMPClause *Sema::ActOnOpenMPLinearClause(
11580 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
11581 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
11582 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000011583 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011584 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000011585 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000011586 SmallVector<Decl *, 4> ExprCaptures;
11587 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011588 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000011589 LinKind = OMPC_LINEAR_val;
Alexey Bataeve3727102018-04-18 15:57:46 +000011590 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000011591 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011592 SourceLocation ELoc;
11593 SourceRange ERange;
11594 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000011595 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011596 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000011597 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011598 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011599 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000011600 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000011601 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011602 ValueDecl *D = Res.first;
11603 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000011604 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000011605
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011606 QualType Type = D->getType();
11607 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000011608
11609 // OpenMP [2.14.3.7, linear clause]
11610 // A list-item cannot appear in more than one linear clause.
11611 // A list-item that appears in a linear clause cannot appear in any
11612 // other data-sharing attribute clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000011613 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexander Musman8dba6642014-04-22 13:09:42 +000011614 if (DVar.RefExpr) {
11615 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
11616 << getOpenMPClauseName(OMPC_linear);
Alexey Bataeve3727102018-04-18 15:57:46 +000011617 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000011618 continue;
11619 }
11620
Alexey Bataevecba70f2016-04-12 11:02:11 +000011621 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000011622 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000011623 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000011624
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011625 // Build private copy of original var.
Alexey Bataeve3727102018-04-18 15:57:46 +000011626 VarDecl *Private =
Alexey Bataev63cc8e92018-03-20 14:45:59 +000011627 buildVarDecl(*this, ELoc, Type, D->getName(),
11628 D->hasAttrs() ? &D->getAttrs() : nullptr,
11629 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000011630 DeclRefExpr *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000011631 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011632 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011633 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011634 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011635 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000011636 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011637 if (!isOpenMPCapturedDecl(D)) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000011638 ExprCaptures.push_back(Ref->getDecl());
11639 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
11640 ExprResult RefRes = DefaultLvalueConversion(Ref);
11641 if (!RefRes.isUsable())
11642 continue;
11643 ExprResult PostUpdateRes =
11644 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
11645 SimpleRefExpr, RefRes.get());
11646 if (!PostUpdateRes.isUsable())
11647 continue;
11648 ExprPostUpdates.push_back(
11649 IgnoredValueConversions(PostUpdateRes.get()).get());
11650 }
11651 }
11652 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011653 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011654 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011655 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011656 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011657 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000011658 /*DirectInit=*/false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011659 DeclRefExpr *InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000011660
11661 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000011662 Vars.push_back((VD || CurContext->isDependentContext())
11663 ? RefExpr->IgnoreParens()
11664 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011665 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000011666 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000011667 }
11668
11669 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011670 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000011671
11672 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000011673 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000011674 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
11675 !Step->isInstantiationDependent() &&
11676 !Step->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011677 SourceLocation StepLoc = Step->getBeginLoc();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000011678 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000011679 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000011680 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000011681 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000011682
Alexander Musman3276a272015-03-21 10:12:56 +000011683 // Build var to save the step value.
11684 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000011685 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000011686 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000011687 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000011688 ExprResult CalcStep =
11689 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011690 CalcStep = ActOnFinishFullExpr(CalcStep.get(), /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000011691
Alexander Musman8dba6642014-04-22 13:09:42 +000011692 // Warn about zero linear step (it would be probably better specified as
11693 // making corresponding variables 'const').
11694 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000011695 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
11696 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000011697 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
11698 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000011699 if (!IsConstant && CalcStep.isUsable()) {
11700 // Calculate the step beforehand instead of doing this on each iteration.
11701 // (This is not used if the number of iterations may be kfold-ed).
11702 CalcStepExpr = CalcStep.get();
11703 }
Alexander Musman8dba6642014-04-22 13:09:42 +000011704 }
11705
Alexey Bataev182227b2015-08-20 10:54:39 +000011706 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
11707 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000011708 StepExpr, CalcStepExpr,
11709 buildPreInits(Context, ExprCaptures),
11710 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000011711}
11712
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011713static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
11714 Expr *NumIterations, Sema &SemaRef,
11715 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000011716 // Walk the vars and build update/final expressions for the CodeGen.
11717 SmallVector<Expr *, 8> Updates;
11718 SmallVector<Expr *, 8> Finals;
11719 Expr *Step = Clause.getStep();
11720 Expr *CalcStep = Clause.getCalcStep();
11721 // OpenMP [2.14.3.7, linear clause]
11722 // If linear-step is not specified it is assumed to be 1.
Alexey Bataeve3727102018-04-18 15:57:46 +000011723 if (!Step)
Alexander Musman3276a272015-03-21 10:12:56 +000011724 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000011725 else if (CalcStep)
Alexander Musman3276a272015-03-21 10:12:56 +000011726 Step = cast<BinaryOperator>(CalcStep)->getLHS();
11727 bool HasErrors = false;
11728 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011729 auto CurPrivate = Clause.privates().begin();
Alexey Bataeve3727102018-04-18 15:57:46 +000011730 OpenMPLinearClauseKind LinKind = Clause.getModifier();
11731 for (Expr *RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011732 SourceLocation ELoc;
11733 SourceRange ERange;
11734 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000011735 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011736 ValueDecl *D = Res.first;
11737 if (Res.second || !D) {
11738 Updates.push_back(nullptr);
11739 Finals.push_back(nullptr);
11740 HasErrors = true;
11741 continue;
11742 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011743 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000011744 // OpenMP [2.15.11, distribute simd Construct]
11745 // A list item may not appear in a linear clause, unless it is the loop
11746 // iteration variable.
11747 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
11748 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
11749 SemaRef.Diag(ELoc,
11750 diag::err_omp_linear_distribute_var_non_loop_iteration);
11751 Updates.push_back(nullptr);
11752 Finals.push_back(nullptr);
11753 HasErrors = true;
11754 continue;
11755 }
Alexander Musman3276a272015-03-21 10:12:56 +000011756 Expr *InitExpr = *CurInit;
11757
11758 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000011759 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011760 Expr *CapturedRef;
11761 if (LinKind == OMPC_LINEAR_uval)
11762 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
11763 else
11764 CapturedRef =
11765 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
11766 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
11767 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011768
11769 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011770 ExprResult Update;
Alexey Bataeve3727102018-04-18 15:57:46 +000011771 if (!Info.first)
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011772 Update =
Alexey Bataeve3727102018-04-18 15:57:46 +000011773 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011774 InitExpr, IV, Step, /* Subtract */ false);
Alexey Bataeve3727102018-04-18 15:57:46 +000011775 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011776 Update = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011777 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011778 /*DiscardedValue*/ false);
Alexander Musman3276a272015-03-21 10:12:56 +000011779
11780 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011781 ExprResult Final;
Alexey Bataeve3727102018-04-18 15:57:46 +000011782 if (!Info.first)
11783 Final =
11784 buildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
11785 InitExpr, NumIterations, Step, /*Subtract=*/false);
11786 else
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011787 Final = *CurPrivate;
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011788 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getBeginLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011789 /*DiscardedValue*/ false);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011790
Alexander Musman3276a272015-03-21 10:12:56 +000011791 if (!Update.isUsable() || !Final.isUsable()) {
11792 Updates.push_back(nullptr);
11793 Finals.push_back(nullptr);
11794 HasErrors = true;
11795 } else {
11796 Updates.push_back(Update.get());
11797 Finals.push_back(Final.get());
11798 }
Richard Trieucc3949d2016-02-18 22:34:54 +000011799 ++CurInit;
11800 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000011801 }
11802 Clause.setUpdates(Updates);
11803 Clause.setFinals(Finals);
11804 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000011805}
11806
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011807OMPClause *Sema::ActOnOpenMPAlignedClause(
11808 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11809 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011810 SmallVector<Expr *, 8> Vars;
Alexey Bataeve3727102018-04-18 15:57:46 +000011811 for (Expr *RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000011812 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11813 SourceLocation ELoc;
11814 SourceRange ERange;
11815 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000011816 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev1efd1662016-03-29 10:59:56 +000011817 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011818 // It will be analyzed later.
11819 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011820 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000011821 ValueDecl *D = Res.first;
11822 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011823 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011824
Alexey Bataev1efd1662016-03-29 10:59:56 +000011825 QualType QType = D->getType();
11826 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011827
11828 // OpenMP [2.8.1, simd construct, Restrictions]
11829 // The type of list items appearing in the aligned clause must be
11830 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011831 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011832 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000011833 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011834 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011835 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011836 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000011837 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011838 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000011839 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011840 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011841 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011842 continue;
11843 }
11844
11845 // OpenMP [2.8.1, simd construct, Restrictions]
11846 // A list-item cannot appear in more than one aligned clause.
Alexey Bataeve3727102018-04-18 15:57:46 +000011847 if (const Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000011848 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011849 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11850 << getOpenMPClauseName(OMPC_aligned);
11851 continue;
11852 }
11853
Alexey Bataev1efd1662016-03-29 10:59:56 +000011854 DeclRefExpr *Ref = nullptr;
Alexey Bataeve3727102018-04-18 15:57:46 +000011855 if (!VD && isOpenMPCapturedDecl(D))
Alexey Bataev1efd1662016-03-29 10:59:56 +000011856 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11857 Vars.push_back(DefaultFunctionArrayConversion(
11858 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11859 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011860 }
11861
11862 // OpenMP [2.8.1, simd construct, Description]
11863 // The parameter of the aligned clause, alignment, must be a constant
11864 // positive integer expression.
11865 // If no optional parameter is specified, implementation-defined default
11866 // alignments for SIMD instructions on the target platforms are assumed.
11867 if (Alignment != nullptr) {
11868 ExprResult AlignResult =
11869 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
11870 if (AlignResult.isInvalid())
11871 return nullptr;
11872 Alignment = AlignResult.get();
11873 }
11874 if (Vars.empty())
11875 return nullptr;
11876
11877 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
11878 EndLoc, Vars, Alignment);
11879}
11880
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011881OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11882 SourceLocation StartLoc,
11883 SourceLocation LParenLoc,
11884 SourceLocation EndLoc) {
11885 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011886 SmallVector<Expr *, 8> SrcExprs;
11887 SmallVector<Expr *, 8> DstExprs;
11888 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000011889 for (Expr *RefExpr : VarList) {
Alexey Bataeved09d242014-05-28 05:53:51 +000011890 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
11891 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011892 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011893 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011894 SrcExprs.push_back(nullptr);
11895 DstExprs.push_back(nullptr);
11896 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011897 continue;
11898 }
11899
Alexey Bataeved09d242014-05-28 05:53:51 +000011900 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011901 // OpenMP [2.1, C/C++]
11902 // A list item is a variable name.
11903 // OpenMP [2.14.4.1, Restrictions, p.1]
11904 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeve3727102018-04-18 15:57:46 +000011905 auto *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011906 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011907 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
11908 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011909 continue;
11910 }
11911
11912 Decl *D = DE->getDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000011913 auto *VD = cast<VarDecl>(D);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011914
11915 QualType Type = VD->getType();
11916 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
11917 // It will be analyzed later.
11918 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011919 SrcExprs.push_back(nullptr);
11920 DstExprs.push_back(nullptr);
11921 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011922 continue;
11923 }
11924
11925 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
11926 // A list item that appears in a copyin clause must be threadprivate.
11927 if (!DSAStack->isThreadPrivate(VD)) {
11928 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000011929 << getOpenMPClauseName(OMPC_copyin)
11930 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011931 continue;
11932 }
11933
11934 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11935 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000011936 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011937 // operator for the class type.
Alexey Bataeve3727102018-04-18 15:57:46 +000011938 QualType ElemType = Context.getBaseElementType(Type).getNonReferenceType();
11939 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011940 buildVarDecl(*this, DE->getBeginLoc(), ElemType.getUnqualifiedType(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000011941 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000011942 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011943 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
Alexey Bataeve3727102018-04-18 15:57:46 +000011944 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000011945 buildVarDecl(*this, DE->getBeginLoc(), ElemType, ".copyin.dst",
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000011946 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000011947 DeclRefExpr *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011948 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011949 // For arrays generate assignment operation for single element and replace
11950 // it by the original array element in CodeGen.
Alexey Bataeve3727102018-04-18 15:57:46 +000011951 ExprResult AssignmentOp =
11952 BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign, PseudoDstExpr,
11953 PseudoSrcExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011954 if (AssignmentOp.isInvalid())
11955 continue;
11956 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000011957 /*DiscardedValue*/ false);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011958 if (AssignmentOp.isInvalid())
11959 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011960
11961 DSAStack->addDSA(VD, DE, OMPC_copyin);
11962 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011963 SrcExprs.push_back(PseudoSrcExpr);
11964 DstExprs.push_back(PseudoDstExpr);
11965 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011966 }
11967
Alexey Bataeved09d242014-05-28 05:53:51 +000011968 if (Vars.empty())
11969 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011970
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011971 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11972 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011973}
11974
Alexey Bataevbae9a792014-06-27 10:37:06 +000011975OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11976 SourceLocation StartLoc,
11977 SourceLocation LParenLoc,
11978 SourceLocation EndLoc) {
11979 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000011980 SmallVector<Expr *, 8> SrcExprs;
11981 SmallVector<Expr *, 8> DstExprs;
11982 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeve3727102018-04-18 15:57:46 +000011983 for (Expr *RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011984 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11985 SourceLocation ELoc;
11986 SourceRange ERange;
11987 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevbc529672018-09-28 19:33:14 +000011988 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataeve122da12016-03-17 10:50:17 +000011989 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011990 // It will be analyzed later.
11991 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011992 SrcExprs.push_back(nullptr);
11993 DstExprs.push_back(nullptr);
11994 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011995 }
Alexey Bataeve122da12016-03-17 10:50:17 +000011996 ValueDecl *D = Res.first;
11997 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000011998 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011999
Alexey Bataeve122da12016-03-17 10:50:17 +000012000 QualType Type = D->getType();
12001 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012002
12003 // OpenMP [2.14.4.2, Restrictions, p.2]
12004 // A list item that appears in a copyprivate clause may not appear in a
12005 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000012006 if (!VD || !DSAStack->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012007 DSAStackTy::DSAVarData DVar =
12008 DSAStack->getTopDSA(D, /*FromParent=*/false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012009 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
12010 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000012011 Diag(ELoc, diag::err_omp_wrong_dsa)
12012 << getOpenMPClauseName(DVar.CKind)
12013 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000012014 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012015 continue;
12016 }
12017
12018 // OpenMP [2.11.4.2, Restrictions, p.1]
12019 // All list items that appear in a copyprivate clause must be either
12020 // threadprivate or private in the enclosing context.
12021 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000012022 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012023 if (DVar.CKind == OMPC_shared) {
12024 Diag(ELoc, diag::err_omp_required_access)
12025 << getOpenMPClauseName(OMPC_copyprivate)
12026 << "threadprivate or private in the enclosing context";
Alexey Bataeve3727102018-04-18 15:57:46 +000012027 reportOriginalDsa(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012028 continue;
12029 }
12030 }
12031 }
12032
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012033 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000012034 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012035 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012036 << getOpenMPClauseName(OMPC_copyprivate) << Type
12037 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012038 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000012039 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012040 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000012041 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012042 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000012043 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000012044 continue;
12045 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000012046
Alexey Bataevbae9a792014-06-27 10:37:06 +000012047 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
12048 // A variable of class type (or array thereof) that appears in a
12049 // copyin clause requires an accessible, unambiguous copy assignment
12050 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000012051 Type = Context.getBaseElementType(Type.getNonReferenceType())
12052 .getUnqualifiedType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012053 VarDecl *SrcVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012054 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.src",
Alexey Bataeve122da12016-03-17 10:50:17 +000012055 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012056 DeclRefExpr *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
12057 VarDecl *DstVD =
Stephen Kellyf2ceec42018-08-09 21:08:08 +000012058 buildVarDecl(*this, RefExpr->getBeginLoc(), Type, ".copyprivate.dst",
Alexey Bataeve122da12016-03-17 10:50:17 +000012059 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataeve3727102018-04-18 15:57:46 +000012060 DeclRefExpr *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
12061 ExprResult AssignmentOp = BuildBinOp(
12062 DSAStack->getCurScope(), ELoc, BO_Assign, PseudoDstExpr, PseudoSrcExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012063 if (AssignmentOp.isInvalid())
12064 continue;
Aaron Ballmanfb6deeb2019-01-04 16:58:14 +000012065 AssignmentOp =
12066 ActOnFinishFullExpr(AssignmentOp.get(), ELoc, /*DiscardedValue*/ false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000012067 if (AssignmentOp.isInvalid())
12068 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000012069
12070 // No need to mark vars as copyprivate, they are already threadprivate or
12071 // implicitly private.
Alexey Bataeve3727102018-04-18 15:57:46 +000012072 assert(VD || isOpenMPCapturedDecl(D));
Alexey Bataeve122da12016-03-17 10:50:17 +000012073 Vars.push_back(
12074 VD ? RefExpr->IgnoreParens()
12075 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000012076 SrcExprs.push_back(PseudoSrcExpr);
12077 DstExprs.push_back(PseudoDstExpr);
12078 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000012079 }
12080
12081 if (Vars.empty())
12082 return nullptr;
12083
Alexey Bataeva63048e2015-03-23 06:18:07 +000012084 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12085 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000012086}
12087
Alexey Bataev6125da92014-07-21 11:26:11 +000012088OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
12089 SourceLocation StartLoc,
12090 SourceLocation LParenLoc,
12091 SourceLocation EndLoc) {
12092 if (VarList.empty())
12093 return nullptr;
12094
12095 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
12096}
Alexey Bataevdea47612014-07-23 07:46:59 +000012097
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012098OMPClause *
12099Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
12100 SourceLocation DepLoc, SourceLocation ColonLoc,
12101 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12102 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012103 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012104 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000012105 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012106 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000012107 return nullptr;
12108 }
12109 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012110 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
12111 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000012112 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012113 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000012114 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
12115 /*Last=*/OMPC_DEPEND_unknown, Except)
12116 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012117 return nullptr;
12118 }
12119 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000012120 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012121 llvm::APSInt DepCounter(/*BitWidth=*/32);
12122 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
Alexey Bataevf138fda2018-08-13 19:04:24 +000012123 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) {
12124 if (const Expr *OrderedCountExpr =
12125 DSAStack->getParentOrderedRegionParam().first) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012126 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
12127 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012128 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012129 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012130 for (Expr *RefExpr : VarList) {
Alexey Bataev17daedf2018-02-15 22:42:57 +000012131 assert(RefExpr && "NULL expr in OpenMP shared clause.");
12132 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
12133 // It will be analyzed later.
12134 Vars.push_back(RefExpr);
12135 continue;
12136 }
12137
12138 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataeve3727102018-04-18 15:57:46 +000012139 Expr *SimpleExpr = RefExpr->IgnoreParenCasts();
Alexey Bataev17daedf2018-02-15 22:42:57 +000012140 if (DepKind == OMPC_DEPEND_sink) {
Alexey Bataevf138fda2018-08-13 19:04:24 +000012141 if (DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012142 DepCounter >= TotalDepCount) {
12143 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
12144 continue;
12145 }
12146 ++DepCounter;
12147 // OpenMP [2.13.9, Summary]
12148 // depend(dependence-type : vec), where dependence-type is:
12149 // 'sink' and where vec is the iteration vector, which has the form:
12150 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
12151 // where n is the value specified by the ordered clause in the loop
12152 // directive, xi denotes the loop iteration variable of the i-th nested
12153 // loop associated with the loop directive, and di is a constant
12154 // non-negative integer.
12155 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012156 // It will be analyzed later.
12157 Vars.push_back(RefExpr);
12158 continue;
12159 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012160 SimpleExpr = SimpleExpr->IgnoreImplicit();
12161 OverloadedOperatorKind OOK = OO_None;
12162 SourceLocation OOLoc;
12163 Expr *LHS = SimpleExpr;
12164 Expr *RHS = nullptr;
12165 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
12166 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
12167 OOLoc = BO->getOperatorLoc();
12168 LHS = BO->getLHS()->IgnoreParenImpCasts();
12169 RHS = BO->getRHS()->IgnoreParenImpCasts();
12170 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
12171 OOK = OCE->getOperator();
12172 OOLoc = OCE->getOperatorLoc();
12173 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
12174 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
12175 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
12176 OOK = MCE->getMethodDecl()
12177 ->getNameInfo()
12178 .getName()
12179 .getCXXOverloadedOperator();
12180 OOLoc = MCE->getCallee()->getExprLoc();
12181 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
12182 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012183 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012184 SourceLocation ELoc;
12185 SourceRange ERange;
Alexey Bataevbc529672018-09-28 19:33:14 +000012186 auto Res = getPrivateItem(*this, LHS, ELoc, ERange);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012187 if (Res.second) {
12188 // It will be analyzed later.
12189 Vars.push_back(RefExpr);
12190 }
12191 ValueDecl *D = Res.first;
12192 if (!D)
12193 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012194
Alexey Bataev17daedf2018-02-15 22:42:57 +000012195 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
12196 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
12197 continue;
12198 }
12199 if (RHS) {
12200 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
12201 RHS, OMPC_depend, /*StrictlyPositive=*/false);
12202 if (RHSRes.isInvalid())
12203 continue;
12204 }
12205 if (!CurContext->isDependentContext() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012206 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012207 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012208 const ValueDecl *VD =
Alexey Bataev17daedf2018-02-15 22:42:57 +000012209 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
Alexey Bataeve3727102018-04-18 15:57:46 +000012210 if (VD)
Alexey Bataev17daedf2018-02-15 22:42:57 +000012211 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
12212 << 1 << VD;
Alexey Bataeve3727102018-04-18 15:57:46 +000012213 else
Alexey Bataev17daedf2018-02-15 22:42:57 +000012214 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
Alexey Bataev17daedf2018-02-15 22:42:57 +000012215 continue;
12216 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012217 OpsOffs.emplace_back(RHS, OOK);
Alexey Bataev17daedf2018-02-15 22:42:57 +000012218 } else {
12219 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
12220 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
12221 (ASE &&
12222 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
12223 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
12224 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12225 << RefExpr->getSourceRange();
12226 continue;
12227 }
12228 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
12229 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
12230 ExprResult Res =
12231 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
12232 getDiagnostics().setSuppressAllDiagnostics(Suppress);
12233 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
12234 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
12235 << RefExpr->getSourceRange();
12236 continue;
12237 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012238 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012239 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000012240 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000012241
12242 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
12243 TotalDepCount > VarList.size() &&
Alexey Bataevf138fda2018-08-13 19:04:24 +000012244 DSAStack->getParentOrderedRegionParam().first &&
Alexey Bataev17daedf2018-02-15 22:42:57 +000012245 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
12246 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
12247 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
12248 }
12249 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
12250 Vars.empty())
12251 return nullptr;
12252
Alexey Bataev8b427062016-05-25 12:36:08 +000012253 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataevf138fda2018-08-13 19:04:24 +000012254 DepKind, DepLoc, ColonLoc, Vars,
12255 TotalDepCount.getZExtValue());
Alexey Bataev17daedf2018-02-15 22:42:57 +000012256 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
12257 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000012258 DSAStack->addDoacrossDependClause(C, OpsOffs);
12259 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000012260}
Michael Wonge710d542015-08-07 16:16:36 +000012261
12262OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
12263 SourceLocation LParenLoc,
12264 SourceLocation EndLoc) {
12265 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012266 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000012267
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012268 // OpenMP [2.9.1, Restrictions]
12269 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000012270 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
Alexey Bataeva0569352015-12-01 10:17:31 +000012271 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012272 return nullptr;
12273
Alexey Bataev931e19b2017-10-02 16:32:39 +000012274 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012275 OpenMPDirectiveKind CaptureRegion =
12276 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
12277 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012278 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000012279 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev931e19b2017-10-02 16:32:39 +000012280 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12281 HelperValStmt = buildPreInits(Context, Captures);
12282 }
12283
Alexey Bataev8451efa2018-01-15 19:06:12 +000012284 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
12285 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000012286}
Kelvin Li0bff7af2015-11-23 05:32:03 +000012287
Alexey Bataeve3727102018-04-18 15:57:46 +000012288static bool checkTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000012289 DSAStackTy *Stack, QualType QTy,
12290 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000012291 NamedDecl *ND;
12292 if (QTy->isIncompleteType(&ND)) {
12293 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
12294 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012295 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000012296 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
12297 !QTy.isTrivialType(SemaRef.Context))
12298 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012299 return true;
12300}
12301
Adrian Prantl9fc8faf2018-05-09 01:00:01 +000012302/// Return true if it can be proven that the provided array expression
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012303/// (array section or array subscript) does NOT specify the whole size of the
12304/// array whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012305static bool checkArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012306 const Expr *E,
12307 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012308 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012309
12310 // If this is an array subscript, it refers to the whole size if the size of
12311 // the dimension is constant and equals 1. Also, an array section assumes the
12312 // format of an array subscript if no colon is used.
12313 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012314 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012315 return ATy->getSize().getSExtValue() != 1;
12316 // Size can't be evaluated statically.
12317 return false;
12318 }
12319
12320 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012321 const Expr *LowerBound = OASE->getLowerBound();
12322 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012323
12324 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000012325 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012326 if (LowerBound) {
Fangrui Song407659a2018-11-30 23:41:18 +000012327 Expr::EvalResult Result;
12328 if (!LowerBound->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012329 return false; // Can't get the integer value as a constant.
Fangrui Song407659a2018-11-30 23:41:18 +000012330
12331 llvm::APSInt ConstLowerBound = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012332 if (ConstLowerBound.getSExtValue())
12333 return true;
12334 }
12335
12336 // If we don't have a length we covering the whole dimension.
12337 if (!Length)
12338 return false;
12339
12340 // If the base is a pointer, we don't have a way to get the size of the
12341 // pointee.
12342 if (BaseQTy->isPointerType())
12343 return false;
12344
12345 // We can only check if the length is the same as the size of the dimension
12346 // if we have a constant array.
Alexey Bataeve3727102018-04-18 15:57:46 +000012347 const auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012348 if (!CATy)
12349 return false;
12350
Fangrui Song407659a2018-11-30 23:41:18 +000012351 Expr::EvalResult Result;
12352 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012353 return false; // Can't get the integer value as a constant.
12354
Fangrui Song407659a2018-11-30 23:41:18 +000012355 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012356 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
12357}
12358
12359// Return true if it can be proven that the provided array expression (array
12360// section or array subscript) does NOT specify a single element of the array
12361// whose base type is \a BaseQTy.
Alexey Bataeve3727102018-04-18 15:57:46 +000012362static bool checkArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000012363 const Expr *E,
12364 QualType BaseQTy) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012365 const auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012366
12367 // An array subscript always refer to a single element. Also, an array section
12368 // assumes the format of an array subscript if no colon is used.
12369 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
12370 return false;
12371
12372 assert(OASE && "Expecting array section if not an array subscript.");
Alexey Bataeve3727102018-04-18 15:57:46 +000012373 const Expr *Length = OASE->getLength();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012374
12375 // If we don't have a length we have to check if the array has unitary size
12376 // for this dimension. Also, we should always expect a length if the base type
12377 // is pointer.
12378 if (!Length) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012379 if (const auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012380 return ATy->getSize().getSExtValue() != 1;
12381 // We cannot assume anything.
12382 return false;
12383 }
12384
12385 // Check if the length evaluates to 1.
Fangrui Song407659a2018-11-30 23:41:18 +000012386 Expr::EvalResult Result;
12387 if (!Length->EvaluateAsInt(Result, SemaRef.getASTContext()))
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012388 return false; // Can't get the integer value as a constant.
12389
Fangrui Song407659a2018-11-30 23:41:18 +000012390 llvm::APSInt ConstLength = Result.Val.getInt();
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012391 return ConstLength.getSExtValue() != 1;
12392}
12393
Samuel Antao661c0902016-05-26 17:39:58 +000012394// Return the expression of the base of the mappable expression or null if it
12395// cannot be determined and do all the necessary checks to see if the expression
12396// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000012397// components of the expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000012398static const Expr *checkMapClauseExpressionBase(
Samuel Antao90927002016-04-26 14:54:23 +000012399 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000012400 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012401 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012402 SourceLocation ELoc = E->getExprLoc();
12403 SourceRange ERange = E->getSourceRange();
12404
12405 // The base of elements of list in a map clause have to be either:
12406 // - a reference to variable or field.
12407 // - a member expression.
12408 // - an array expression.
12409 //
12410 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
12411 // reference to 'r'.
12412 //
12413 // If we have:
12414 //
12415 // struct SS {
12416 // Bla S;
12417 // foo() {
12418 // #pragma omp target map (S.Arr[:12]);
12419 // }
12420 // }
12421 //
12422 // We want to retrieve the member expression 'this->S';
12423
Alexey Bataeve3727102018-04-18 15:57:46 +000012424 const Expr *RelevantExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012425
Samuel Antao5de996e2016-01-22 20:21:36 +000012426 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
12427 // If a list item is an array section, it must specify contiguous storage.
12428 //
12429 // For this restriction it is sufficient that we make sure only references
12430 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012431 // exist except in the rightmost expression (unless they cover the whole
12432 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000012433 //
12434 // r.ArrS[3:5].Arr[6:7]
12435 //
12436 // r.ArrS[3:5].x
12437 //
12438 // but these would be valid:
12439 // r.ArrS[3].Arr[6:7]
12440 //
12441 // r.ArrS[3].x
12442
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012443 bool AllowUnitySizeArraySection = true;
12444 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012445
Dmitry Polukhin644a9252016-03-11 07:58:34 +000012446 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012447 E = E->IgnoreParenImpCasts();
12448
12449 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
12450 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000012451 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012452
12453 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012454
12455 // If we got a reference to a declaration, we should not expect any array
12456 // section before that.
12457 AllowUnitySizeArraySection = false;
12458 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012459
12460 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012461 CurComponents.emplace_back(CurE, CurE->getDecl());
12462 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012463 Expr *BaseE = CurE->getBase()->IgnoreParenImpCasts();
Samuel Antao5de996e2016-01-22 20:21:36 +000012464
12465 if (isa<CXXThisExpr>(BaseE))
12466 // We found a base expression: this->Val.
12467 RelevantExpr = CurE;
12468 else
12469 E = BaseE;
12470
12471 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012472 if (!NoDiagnose) {
12473 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
12474 << CurE->getSourceRange();
12475 return nullptr;
12476 }
12477 if (RelevantExpr)
12478 return nullptr;
12479 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012480 }
12481
12482 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
12483
12484 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
12485 // A bit-field cannot appear in a map clause.
12486 //
12487 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012488 if (!NoDiagnose) {
12489 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
12490 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
12491 return nullptr;
12492 }
12493 if (RelevantExpr)
12494 return nullptr;
12495 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012496 }
12497
12498 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12499 // If the type of a list item is a reference to a type T then the type
12500 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012501 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012502
12503 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
12504 // A list item cannot be a variable that is a member of a structure with
12505 // a union type.
12506 //
Alexey Bataeve3727102018-04-18 15:57:46 +000012507 if (CurType->isUnionType()) {
12508 if (!NoDiagnose) {
12509 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
12510 << CurE->getSourceRange();
12511 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012512 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012513 continue;
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012514 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012515
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012516 // If we got a member expression, we should not expect any array section
12517 // before that:
12518 //
12519 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
12520 // If a list item is an element of a structure, only the rightmost symbol
12521 // of the variable reference can be an array section.
12522 //
12523 AllowUnitySizeArraySection = false;
12524 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012525
12526 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012527 CurComponents.emplace_back(CurE, FD);
12528 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012529 E = CurE->getBase()->IgnoreParenImpCasts();
12530
12531 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012532 if (!NoDiagnose) {
12533 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12534 << 0 << CurE->getSourceRange();
12535 return nullptr;
12536 }
12537 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000012538 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012539
12540 // If we got an array subscript that express the whole dimension we
12541 // can have any array expressions before. If it only expressing part of
12542 // the dimension, we can only have unitary-size array expressions.
Alexey Bataeve3727102018-04-18 15:57:46 +000012543 if (checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012544 E->getType()))
12545 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000012546
Patrick Lystere13b1e32019-01-02 19:28:48 +000012547 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12548 Expr::EvalResult Result;
12549 if (CurE->getIdx()->EvaluateAsInt(Result, SemaRef.getASTContext())) {
12550 if (!Result.Val.getInt().isNullValue()) {
12551 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12552 diag::err_omp_invalid_map_this_expr);
12553 SemaRef.Diag(CurE->getIdx()->getExprLoc(),
12554 diag::note_omp_invalid_subscript_on_this_ptr_map);
12555 }
12556 }
12557 RelevantExpr = TE;
12558 }
12559
Samuel Antao90927002016-04-26 14:54:23 +000012560 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012561 CurComponents.emplace_back(CurE, nullptr);
12562 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012563 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000012564 E = CurE->getBase()->IgnoreParenImpCasts();
12565
Alexey Bataev27041fa2017-12-05 15:22:49 +000012566 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012567 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12568
Samuel Antao5de996e2016-01-22 20:21:36 +000012569 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12570 // If the type of a list item is a reference to a type T then the type
12571 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000012572 if (CurType->isReferenceType())
12573 CurType = CurType->getPointeeType();
12574
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012575 bool IsPointer = CurType->isAnyPointerType();
12576
12577 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012578 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
12579 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000012580 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012581 }
12582
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012583 bool NotWhole =
Alexey Bataeve3727102018-04-18 15:57:46 +000012584 checkArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012585 bool NotUnity =
Alexey Bataeve3727102018-04-18 15:57:46 +000012586 checkArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012587
Samuel Antaodab51bb2016-07-18 23:22:11 +000012588 if (AllowWholeSizeArraySection) {
12589 // Any array section is currently allowed. Allowing a whole size array
12590 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012591 //
12592 // If this array section refers to the whole dimension we can still
12593 // accept other array sections before this one, except if the base is a
12594 // pointer. Otherwise, only unitary sections are accepted.
12595 if (NotWhole || IsPointer)
12596 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000012597 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012598 // A unity or whole array section is not allowed and that is not
12599 // compatible with the properties of the current array section.
12600 SemaRef.Diag(
12601 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
12602 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000012603 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000012604 }
Samuel Antao90927002016-04-26 14:54:23 +000012605
Patrick Lystere13b1e32019-01-02 19:28:48 +000012606 if (const auto *TE = dyn_cast<CXXThisExpr>(E)) {
12607 Expr::EvalResult ResultR;
12608 Expr::EvalResult ResultL;
12609 if (CurE->getLength()->EvaluateAsInt(ResultR,
12610 SemaRef.getASTContext())) {
12611 if (!ResultR.Val.getInt().isOneValue()) {
12612 SemaRef.Diag(CurE->getLength()->getExprLoc(),
12613 diag::err_omp_invalid_map_this_expr);
12614 SemaRef.Diag(CurE->getLength()->getExprLoc(),
12615 diag::note_omp_invalid_length_on_this_ptr_mapping);
12616 }
12617 }
12618 if (CurE->getLowerBound() && CurE->getLowerBound()->EvaluateAsInt(
12619 ResultL, SemaRef.getASTContext())) {
12620 if (!ResultL.Val.getInt().isNullValue()) {
12621 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
12622 diag::err_omp_invalid_map_this_expr);
12623 SemaRef.Diag(CurE->getLowerBound()->getExprLoc(),
12624 diag::note_omp_invalid_lower_bound_on_this_ptr_mapping);
12625 }
12626 }
12627 RelevantExpr = TE;
12628 }
12629
Samuel Antao90927002016-04-26 14:54:23 +000012630 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000012631 CurComponents.emplace_back(CurE, nullptr);
12632 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012633 if (!NoDiagnose) {
12634 // If nothing else worked, this is not a valid map clause expression.
12635 SemaRef.Diag(
12636 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
12637 << ERange;
12638 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000012639 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012640 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012641 }
12642
12643 return RelevantExpr;
12644}
12645
12646// Return true if expression E associated with value VD has conflicts with other
12647// map information.
Alexey Bataeve3727102018-04-18 15:57:46 +000012648static bool checkMapConflicts(
12649 Sema &SemaRef, DSAStackTy *DSAS, const ValueDecl *VD, const Expr *E,
Samuel Antao90927002016-04-26 14:54:23 +000012650 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000012651 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
12652 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012653 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000012654 SourceLocation ELoc = E->getExprLoc();
12655 SourceRange ERange = E->getSourceRange();
12656
12657 // In order to easily check the conflicts we need to match each component of
12658 // the expression under test with the components of the expressions that are
12659 // already in the stack.
12660
Samuel Antao5de996e2016-01-22 20:21:36 +000012661 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000012662 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000012663 "Map clause expression with unexpected base!");
12664
12665 // Variables to help detecting enclosing problems in data environment nests.
12666 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000012667 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000012668
Samuel Antao90927002016-04-26 14:54:23 +000012669 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
12670 VD, CurrentRegionOnly,
Alexey Bataeve3727102018-04-18 15:57:46 +000012671 [&IsEnclosedByDataEnvironmentExpr, &SemaRef, VD, CurrentRegionOnly, ELoc,
12672 ERange, CKind, &EnclosingExpr,
12673 CurComponents](OMPClauseMappableExprCommon::MappableExprComponentListRef
12674 StackComponents,
12675 OpenMPClauseKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012676 assert(!StackComponents.empty() &&
12677 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000012678 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000012679 "Map clause expression with unexpected base!");
Fangrui Song16fe49a2018-04-18 19:32:01 +000012680 (void)VD;
Samuel Antao5de996e2016-01-22 20:21:36 +000012681
Samuel Antao90927002016-04-26 14:54:23 +000012682 // The whole expression in the stack.
Alexey Bataeve3727102018-04-18 15:57:46 +000012683 const Expr *RE = StackComponents.front().getAssociatedExpression();
Samuel Antao90927002016-04-26 14:54:23 +000012684
Samuel Antao5de996e2016-01-22 20:21:36 +000012685 // Expressions must start from the same base. Here we detect at which
12686 // point both expressions diverge from each other and see if we can
12687 // detect if the memory referred to both expressions is contiguous and
12688 // do not overlap.
12689 auto CI = CurComponents.rbegin();
12690 auto CE = CurComponents.rend();
12691 auto SI = StackComponents.rbegin();
12692 auto SE = StackComponents.rend();
12693 for (; CI != CE && SI != SE; ++CI, ++SI) {
12694
12695 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
12696 // At most one list item can be an array item derived from a given
12697 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000012698 if (CurrentRegionOnly &&
12699 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
12700 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
12701 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
12702 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
12703 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000012704 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000012705 << CI->getAssociatedExpression()->getSourceRange();
12706 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
12707 diag::note_used_here)
12708 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000012709 return true;
12710 }
12711
12712 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000012713 if (CI->getAssociatedExpression()->getStmtClass() !=
12714 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000012715 break;
12716
12717 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000012718 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000012719 break;
12720 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000012721 // Check if the extra components of the expressions in the enclosing
12722 // data environment are redundant for the current base declaration.
12723 // If they are, the maps completely overlap, which is legal.
12724 for (; SI != SE; ++SI) {
12725 QualType Type;
Alexey Bataeve3727102018-04-18 15:57:46 +000012726 if (const auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000012727 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000012728 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
Alexey Bataeve3727102018-04-18 15:57:46 +000012729 } else if (const auto *OASE = dyn_cast<OMPArraySectionExpr>(
David Majnemer9d168222016-08-05 17:44:54 +000012730 SI->getAssociatedExpression())) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012731 const Expr *E = OASE->getBase()->IgnoreParenImpCasts();
Kelvin Li9f645ae2016-07-18 22:49:16 +000012732 Type =
12733 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
12734 }
12735 if (Type.isNull() || Type->isAnyPointerType() ||
Alexey Bataeve3727102018-04-18 15:57:46 +000012736 checkArrayExpressionDoesNotReferToWholeSize(
Kelvin Li9f645ae2016-07-18 22:49:16 +000012737 SemaRef, SI->getAssociatedExpression(), Type))
12738 break;
12739 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012740
12741 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12742 // List items of map clauses in the same construct must not share
12743 // original storage.
12744 //
12745 // If the expressions are exactly the same or one is a subset of the
12746 // other, it means they are sharing storage.
12747 if (CI == CE && SI == SE) {
12748 if (CurrentRegionOnly) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012749 if (CKind == OMPC_map) {
Samuel Antao661c0902016-05-26 17:39:58 +000012750 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000012751 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012752 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012753 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12754 << ERange;
12755 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012756 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12757 << RE->getSourceRange();
12758 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012759 }
Alexey Bataeve3727102018-04-18 15:57:46 +000012760 // If we find the same expression in the enclosing data environment,
12761 // that is legal.
12762 IsEnclosedByDataEnvironmentExpr = true;
12763 return false;
Samuel Antao5de996e2016-01-22 20:21:36 +000012764 }
12765
Samuel Antao90927002016-04-26 14:54:23 +000012766 QualType DerivedType =
12767 std::prev(CI)->getAssociatedDeclaration()->getType();
12768 SourceLocation DerivedLoc =
12769 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000012770
12771 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12772 // If the type of a list item is a reference to a type T then the type
12773 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000012774 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012775
12776 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
12777 // A variable for which the type is pointer and an array section
12778 // derived from that variable must not appear as list items of map
12779 // clauses of the same construct.
12780 //
12781 // Also, cover one of the cases in:
12782 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12783 // If any part of the original storage of a list item has corresponding
12784 // storage in the device data environment, all of the original storage
12785 // must have corresponding storage in the device data environment.
12786 //
12787 if (DerivedType->isAnyPointerType()) {
12788 if (CI == CE || SI == SE) {
12789 SemaRef.Diag(
12790 DerivedLoc,
12791 diag::err_omp_pointer_mapped_along_with_derived_section)
12792 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012793 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12794 << RE->getSourceRange();
12795 return true;
Alexey Bataeve3727102018-04-18 15:57:46 +000012796 }
12797 if (CI->getAssociatedExpression()->getStmtClass() !=
Alexey Bataev2819260b2018-02-27 17:42:00 +000012798 SI->getAssociatedExpression()->getStmtClass() ||
12799 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
12800 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012801 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000012802 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000012803 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012804 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12805 << RE->getSourceRange();
12806 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012807 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012808 }
12809
12810 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12811 // List items of map clauses in the same construct must not share
12812 // original storage.
12813 //
12814 // An expression is a subset of the other.
12815 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012816 if (CKind == OMPC_map) {
Alexey Bataeve82445f2018-09-20 13:54:02 +000012817 if (CI != CE || SI != SE) {
12818 // Allow constructs like this: map(s, s.ptr[0:1]), where s.ptr is
12819 // a pointer.
12820 auto Begin =
12821 CI != CE ? CurComponents.begin() : StackComponents.begin();
12822 auto End = CI != CE ? CurComponents.end() : StackComponents.end();
12823 auto It = Begin;
12824 while (It != End && !It->getAssociatedDeclaration())
12825 std::advance(It, 1);
12826 assert(It != End &&
12827 "Expected at least one component with the declaration.");
12828 if (It != Begin && It->getAssociatedDeclaration()
12829 ->getType()
12830 .getCanonicalType()
12831 ->isAnyPointerType()) {
12832 IsEnclosedByDataEnvironmentExpr = false;
12833 EnclosingExpr = nullptr;
12834 return false;
12835 }
12836 }
Samuel Antao661c0902016-05-26 17:39:58 +000012837 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
Alexey Bataeve3727102018-04-18 15:57:46 +000012838 } else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012839 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012840 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12841 << ERange;
12842 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012843 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12844 << RE->getSourceRange();
12845 return true;
12846 }
12847
12848 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000012849 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000012850 if (!CurrentRegionOnly && SI != SE)
12851 EnclosingExpr = RE;
12852
12853 // The current expression is a subset of the expression in the data
12854 // environment.
12855 IsEnclosedByDataEnvironmentExpr |=
12856 (!CurrentRegionOnly && CI != CE && SI == SE);
12857
12858 return false;
12859 });
12860
12861 if (CurrentRegionOnly)
12862 return FoundError;
12863
12864 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12865 // If any part of the original storage of a list item has corresponding
12866 // storage in the device data environment, all of the original storage must
12867 // have corresponding storage in the device data environment.
12868 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
12869 // If a list item is an element of a structure, and a different element of
12870 // the structure has a corresponding list item in the device data environment
12871 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000012872 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000012873 // data environment prior to the task encountering the construct.
12874 //
12875 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
12876 SemaRef.Diag(ELoc,
12877 diag::err_omp_original_storage_is_shared_and_does_not_contain)
12878 << ERange;
12879 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
12880 << EnclosingExpr->getSourceRange();
12881 return true;
12882 }
12883
12884 return FoundError;
12885}
12886
Samuel Antao661c0902016-05-26 17:39:58 +000012887namespace {
12888// Utility struct that gathers all the related lists associated with a mappable
12889// expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000012890struct MappableVarListInfo {
Samuel Antao661c0902016-05-26 17:39:58 +000012891 // The list of expressions.
12892 ArrayRef<Expr *> VarList;
12893 // The list of processed expressions.
12894 SmallVector<Expr *, 16> ProcessedVarList;
12895 // The mappble components for each expression.
12896 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
12897 // The base declaration of the variable.
12898 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
12899
12900 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
12901 // We have a list of components and base declarations for each entry in the
12902 // variable list.
12903 VarComponents.reserve(VarList.size());
12904 VarBaseDeclarations.reserve(VarList.size());
12905 }
12906};
12907}
12908
12909// Check the validity of the provided variable list for the provided clause kind
12910// \a CKind. In the check process the valid expressions, and mappable expression
12911// components and variables are extracted and used to fill \a Vars,
12912// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
12913// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
12914static void
12915checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
12916 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
12917 SourceLocation StartLoc,
12918 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
12919 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000012920 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
12921 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000012922 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012923
Samuel Antao90927002016-04-26 14:54:23 +000012924 // Keep track of the mappable components and base declarations in this clause.
12925 // Each entry in the list is going to have a list of components associated. We
12926 // record each set of the components so that we can build the clause later on.
12927 // In the end we should have the same amount of declarations and component
12928 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000012929
Alexey Bataeve3727102018-04-18 15:57:46 +000012930 for (Expr *RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000012931 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012932 SourceLocation ELoc = RE->getExprLoc();
12933
Alexey Bataeve3727102018-04-18 15:57:46 +000012934 const Expr *VE = RE->IgnoreParenLValueCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012935
12936 if (VE->isValueDependent() || VE->isTypeDependent() ||
12937 VE->isInstantiationDependent() ||
12938 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012939 // We can only analyze this information once the missing information is
12940 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000012941 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012942 continue;
12943 }
12944
Alexey Bataeve3727102018-04-18 15:57:46 +000012945 Expr *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012946
Samuel Antao5de996e2016-01-22 20:21:36 +000012947 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000012948 SemaRef.Diag(ELoc,
12949 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000012950 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012951 continue;
12952 }
12953
Samuel Antao90927002016-04-26 14:54:23 +000012954 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
12955 ValueDecl *CurDeclaration = nullptr;
12956
12957 // Obtain the array or member expression bases if required. Also, fill the
12958 // components array with all the components identified in the process.
Alexey Bataeve3727102018-04-18 15:57:46 +000012959 const Expr *BE = checkMapClauseExpressionBase(
12960 SemaRef, SimpleExpr, CurComponents, CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000012961 if (!BE)
12962 continue;
12963
Samuel Antao90927002016-04-26 14:54:23 +000012964 assert(!CurComponents.empty() &&
12965 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012966
Patrick Lystere13b1e32019-01-02 19:28:48 +000012967 if (const auto *TE = dyn_cast<CXXThisExpr>(BE)) {
12968 // Add store "this" pointer to class in DSAStackTy for future checking
12969 DSAS->addMappedClassesQualTypes(TE->getType());
12970 // Skip restriction checking for variable or field declarations
12971 MVLI.ProcessedVarList.push_back(RE);
12972 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12973 MVLI.VarComponents.back().append(CurComponents.begin(),
12974 CurComponents.end());
12975 MVLI.VarBaseDeclarations.push_back(nullptr);
12976 continue;
12977 }
12978
Samuel Antao90927002016-04-26 14:54:23 +000012979 // For the following checks, we rely on the base declaration which is
12980 // expected to be associated with the last component. The declaration is
12981 // expected to be a variable or a field (if 'this' is being mapped).
12982 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
12983 assert(CurDeclaration && "Null decl on map clause.");
12984 assert(
12985 CurDeclaration->isCanonicalDecl() &&
12986 "Expecting components to have associated only canonical declarations.");
12987
12988 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
Alexey Bataeve3727102018-04-18 15:57:46 +000012989 const auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000012990
12991 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000012992 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000012993
12994 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000012995 // threadprivate variables cannot appear in a map clause.
12996 // OpenMP 4.5 [2.10.5, target update Construct]
12997 // threadprivate variables cannot appear in a from clause.
12998 if (VD && DSAS->isThreadPrivate(VD)) {
Alexey Bataeve3727102018-04-18 15:57:46 +000012999 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013000 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
13001 << getOpenMPClauseName(CKind);
Alexey Bataeve3727102018-04-18 15:57:46 +000013002 reportOriginalDsa(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013003 continue;
13004 }
13005
Samuel Antao5de996e2016-01-22 20:21:36 +000013006 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
13007 // A list item cannot appear in both a map clause and a data-sharing
13008 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000013009
Samuel Antao5de996e2016-01-22 20:21:36 +000013010 // Check conflicts with other map clause expressions. We check the conflicts
13011 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000013012 // environment, because the restrictions are different. We only have to
13013 // check conflicts across regions for the map clauses.
Alexey Bataeve3727102018-04-18 15:57:46 +000013014 if (checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013015 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013016 break;
Samuel Antao661c0902016-05-26 17:39:58 +000013017 if (CKind == OMPC_map &&
Alexey Bataeve3727102018-04-18 15:57:46 +000013018 checkMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
Samuel Antao661c0902016-05-26 17:39:58 +000013019 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000013020 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000013021
Samuel Antao661c0902016-05-26 17:39:58 +000013022 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000013023 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
13024 // If the type of a list item is a reference to a type T then the type will
13025 // be considered to be T for all purposes of this clause.
Alexey Bataev354df2e2018-05-02 18:44:10 +000013026 auto I = llvm::find_if(
13027 CurComponents,
13028 [](const OMPClauseMappableExprCommon::MappableComponent &MC) {
13029 return MC.getAssociatedDeclaration();
13030 });
13031 assert(I != CurComponents.end() && "Null decl on map clause.");
13032 QualType Type =
13033 I->getAssociatedDeclaration()->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000013034
Samuel Antao661c0902016-05-26 17:39:58 +000013035 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
13036 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000013037 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000013038 // A list item must have a mappable type.
Alexey Bataeve3727102018-04-18 15:57:46 +000013039 if (!checkTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
Samuel Antao661c0902016-05-26 17:39:58 +000013040 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000013041 continue;
13042
Samuel Antao661c0902016-05-26 17:39:58 +000013043 if (CKind == OMPC_map) {
13044 // target enter data
13045 // OpenMP [2.10.2, Restrictions, p. 99]
13046 // A map-type must be specified in all map clauses and must be either
13047 // to or alloc.
13048 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
13049 if (DKind == OMPD_target_enter_data &&
13050 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
13051 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13052 << (IsMapTypeImplicit ? 1 : 0)
13053 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13054 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013055 continue;
13056 }
Samuel Antao661c0902016-05-26 17:39:58 +000013057
13058 // target exit_data
13059 // OpenMP [2.10.3, Restrictions, p. 102]
13060 // A map-type must be specified in all map clauses and must be either
13061 // from, release, or delete.
13062 if (DKind == OMPD_target_exit_data &&
13063 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
13064 MapType == OMPC_MAP_delete)) {
13065 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
13066 << (IsMapTypeImplicit ? 1 : 0)
13067 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
13068 << getOpenMPDirectiveName(DKind);
13069 continue;
13070 }
13071
13072 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
13073 // A list item cannot appear in both a map clause and a data-sharing
13074 // attribute clause on the same construct
Alexey Bataeve3727102018-04-18 15:57:46 +000013075 if (VD && isOpenMPTargetExecutionDirective(DKind)) {
13076 DSAStackTy::DSAVarData DVar = DSAS->getTopDSA(VD, /*FromParent=*/false);
Samuel Antao661c0902016-05-26 17:39:58 +000013077 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000013078 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000013079 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000013080 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000013081 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000013082 reportOriginalDsa(SemaRef, DSAS, CurDeclaration, DVar);
Samuel Antao661c0902016-05-26 17:39:58 +000013083 continue;
13084 }
13085 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000013086 }
13087
Samuel Antao90927002016-04-26 14:54:23 +000013088 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000013089 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000013090
13091 // Store the components in the stack so that they can be used to check
13092 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000013093 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
13094 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000013095
13096 // Save the components and declaration to create the clause. For purposes of
13097 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000013098 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000013099 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13100 MVLI.VarComponents.back().append(CurComponents.begin(),
13101 CurComponents.end());
13102 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
13103 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013104 }
Samuel Antao661c0902016-05-26 17:39:58 +000013105}
13106
13107OMPClause *
Kelvin Lief579432018-12-18 22:18:41 +000013108Sema::ActOnOpenMPMapClause(ArrayRef<OpenMPMapModifierKind> MapTypeModifiers,
13109 ArrayRef<SourceLocation> MapTypeModifiersLoc,
Samuel Antao661c0902016-05-26 17:39:58 +000013110 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
13111 SourceLocation MapLoc, SourceLocation ColonLoc,
13112 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
13113 SourceLocation LParenLoc, SourceLocation EndLoc) {
13114 MappableVarListInfo MVLI(VarList);
13115 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
13116 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013117
Kelvin Lief579432018-12-18 22:18:41 +000013118 OpenMPMapModifierKind Modifiers[] = { OMPC_MAP_MODIFIER_unknown,
13119 OMPC_MAP_MODIFIER_unknown };
13120 SourceLocation ModifiersLoc[OMPMapClause::NumberOfModifiers];
13121
13122 // Process map-type-modifiers, flag errors for duplicate modifiers.
13123 unsigned Count = 0;
13124 for (unsigned I = 0, E = MapTypeModifiers.size(); I < E; ++I) {
13125 if (MapTypeModifiers[I] != OMPC_MAP_MODIFIER_unknown &&
13126 llvm::find(Modifiers, MapTypeModifiers[I]) != std::end(Modifiers)) {
13127 Diag(MapTypeModifiersLoc[I], diag::err_omp_duplicate_map_type_modifier);
13128 continue;
13129 }
13130 assert(Count < OMPMapClause::NumberOfModifiers &&
Gheorghe-Teodor Berceaa3afcf22019-01-09 20:38:35 +000013131 "Modifiers exceed the allowed number of map type modifiers");
Kelvin Lief579432018-12-18 22:18:41 +000013132 Modifiers[Count] = MapTypeModifiers[I];
13133 ModifiersLoc[Count] = MapTypeModifiersLoc[I];
13134 ++Count;
13135 }
13136
Samuel Antao5de996e2016-01-22 20:21:36 +000013137 // We need to produce a map clause even if we don't have variables so that
13138 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000013139 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13140 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
Kelvin Lief579432018-12-18 22:18:41 +000013141 MVLI.VarComponents, Modifiers, ModifiersLoc,
13142 MapType, IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000013143}
Kelvin Li099bb8c2015-11-24 20:50:12 +000013144
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013145QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
13146 TypeResult ParsedType) {
13147 assert(ParsedType.isUsable());
13148
13149 QualType ReductionType = GetTypeFromParser(ParsedType.get());
13150 if (ReductionType.isNull())
13151 return QualType();
13152
13153 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
13154 // A type name in a declare reduction directive cannot be a function type, an
13155 // array type, a reference type, or a type qualified with const, volatile or
13156 // restrict.
13157 if (ReductionType.hasQualifiers()) {
13158 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
13159 return QualType();
13160 }
13161
13162 if (ReductionType->isFunctionType()) {
13163 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
13164 return QualType();
13165 }
13166 if (ReductionType->isReferenceType()) {
13167 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
13168 return QualType();
13169 }
13170 if (ReductionType->isArrayType()) {
13171 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
13172 return QualType();
13173 }
13174 return ReductionType;
13175}
13176
13177Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
13178 Scope *S, DeclContext *DC, DeclarationName Name,
13179 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
13180 AccessSpecifier AS, Decl *PrevDeclInScope) {
13181 SmallVector<Decl *, 8> Decls;
13182 Decls.reserve(ReductionTypes.size());
13183
13184 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000013185 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013186 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
13187 // A reduction-identifier may not be re-declared in the current scope for the
13188 // same type or for a type that is compatible according to the base language
13189 // rules.
13190 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
13191 OMPDeclareReductionDecl *PrevDRD = nullptr;
13192 bool InCompoundScope = true;
13193 if (S != nullptr) {
13194 // Find previous declaration with the same name not referenced in other
13195 // declarations.
13196 FunctionScopeInfo *ParentFn = getEnclosingFunction();
13197 InCompoundScope =
13198 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
13199 LookupName(Lookup, S);
13200 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
13201 /*AllowInlineNamespace=*/false);
13202 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
Alexey Bataeve3727102018-04-18 15:57:46 +000013203 LookupResult::Filter Filter = Lookup.makeFilter();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013204 while (Filter.hasNext()) {
13205 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
13206 if (InCompoundScope) {
13207 auto I = UsedAsPrevious.find(PrevDecl);
13208 if (I == UsedAsPrevious.end())
13209 UsedAsPrevious[PrevDecl] = false;
Alexey Bataeve3727102018-04-18 15:57:46 +000013210 if (OMPDeclareReductionDecl *D = PrevDecl->getPrevDeclInScope())
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013211 UsedAsPrevious[D] = true;
13212 }
13213 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
13214 PrevDecl->getLocation();
13215 }
13216 Filter.done();
13217 if (InCompoundScope) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013218 for (const auto &PrevData : UsedAsPrevious) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013219 if (!PrevData.second) {
13220 PrevDRD = PrevData.first;
13221 break;
13222 }
13223 }
13224 }
13225 } else if (PrevDeclInScope != nullptr) {
13226 auto *PrevDRDInScope = PrevDRD =
13227 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
13228 do {
13229 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
13230 PrevDRDInScope->getLocation();
13231 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
13232 } while (PrevDRDInScope != nullptr);
13233 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013234 for (const auto &TyData : ReductionTypes) {
13235 const auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013236 bool Invalid = false;
13237 if (I != PreviousRedeclTypes.end()) {
13238 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
13239 << TyData.first;
13240 Diag(I->second, diag::note_previous_definition);
13241 Invalid = true;
13242 }
13243 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
13244 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
13245 Name, TyData.first, PrevDRD);
13246 DC->addDecl(DRD);
13247 DRD->setAccess(AS);
13248 Decls.push_back(DRD);
13249 if (Invalid)
13250 DRD->setInvalidDecl();
13251 else
13252 PrevDRD = DRD;
13253 }
13254
13255 return DeclGroupPtrTy::make(
13256 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
13257}
13258
13259void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
13260 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13261
13262 // Enter new function scope.
13263 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013264 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013265 getCurFunction()->setHasOMPDeclareReductionCombiner();
13266
13267 if (S != nullptr)
13268 PushDeclContext(S, DRD);
13269 else
13270 CurContext = DRD;
13271
Faisal Valid143a0c2017-04-01 21:30:49 +000013272 PushExpressionEvaluationContext(
13273 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013274
13275 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013276 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
13277 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
13278 // uses semantics of argument handles by value, but it should be passed by
13279 // reference. C lang does not support references, so pass all parameters as
13280 // pointers.
13281 // Create 'T omp_in;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013282 VarDecl *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013283 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013284 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
13285 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
13286 // uses semantics of argument handles by value, but it should be passed by
13287 // reference. C lang does not support references, so pass all parameters as
13288 // pointers.
13289 // Create 'T omp_out;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013290 VarDecl *OmpOutParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013291 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
13292 if (S != nullptr) {
13293 PushOnScopeChains(OmpInParm, S);
13294 PushOnScopeChains(OmpOutParm, S);
13295 } else {
13296 DRD->addDecl(OmpInParm);
13297 DRD->addDecl(OmpOutParm);
13298 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013299 Expr *InE =
13300 ::buildDeclRefExpr(*this, OmpInParm, ReductionType, D->getLocation());
13301 Expr *OutE =
13302 ::buildDeclRefExpr(*this, OmpOutParm, ReductionType, D->getLocation());
13303 DRD->setCombinerData(InE, OutE);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013304}
13305
13306void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
13307 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13308 DiscardCleanupsInEvaluationContext();
13309 PopExpressionEvaluationContext();
13310
13311 PopDeclContext();
13312 PopFunctionScopeInfo();
13313
13314 if (Combiner != nullptr)
13315 DRD->setCombiner(Combiner);
13316 else
13317 DRD->setInvalidDecl();
13318}
13319
Alexey Bataev070f43a2017-09-06 14:49:58 +000013320VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013321 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13322
13323 // Enter new function scope.
13324 PushFunctionScope();
Reid Kleckner87a31802018-03-12 21:43:02 +000013325 setFunctionHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013326
13327 if (S != nullptr)
13328 PushDeclContext(S, DRD);
13329 else
13330 CurContext = DRD;
13331
Faisal Valid143a0c2017-04-01 21:30:49 +000013332 PushExpressionEvaluationContext(
13333 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013334
13335 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013336 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
13337 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
13338 // uses semantics of argument handles by value, but it should be passed by
13339 // reference. C lang does not support references, so pass all parameters as
13340 // pointers.
13341 // Create 'T omp_priv;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013342 VarDecl *OmpPrivParm =
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013343 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013344 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
13345 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
13346 // uses semantics of argument handles by value, but it should be passed by
13347 // reference. C lang does not support references, so pass all parameters as
13348 // pointers.
13349 // Create 'T omp_orig;' variable.
Alexey Bataeve3727102018-04-18 15:57:46 +000013350 VarDecl *OmpOrigParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000013351 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013352 if (S != nullptr) {
13353 PushOnScopeChains(OmpPrivParm, S);
13354 PushOnScopeChains(OmpOrigParm, S);
13355 } else {
13356 DRD->addDecl(OmpPrivParm);
13357 DRD->addDecl(OmpOrigParm);
13358 }
Alexey Bataeve6aa4692018-09-13 16:54:05 +000013359 Expr *OrigE =
13360 ::buildDeclRefExpr(*this, OmpOrigParm, ReductionType, D->getLocation());
13361 Expr *PrivE =
13362 ::buildDeclRefExpr(*this, OmpPrivParm, ReductionType, D->getLocation());
13363 DRD->setInitializerData(OrigE, PrivE);
Alexey Bataev070f43a2017-09-06 14:49:58 +000013364 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013365}
13366
Alexey Bataev070f43a2017-09-06 14:49:58 +000013367void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
13368 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013369 auto *DRD = cast<OMPDeclareReductionDecl>(D);
13370 DiscardCleanupsInEvaluationContext();
13371 PopExpressionEvaluationContext();
13372
13373 PopDeclContext();
13374 PopFunctionScopeInfo();
13375
Alexey Bataev070f43a2017-09-06 14:49:58 +000013376 if (Initializer != nullptr) {
13377 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
13378 } else if (OmpPrivParm->hasInit()) {
13379 DRD->setInitializer(OmpPrivParm->getInit(),
13380 OmpPrivParm->isDirectInit()
13381 ? OMPDeclareReductionDecl::DirectInit
13382 : OMPDeclareReductionDecl::CopyInit);
13383 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013384 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000013385 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013386}
13387
13388Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
13389 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013390 for (Decl *D : DeclReductions.get()) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013391 if (IsValid) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013392 if (S)
13393 PushOnScopeChains(cast<OMPDeclareReductionDecl>(D), S,
13394 /*AddToContext=*/false);
13395 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013396 D->setInvalidDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000013397 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000013398 }
13399 return DeclReductions;
13400}
13401
David Majnemer9d168222016-08-05 17:44:54 +000013402OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000013403 SourceLocation StartLoc,
13404 SourceLocation LParenLoc,
13405 SourceLocation EndLoc) {
13406 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000013407 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000013408
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013409 // OpenMP [teams Constrcut, Restrictions]
13410 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000013411 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
Alexey Bataeva0569352015-12-01 10:17:31 +000013412 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013413 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000013414
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000013415 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000013416 OpenMPDirectiveKind CaptureRegion =
13417 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
13418 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013419 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013420 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000013421 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13422 HelperValStmt = buildPreInits(Context, Captures);
13423 }
13424
13425 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
13426 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000013427}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013428
13429OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
13430 SourceLocation StartLoc,
13431 SourceLocation LParenLoc,
13432 SourceLocation EndLoc) {
13433 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000013434 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013435
13436 // OpenMP [teams Constrcut, Restrictions]
13437 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeve3727102018-04-18 15:57:46 +000013438 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
Alexey Bataeva0569352015-12-01 10:17:31 +000013439 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013440 return nullptr;
13441
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000013442 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000013443 OpenMPDirectiveKind CaptureRegion =
13444 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
13445 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013446 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013447 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000013448 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13449 HelperValStmt = buildPreInits(Context, Captures);
13450 }
13451
13452 return new (Context) OMPThreadLimitClause(
13453 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000013454}
Alexey Bataeva0569352015-12-01 10:17:31 +000013455
13456OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
13457 SourceLocation StartLoc,
13458 SourceLocation LParenLoc,
13459 SourceLocation EndLoc) {
13460 Expr *ValExpr = Priority;
13461
13462 // OpenMP [2.9.1, task Constrcut]
13463 // The priority-value is a non-negative numerical scalar expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013464 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
Alexey Bataeva0569352015-12-01 10:17:31 +000013465 /*StrictlyPositive=*/false))
13466 return nullptr;
13467
13468 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13469}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000013470
13471OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
13472 SourceLocation StartLoc,
13473 SourceLocation LParenLoc,
13474 SourceLocation EndLoc) {
13475 Expr *ValExpr = Grainsize;
13476
13477 // OpenMP [2.9.2, taskloop Constrcut]
13478 // The parameter of the grainsize clause must be a positive integer
13479 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013480 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000013481 /*StrictlyPositive=*/true))
13482 return nullptr;
13483
13484 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13485}
Alexey Bataev382967a2015-12-08 12:06:20 +000013486
13487OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
13488 SourceLocation StartLoc,
13489 SourceLocation LParenLoc,
13490 SourceLocation EndLoc) {
13491 Expr *ValExpr = NumTasks;
13492
13493 // OpenMP [2.9.2, taskloop Constrcut]
13494 // The parameter of the num_tasks clause must be a positive integer
13495 // expression.
Alexey Bataeve3727102018-04-18 15:57:46 +000013496 if (!isNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
Alexey Bataev382967a2015-12-08 12:06:20 +000013497 /*StrictlyPositive=*/true))
13498 return nullptr;
13499
13500 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
13501}
13502
Alexey Bataev28c75412015-12-15 08:19:24 +000013503OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
13504 SourceLocation LParenLoc,
13505 SourceLocation EndLoc) {
13506 // OpenMP [2.13.2, critical construct, Description]
13507 // ... where hint-expression is an integer constant expression that evaluates
13508 // to a valid lock hint.
13509 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
13510 if (HintExpr.isInvalid())
13511 return nullptr;
13512 return new (Context)
13513 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
13514}
13515
Carlo Bertollib4adf552016-01-15 18:50:31 +000013516OMPClause *Sema::ActOnOpenMPDistScheduleClause(
13517 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
13518 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
13519 SourceLocation EndLoc) {
13520 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
13521 std::string Values;
13522 Values += "'";
13523 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
13524 Values += "'";
13525 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
13526 << Values << getOpenMPClauseName(OMPC_dist_schedule);
13527 return nullptr;
13528 }
13529 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000013530 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000013531 if (ChunkSize) {
13532 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
13533 !ChunkSize->isInstantiationDependent() &&
13534 !ChunkSize->containsUnexpandedParameterPack()) {
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013535 SourceLocation ChunkSizeLoc = ChunkSize->getBeginLoc();
Carlo Bertollib4adf552016-01-15 18:50:31 +000013536 ExprResult Val =
13537 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
13538 if (Val.isInvalid())
13539 return nullptr;
13540
13541 ValExpr = Val.get();
13542
13543 // OpenMP [2.7.1, Restrictions]
13544 // chunk_size must be a loop invariant integer expression with a positive
13545 // value.
13546 llvm::APSInt Result;
13547 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
13548 if (Result.isSigned() && !Result.isStrictlyPositive()) {
13549 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
13550 << "dist_schedule" << ChunkSize->getSourceRange();
13551 return nullptr;
13552 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000013553 } else if (getOpenMPCaptureRegionForClause(
13554 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
13555 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000013556 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000013557 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataeve3727102018-04-18 15:57:46 +000013558 llvm::MapVector<const Expr *, DeclRefExpr *> Captures;
Alexey Bataev5a3af132016-03-29 08:58:54 +000013559 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
13560 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000013561 }
13562 }
13563 }
13564
13565 return new (Context)
13566 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000013567 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000013568}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000013569
13570OMPClause *Sema::ActOnOpenMPDefaultmapClause(
13571 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
13572 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
13573 SourceLocation KindLoc, SourceLocation EndLoc) {
13574 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000013575 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000013576 std::string Value;
13577 SourceLocation Loc;
13578 Value += "'";
13579 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
13580 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000013581 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000013582 Loc = MLoc;
13583 } else {
13584 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000013585 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000013586 Loc = KindLoc;
13587 }
13588 Value += "'";
13589 Diag(Loc, diag::err_omp_unexpected_clause_value)
13590 << Value << getOpenMPClauseName(OMPC_defaultmap);
13591 return nullptr;
13592 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000013593 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000013594
13595 return new (Context)
13596 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
13597}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013598
13599bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
13600 DeclContext *CurLexicalContext = getCurLexicalContext();
13601 if (!CurLexicalContext->isFileContext() &&
13602 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000013603 !CurLexicalContext->isExternCXXContext() &&
13604 !isa<CXXRecordDecl>(CurLexicalContext) &&
13605 !isa<ClassTemplateDecl>(CurLexicalContext) &&
13606 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
13607 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013608 Diag(Loc, diag::err_omp_region_not_file_context);
13609 return false;
13610 }
Kelvin Libc38e632018-09-10 02:07:09 +000013611 ++DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013612 return true;
13613}
13614
13615void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
Kelvin Libc38e632018-09-10 02:07:09 +000013616 assert(DeclareTargetNestingLevel > 0 &&
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013617 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
Kelvin Libc38e632018-09-10 02:07:09 +000013618 --DeclareTargetNestingLevel;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013619}
13620
David Majnemer9d168222016-08-05 17:44:54 +000013621void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
13622 CXXScopeSpec &ScopeSpec,
13623 const DeclarationNameInfo &Id,
13624 OMPDeclareTargetDeclAttr::MapTypeTy MT,
13625 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000013626 LookupResult Lookup(*this, Id, LookupOrdinaryName);
13627 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
13628
13629 if (Lookup.isAmbiguous())
13630 return;
13631 Lookup.suppressDiagnostics();
13632
13633 if (!Lookup.isSingleResult()) {
13634 if (TypoCorrection Corrected =
13635 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
13636 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
13637 CTK_ErrorRecovery)) {
13638 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
13639 << Id.getName());
13640 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
13641 return;
13642 }
13643
13644 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
13645 return;
13646 }
13647
13648 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
Alexey Bataev30a78212018-09-11 13:59:10 +000013649 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND) ||
13650 isa<FunctionTemplateDecl>(ND)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000013651 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
13652 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
Alexey Bataev30a78212018-09-11 13:59:10 +000013653 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
13654 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(
13655 cast<ValueDecl>(ND));
13656 if (!Res) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013657 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
Dmitry Polukhind69b5052016-05-09 14:59:13 +000013658 ND->addAttr(A);
13659 if (ASTMutationListener *ML = Context.getASTMutationListener())
13660 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000013661 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Alexey Bataev30a78212018-09-11 13:59:10 +000013662 } else if (*Res != MT) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000013663 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
13664 << Id.getName();
13665 }
Alexey Bataeve3727102018-04-18 15:57:46 +000013666 } else {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000013667 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
Alexey Bataeve3727102018-04-18 15:57:46 +000013668 }
Dmitry Polukhind69b5052016-05-09 14:59:13 +000013669}
13670
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013671static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
13672 Sema &SemaRef, Decl *D) {
Alexey Bataev30a78212018-09-11 13:59:10 +000013673 if (!D || !isa<VarDecl>(D))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013674 return;
Alexey Bataev30a78212018-09-11 13:59:10 +000013675 auto *VD = cast<VarDecl>(D);
13676 if (OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD))
13677 return;
13678 SemaRef.Diag(VD->getLocation(), diag::warn_omp_not_in_target_context);
13679 SemaRef.Diag(SL, diag::note_used_here) << SR;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013680}
13681
13682static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
13683 Sema &SemaRef, DSAStackTy *Stack,
13684 ValueDecl *VD) {
Alexey Bataeve3727102018-04-18 15:57:46 +000013685 return VD->hasAttr<OMPDeclareTargetDeclAttr>() ||
13686 checkTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
13687 /*FullCheck=*/false);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013688}
13689
Kelvin Li1ce87c72017-12-12 20:08:12 +000013690void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
13691 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013692 if (!D || D->isInvalidDecl())
13693 return;
13694 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
Stephen Kellyf2ceec42018-08-09 21:08:08 +000013695 SourceLocation SL = E ? E->getBeginLoc() : D->getLocation();
Alexey Bataeve3727102018-04-18 15:57:46 +000013696 if (auto *VD = dyn_cast<VarDecl>(D)) {
Alexey Bataevc1943e72018-07-09 19:58:08 +000013697 // Only global variables can be marked as declare target.
Alexey Bataev30a78212018-09-11 13:59:10 +000013698 if (!VD->isFileVarDecl() && !VD->isStaticLocal() &&
13699 !VD->isStaticDataMember())
Alexey Bataevc1943e72018-07-09 19:58:08 +000013700 return;
13701 // 2.10.6: threadprivate variable cannot appear in a declare target
13702 // directive.
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013703 if (DSAStack->isThreadPrivate(VD)) {
13704 Diag(SL, diag::err_omp_threadprivate_in_target);
Alexey Bataeve3727102018-04-18 15:57:46 +000013705 reportOriginalDsa(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013706 return;
13707 }
13708 }
Alexey Bataev97b72212018-08-14 18:31:20 +000013709 if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
13710 D = FTD->getTemplatedDecl();
Alexey Bataeve3727102018-04-18 15:57:46 +000013711 if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
Alexey Bataev30a78212018-09-11 13:59:10 +000013712 llvm::Optional<OMPDeclareTargetDeclAttr::MapTypeTy> Res =
13713 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(FD);
13714 if (Res && *Res == OMPDeclareTargetDeclAttr::MT_Link) {
Kelvin Li1ce87c72017-12-12 20:08:12 +000013715 assert(IdLoc.isValid() && "Source location is expected");
13716 Diag(IdLoc, diag::err_omp_function_in_link_clause);
13717 Diag(FD->getLocation(), diag::note_defined_here) << FD;
13718 return;
13719 }
13720 }
Alexey Bataev30a78212018-09-11 13:59:10 +000013721 if (auto *VD = dyn_cast<ValueDecl>(D)) {
13722 // Problem if any with var declared with incomplete type will be reported
13723 // as normal, so no need to check it here.
13724 if ((E || !VD->getType()->isIncompleteType()) &&
13725 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD))
13726 return;
13727 if (!E && !OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(VD)) {
13728 // Checking declaration inside declare target region.
13729 if (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
13730 isa<FunctionTemplateDecl>(D)) {
13731 auto *A = OMPDeclareTargetDeclAttr::CreateImplicit(
13732 Context, OMPDeclareTargetDeclAttr::MT_To);
13733 D->addAttr(A);
13734 if (ASTMutationListener *ML = Context.getASTMutationListener())
13735 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
13736 }
13737 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013738 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013739 }
Alexey Bataev30a78212018-09-11 13:59:10 +000013740 if (!E)
13741 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013742 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
13743}
Samuel Antao661c0902016-05-26 17:39:58 +000013744
13745OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
13746 SourceLocation StartLoc,
13747 SourceLocation LParenLoc,
13748 SourceLocation EndLoc) {
13749 MappableVarListInfo MVLI(VarList);
13750 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
13751 if (MVLI.ProcessedVarList.empty())
13752 return nullptr;
13753
13754 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13755 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13756 MVLI.VarComponents);
13757}
Samuel Antaoec172c62016-05-26 17:49:04 +000013758
13759OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
13760 SourceLocation StartLoc,
13761 SourceLocation LParenLoc,
13762 SourceLocation EndLoc) {
13763 MappableVarListInfo MVLI(VarList);
13764 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
13765 if (MVLI.ProcessedVarList.empty())
13766 return nullptr;
13767
13768 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13769 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13770 MVLI.VarComponents);
13771}
Carlo Bertolli2404b172016-07-13 15:37:16 +000013772
13773OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
13774 SourceLocation StartLoc,
13775 SourceLocation LParenLoc,
13776 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000013777 MappableVarListInfo MVLI(VarList);
13778 SmallVector<Expr *, 8> PrivateCopies;
13779 SmallVector<Expr *, 8> Inits;
13780
Alexey Bataeve3727102018-04-18 15:57:46 +000013781 for (Expr *RefExpr : VarList) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000013782 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
13783 SourceLocation ELoc;
13784 SourceRange ERange;
13785 Expr *SimpleRefExpr = RefExpr;
13786 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13787 if (Res.second) {
13788 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000013789 MVLI.ProcessedVarList.push_back(RefExpr);
13790 PrivateCopies.push_back(nullptr);
13791 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000013792 }
13793 ValueDecl *D = Res.first;
13794 if (!D)
13795 continue;
13796
13797 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000013798 Type = Type.getNonReferenceType().getUnqualifiedType();
13799
13800 auto *VD = dyn_cast<VarDecl>(D);
13801
13802 // Item should be a pointer or reference to pointer.
13803 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000013804 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
13805 << 0 << RefExpr->getSourceRange();
13806 continue;
13807 }
Samuel Antaocc10b852016-07-28 14:23:26 +000013808
13809 // Build the private variable and the expression that refers to it.
Alexey Bataev63cc8e92018-03-20 14:45:59 +000013810 auto VDPrivate =
13811 buildVarDecl(*this, ELoc, Type, D->getName(),
13812 D->hasAttrs() ? &D->getAttrs() : nullptr,
13813 VD ? cast<DeclRefExpr>(SimpleRefExpr) : nullptr);
Samuel Antaocc10b852016-07-28 14:23:26 +000013814 if (VDPrivate->isInvalidDecl())
13815 continue;
13816
13817 CurContext->addDecl(VDPrivate);
Alexey Bataeve3727102018-04-18 15:57:46 +000013818 DeclRefExpr *VDPrivateRefExpr = buildDeclRefExpr(
Samuel Antaocc10b852016-07-28 14:23:26 +000013819 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
13820
13821 // Add temporary variable to initialize the private copy of the pointer.
Alexey Bataeve3727102018-04-18 15:57:46 +000013822 VarDecl *VDInit =
Samuel Antaocc10b852016-07-28 14:23:26 +000013823 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
Alexey Bataeve3727102018-04-18 15:57:46 +000013824 DeclRefExpr *VDInitRefExpr = buildDeclRefExpr(
13825 *this, VDInit, RefExpr->getType(), RefExpr->getExprLoc());
Samuel Antaocc10b852016-07-28 14:23:26 +000013826 AddInitializerToDecl(VDPrivate,
13827 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000013828 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000013829
13830 // If required, build a capture to implement the privatization initialized
13831 // with the current list item value.
13832 DeclRefExpr *Ref = nullptr;
13833 if (!VD)
13834 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
13835 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
13836 PrivateCopies.push_back(VDPrivateRefExpr);
13837 Inits.push_back(VDInitRefExpr);
13838
13839 // We need to add a data sharing attribute for this variable to make sure it
13840 // is correctly captured. A variable that shows up in a use_device_ptr has
13841 // similar properties of a first private variable.
13842 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
13843
13844 // Create a mappable component for the list item. List items in this clause
13845 // only need a component.
13846 MVLI.VarBaseDeclarations.push_back(D);
13847 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13848 MVLI.VarComponents.back().push_back(
13849 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000013850 }
13851
Samuel Antaocc10b852016-07-28 14:23:26 +000013852 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000013853 return nullptr;
13854
Samuel Antaocc10b852016-07-28 14:23:26 +000013855 return OMPUseDevicePtrClause::Create(
13856 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13857 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000013858}
Carlo Bertolli70594e92016-07-13 17:16:49 +000013859
13860OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
13861 SourceLocation StartLoc,
13862 SourceLocation LParenLoc,
13863 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000013864 MappableVarListInfo MVLI(VarList);
Alexey Bataeve3727102018-04-18 15:57:46 +000013865 for (Expr *RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000013866 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000013867 SourceLocation ELoc;
13868 SourceRange ERange;
13869 Expr *SimpleRefExpr = RefExpr;
13870 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13871 if (Res.second) {
13872 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000013873 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013874 }
13875 ValueDecl *D = Res.first;
13876 if (!D)
13877 continue;
13878
13879 QualType Type = D->getType();
13880 // item should be a pointer or array or reference to pointer or array
13881 if (!Type.getNonReferenceType()->isPointerType() &&
13882 !Type.getNonReferenceType()->isArrayType()) {
13883 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
13884 << 0 << RefExpr->getSourceRange();
13885 continue;
13886 }
Samuel Antao6890b092016-07-28 14:25:09 +000013887
13888 // Check if the declaration in the clause does not show up in any data
13889 // sharing attribute.
Alexey Bataeve3727102018-04-18 15:57:46 +000013890 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, /*FromParent=*/false);
Samuel Antao6890b092016-07-28 14:25:09 +000013891 if (isOpenMPPrivate(DVar.CKind)) {
13892 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13893 << getOpenMPClauseName(DVar.CKind)
13894 << getOpenMPClauseName(OMPC_is_device_ptr)
13895 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataeve3727102018-04-18 15:57:46 +000013896 reportOriginalDsa(*this, DSAStack, D, DVar);
Samuel Antao6890b092016-07-28 14:25:09 +000013897 continue;
13898 }
13899
Alexey Bataeve3727102018-04-18 15:57:46 +000013900 const Expr *ConflictExpr;
Samuel Antao6890b092016-07-28 14:25:09 +000013901 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000013902 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000013903 [&ConflictExpr](
13904 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
13905 OpenMPClauseKind) -> bool {
13906 ConflictExpr = R.front().getAssociatedExpression();
13907 return true;
13908 })) {
13909 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
13910 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
13911 << ConflictExpr->getSourceRange();
13912 continue;
13913 }
13914
13915 // Store the components in the stack so that they can be used to check
13916 // against other clauses later on.
13917 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
13918 DSAStack->addMappableExpressionComponents(
13919 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
13920
13921 // Record the expression we've just processed.
13922 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
13923
13924 // Create a mappable component for the list item. List items in this clause
13925 // only need a component. We use a null declaration to signal fields in
13926 // 'this'.
13927 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
13928 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
13929 "Unexpected device pointer expression!");
13930 MVLI.VarBaseDeclarations.push_back(
13931 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
13932 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13933 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013934 }
13935
Samuel Antao6890b092016-07-28 14:25:09 +000013936 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000013937 return nullptr;
13938
Samuel Antao6890b092016-07-28 14:25:09 +000013939 return OMPIsDevicePtrClause::Create(
13940 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13941 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013942}