blob: be51787a377706b011b58be4a8bca14bb7009709 [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//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9/// \file
10/// \brief This file implements semantic analysis for OpenMP directives and
Alexey Bataev6f6f3b42013-05-13 04:18:18 +000011/// clauses.
Alexey Bataeva769e072013-03-22 06:34:35 +000012///
13//===----------------------------------------------------------------------===//
14
Alexey Bataevb08f89f2015-08-14 12:25:37 +000015#include "TreeTransform.h"
Alexey Bataev9959db52014-05-06 10:08:46 +000016#include "clang/AST/ASTContext.h"
Alexey Bataev97720002014-11-11 04:05:39 +000017#include "clang/AST/ASTMutationListener.h"
Alexey Bataeva839ddd2016-03-17 10:19:46 +000018#include "clang/AST/CXXInheritance.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000019#include "clang/AST/Decl.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000020#include "clang/AST/DeclCXX.h"
Alexey Bataeva769e072013-03-22 06:34:35 +000021#include "clang/AST/DeclOpenMP.h"
Alexey Bataev5ec3eb12013-07-19 03:13:43 +000022#include "clang/AST/StmtCXX.h"
23#include "clang/AST/StmtOpenMP.h"
24#include "clang/AST/StmtVisitor.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 Bataevf47c4b42017-09-26 13:47:31 +000038static Expr *CheckMapClauseExpressionBase(
39 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 {
44/// \brief Default data sharing attributes, which can be applied to directive.
45enum DefaultDataSharingAttributes {
Alexey Bataeved09d242014-05-28 05:53:51 +000046 DSA_unspecified = 0, /// \brief Data sharing attribute not specified.
47 DSA_none = 1 << 0, /// \brief Default data sharing attribute 'none'.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000048 DSA_shared = 1 << 1, /// \brief Default data sharing attribute 'shared'.
49};
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
Alexey Bataev758e55e2013-09-06 18:03:48 +000057/// \brief Stack for tracking declarations used in OpenMP directives and
58/// clauses and their data-sharing attributes.
Alexey Bataev7ace49d2016-05-17 08:55:33 +000059class DSAStackTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +000060public:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000061 struct DSAVarData final {
62 OpenMPDirectiveKind DKind = OMPD_unknown;
63 OpenMPClauseKind CKind = OMPC_unknown;
64 Expr *RefExpr = nullptr;
65 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +000066 SourceLocation ImplicitDSALoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +000067 DSAVarData() = default;
Alexey Bataevf189cb72017-07-24 14:52:13 +000068 DSAVarData(OpenMPDirectiveKind DKind, OpenMPClauseKind CKind, Expr *RefExpr,
69 DeclRefExpr *PrivateCopy, SourceLocation ImplicitDSALoc)
70 : DKind(DKind), CKind(CKind), RefExpr(RefExpr),
71 PrivateCopy(PrivateCopy), ImplicitDSALoc(ImplicitDSALoc) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +000072 };
Alexey Bataev8b427062016-05-25 12:36:08 +000073 typedef llvm::SmallVector<std::pair<Expr *, OverloadedOperatorKind>, 4>
74 OperatorOffsetTy;
Alexey Bataeved09d242014-05-28 05:53:51 +000075
Alexey Bataev758e55e2013-09-06 18:03:48 +000076private:
Alexey Bataev7ace49d2016-05-17 08:55:33 +000077 struct DSAInfo final {
78 OpenMPClauseKind Attributes = OMPC_unknown;
79 /// Pointer to a reference expression and a flag which shows that the
80 /// variable is marked as lastprivate(true) or not (false).
81 llvm::PointerIntPair<Expr *, 1, bool> RefExpr;
82 DeclRefExpr *PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +000083 };
Alexey Bataev90c228f2016-02-08 09:29:13 +000084 typedef llvm::DenseMap<ValueDecl *, DSAInfo> DeclSAMapTy;
85 typedef llvm::DenseMap<ValueDecl *, Expr *> AlignedMapTy;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +000086 typedef std::pair<unsigned, VarDecl *> LCDeclInfo;
87 typedef llvm::DenseMap<ValueDecl *, LCDeclInfo> LoopControlVariablesMapTy;
Samuel Antao6890b092016-07-28 14:25:09 +000088 /// Struct that associates a component with the clause kind where they are
89 /// found.
90 struct MappedExprComponentTy {
91 OMPClauseMappableExprCommon::MappableExprComponentLists Components;
92 OpenMPClauseKind Kind = OMPC_unknown;
93 };
94 typedef llvm::DenseMap<ValueDecl *, MappedExprComponentTy>
Samuel Antao90927002016-04-26 14:54:23 +000095 MappedExprComponentsTy;
Alexey Bataev28c75412015-12-15 08:19:24 +000096 typedef llvm::StringMap<std::pair<OMPCriticalDirective *, llvm::APSInt>>
97 CriticalsWithHintsTy;
Alexey Bataev8b427062016-05-25 12:36:08 +000098 typedef llvm::DenseMap<OMPDependClause *, OperatorOffsetTy>
99 DoacrossDependMapTy;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000100 struct ReductionData {
Alexey Bataevf87fa882017-07-21 19:26:22 +0000101 typedef llvm::PointerEmbeddedInt<BinaryOperatorKind, 16> BOKPtrType;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000102 SourceRange ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000103 llvm::PointerUnion<const Expr *, BOKPtrType> ReductionOp;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000104 ReductionData() = default;
105 void set(BinaryOperatorKind BO, SourceRange RR) {
106 ReductionRange = RR;
107 ReductionOp = BO;
108 }
109 void set(const Expr *RefExpr, SourceRange RR) {
110 ReductionRange = RR;
111 ReductionOp = RefExpr;
112 }
113 };
114 typedef llvm::DenseMap<ValueDecl *, ReductionData> DeclReductionMapTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000115
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000116 struct SharingMapTy final {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000117 DeclSAMapTy SharingMap;
Alexey Bataevfa312f32017-07-21 18:48:21 +0000118 DeclReductionMapTy ReductionMap;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000119 AlignedMapTy AlignedMap;
Samuel Antao90927002016-04-26 14:54:23 +0000120 MappedExprComponentsTy MappedExprComponents;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000121 LoopControlVariablesMapTy LCVMap;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000122 DefaultDataSharingAttributes DefaultAttr = DSA_unspecified;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000123 SourceLocation DefaultAttrLoc;
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000124 DefaultMapAttributes DefaultMapAttr = DMA_unspecified;
125 SourceLocation DefaultMapAttrLoc;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000126 OpenMPDirectiveKind Directive = OMPD_unknown;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000127 DeclarationNameInfo DirectiveName;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000128 Scope *CurScope = nullptr;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000129 SourceLocation ConstructLoc;
Alexey Bataev8b427062016-05-25 12:36:08 +0000130 /// Set of 'depend' clauses with 'sink|source' dependence kind. Required to
131 /// get the data (loop counters etc.) about enclosing loop-based construct.
132 /// This data is required during codegen.
133 DoacrossDependMapTy DoacrossDepends;
Alexey Bataev346265e2015-09-25 10:37:12 +0000134 /// \brief first argument (Expr *) contains optional argument of the
135 /// 'ordered' clause, the second one is true if the regions has 'ordered'
136 /// clause, false otherwise.
137 llvm::PointerIntPair<Expr *, 1, bool> OrderedRegion;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000138 bool NowaitRegion = false;
139 bool CancelRegion = false;
140 unsigned AssociatedLoops = 1;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000141 SourceLocation InnerTeamsRegionLoc;
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000142 /// Reference to the taskgroup task_reduction reference expression.
143 Expr *TaskgroupReductionRef = nullptr;
Alexey Bataeved09d242014-05-28 05:53:51 +0000144 SharingMapTy(OpenMPDirectiveKind DKind, DeclarationNameInfo Name,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000145 Scope *CurScope, SourceLocation Loc)
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000146 : Directive(DKind), DirectiveName(Name), CurScope(CurScope),
147 ConstructLoc(Loc) {}
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000148 SharingMapTy() = default;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000149 };
150
Axel Naumann323862e2016-02-03 10:45:22 +0000151 typedef SmallVector<SharingMapTy, 4> StackTy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000152
153 /// \brief Stack of used declaration and their data-sharing attributes.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000154 DeclSAMapTy Threadprivates;
Alexey Bataev4b465392017-04-26 15:06:24 +0000155 const FunctionScopeInfo *CurrentNonCapturingFunctionScope = nullptr;
156 SmallVector<std::pair<StackTy, const FunctionScopeInfo *>, 4> Stack;
Alexey Bataev39f915b82015-05-08 10:41:21 +0000157 /// \brief true, if check for DSA must be from parent directive, false, if
158 /// from current directive.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000159 OpenMPClauseKind ClauseKindMode = OMPC_unknown;
Alexey Bataev7ff55242014-06-19 09:13:45 +0000160 Sema &SemaRef;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000161 bool ForceCapturing = false;
Alexey Bataev28c75412015-12-15 08:19:24 +0000162 CriticalsWithHintsTy Criticals;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000163
164 typedef SmallVector<SharingMapTy, 8>::reverse_iterator reverse_iterator;
165
David Majnemer9d168222016-08-05 17:44:54 +0000166 DSAVarData getDSA(StackTy::reverse_iterator &Iter, ValueDecl *D);
Alexey Bataevec3da872014-01-31 05:15:34 +0000167
168 /// \brief Checks if the variable is a local for OpenMP region.
169 bool isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter);
Alexey Bataeved09d242014-05-28 05:53:51 +0000170
Alexey Bataev4b465392017-04-26 15:06:24 +0000171 bool isStackEmpty() const {
172 return Stack.empty() ||
173 Stack.back().second != CurrentNonCapturingFunctionScope ||
174 Stack.back().first.empty();
175 }
176
Alexey Bataev758e55e2013-09-06 18:03:48 +0000177public:
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000178 explicit DSAStackTy(Sema &S) : SemaRef(S) {}
Alexey Bataev39f915b82015-05-08 10:41:21 +0000179
Alexey Bataevaac108a2015-06-23 04:51:00 +0000180 bool isClauseParsingMode() const { return ClauseKindMode != OMPC_unknown; }
Alexey Bataev3f82cfc2017-12-13 15:28:44 +0000181 OpenMPClauseKind getClauseParsingMode() const {
182 assert(isClauseParsingMode() && "Must be in clause parsing mode.");
183 return ClauseKindMode;
184 }
Alexey Bataevaac108a2015-06-23 04:51:00 +0000185 void setClauseParsingMode(OpenMPClauseKind K) { ClauseKindMode = K; }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000186
Samuel Antao9c75cfe2015-07-27 16:38:06 +0000187 bool isForceVarCapturing() const { return ForceCapturing; }
188 void setForceVarCapturing(bool V) { ForceCapturing = V; }
189
Alexey Bataev758e55e2013-09-06 18:03:48 +0000190 void push(OpenMPDirectiveKind DKind, const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +0000191 Scope *CurScope, SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000192 if (Stack.empty() ||
193 Stack.back().second != CurrentNonCapturingFunctionScope)
194 Stack.emplace_back(StackTy(), CurrentNonCapturingFunctionScope);
195 Stack.back().first.emplace_back(DKind, DirName, CurScope, Loc);
196 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000197 }
198
199 void pop() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000200 assert(!Stack.back().first.empty() &&
201 "Data-sharing attributes stack is empty!");
202 Stack.back().first.pop_back();
203 }
204
205 /// Start new OpenMP region stack in new non-capturing function.
206 void pushFunction() {
207 const FunctionScopeInfo *CurFnScope = SemaRef.getCurFunction();
208 assert(!isa<CapturingScopeInfo>(CurFnScope));
209 CurrentNonCapturingFunctionScope = CurFnScope;
210 }
211 /// Pop region stack for non-capturing function.
212 void popFunction(const FunctionScopeInfo *OldFSI) {
213 if (!Stack.empty() && Stack.back().second == OldFSI) {
214 assert(Stack.back().first.empty());
215 Stack.pop_back();
216 }
217 CurrentNonCapturingFunctionScope = nullptr;
218 for (const FunctionScopeInfo *FSI : llvm::reverse(SemaRef.FunctionScopes)) {
219 if (!isa<CapturingScopeInfo>(FSI)) {
220 CurrentNonCapturingFunctionScope = FSI;
221 break;
222 }
223 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000224 }
225
Alexey Bataev28c75412015-12-15 08:19:24 +0000226 void addCriticalWithHint(OMPCriticalDirective *D, llvm::APSInt Hint) {
227 Criticals[D->getDirectiveName().getAsString()] = std::make_pair(D, Hint);
228 }
229 const std::pair<OMPCriticalDirective *, llvm::APSInt>
230 getCriticalWithHint(const DeclarationNameInfo &Name) const {
231 auto I = Criticals.find(Name.getAsString());
232 if (I != Criticals.end())
233 return I->second;
234 return std::make_pair(nullptr, llvm::APSInt());
235 }
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000236 /// \brief If 'aligned' declaration for given variable \a D was not seen yet,
Alp Toker15e62a32014-06-06 12:02:07 +0000237 /// add it and return NULL; otherwise return previous occurrence's expression
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000238 /// for diagnostics.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000239 Expr *addUniqueAligned(ValueDecl *D, Expr *NewDE);
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000240
Alexey Bataev9c821032015-04-30 04:23:23 +0000241 /// \brief Register specified variable as loop control variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000242 void addLoopControlVariable(ValueDecl *D, VarDecl *Capture);
Alexey Bataev9c821032015-04-30 04:23:23 +0000243 /// \brief Check if the specified variable is a loop control variable for
244 /// current region.
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000245 /// \return The index of the loop control variable in the list of associated
246 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000247 LCDeclInfo isLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000248 /// \brief Check if the specified variable is a loop control variable for
249 /// parent region.
250 /// \return The index of the loop control variable in the list of associated
251 /// for-loops (from outer to inner).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000252 LCDeclInfo isParentLoopControlVariable(ValueDecl *D);
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000253 /// \brief Get the loop control variable for the I-th loop (or nullptr) in
254 /// parent directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000255 ValueDecl *getParentLoopControlVariable(unsigned I);
Alexey Bataev9c821032015-04-30 04:23:23 +0000256
Alexey Bataev758e55e2013-09-06 18:03:48 +0000257 /// \brief Adds explicit data sharing attribute to the specified declaration.
Alexey Bataev90c228f2016-02-08 09:29:13 +0000258 void addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
259 DeclRefExpr *PrivateCopy = nullptr);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000260
Alexey Bataevfa312f32017-07-21 18:48:21 +0000261 /// Adds additional information for the reduction items with the reduction id
262 /// represented as an operator.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000263 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
264 BinaryOperatorKind BOK);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000265 /// Adds additional information for the reduction items with the reduction id
266 /// represented as reduction identifier.
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000267 void addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
268 const Expr *ReductionRef);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000269 /// Returns the location and reduction operation from the innermost parent
270 /// region for the given \p D.
Alexey Bataevf189cb72017-07-24 14:52:13 +0000271 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000272 BinaryOperatorKind &BOK,
273 Expr *&TaskgroupDescriptor);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000274 /// Returns the location and reduction operation from the innermost parent
275 /// region for the given \p D.
Alexey Bataevf189cb72017-07-24 14:52:13 +0000276 DSAVarData getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000277 const Expr *&ReductionRef,
278 Expr *&TaskgroupDescriptor);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000279 /// Return reduction reference expression for the current taskgroup.
280 Expr *getTaskgroupReductionRef() const {
281 assert(Stack.back().first.back().Directive == OMPD_taskgroup &&
282 "taskgroup reference expression requested for non taskgroup "
283 "directive.");
284 return Stack.back().first.back().TaskgroupReductionRef;
285 }
Alexey Bataev88202be2017-07-27 13:20:36 +0000286 /// Checks if the given \p VD declaration is actually a taskgroup reduction
287 /// descriptor variable at the \p Level of OpenMP regions.
288 bool isTaskgroupReductionRef(ValueDecl *VD, unsigned Level) const {
289 return Stack.back().first[Level].TaskgroupReductionRef &&
290 cast<DeclRefExpr>(Stack.back().first[Level].TaskgroupReductionRef)
291 ->getDecl() == VD;
292 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000293
Alexey Bataev758e55e2013-09-06 18:03:48 +0000294 /// \brief Returns data sharing attributes from top of the stack for the
295 /// specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000296 DSAVarData getTopDSA(ValueDecl *D, bool FromParent);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000297 /// \brief Returns data-sharing attributes for the specified declaration.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000298 DSAVarData getImplicitDSA(ValueDecl *D, bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000299 /// \brief Checks if the specified variables has data-sharing attributes which
300 /// match specified \a CPred predicate in any directive which matches \a DPred
301 /// predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000302 DSAVarData hasDSA(ValueDecl *D,
303 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
304 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
305 bool FromParent);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000306 /// \brief Checks if the specified variables has data-sharing attributes which
307 /// match specified \a CPred predicate in any innermost directive which
308 /// matches \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000309 DSAVarData
310 hasInnermostDSA(ValueDecl *D,
311 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
312 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
313 bool FromParent);
Alexey Bataevaac108a2015-06-23 04:51:00 +0000314 /// \brief Checks if the specified variables has explicit data-sharing
315 /// attributes which match specified \a CPred predicate at the specified
316 /// OpenMP region.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000317 bool hasExplicitDSA(ValueDecl *D,
Alexey Bataevaac108a2015-06-23 04:51:00 +0000318 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000319 unsigned Level, bool NotLastprivate = false);
Samuel Antao4be30e92015-10-02 17:14:03 +0000320
321 /// \brief Returns true if the directive at level \Level matches in the
322 /// specified \a DPred predicate.
323 bool hasExplicitDirective(
324 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
325 unsigned Level);
326
Alexander Musmand9ed09f2014-07-21 09:42:05 +0000327 /// \brief Finds a directive which matches specified \a DPred predicate.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000328 bool hasDirective(const llvm::function_ref<bool(OpenMPDirectiveKind,
329 const DeclarationNameInfo &,
330 SourceLocation)> &DPred,
331 bool FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000332
Alexey Bataev758e55e2013-09-06 18:03:48 +0000333 /// \brief Returns currently analyzed directive.
334 OpenMPDirectiveKind getCurrentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000335 return isStackEmpty() ? OMPD_unknown : Stack.back().first.back().Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000336 }
Alexey Bataevdfa430f2017-12-08 15:03:50 +0000337 /// \brief Returns directive kind at specified level.
338 OpenMPDirectiveKind getDirective(unsigned Level) const {
339 assert(!isStackEmpty() && "No directive at specified level.");
340 return Stack.back().first[Level].Directive;
341 }
Alexey Bataev549210e2014-06-24 04:39:47 +0000342 /// \brief Returns parent directive.
343 OpenMPDirectiveKind getParentDirective() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000344 if (isStackEmpty() || Stack.back().first.size() == 1)
345 return OMPD_unknown;
346 return std::next(Stack.back().first.rbegin())->Directive;
Alexey Bataev549210e2014-06-24 04:39:47 +0000347 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000348
349 /// \brief Set default data sharing attribute to none.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000350 void setDefaultDSANone(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000351 assert(!isStackEmpty());
352 Stack.back().first.back().DefaultAttr = DSA_none;
353 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000354 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000355 /// \brief Set default data sharing attribute to shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000356 void setDefaultDSAShared(SourceLocation Loc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000357 assert(!isStackEmpty());
358 Stack.back().first.back().DefaultAttr = DSA_shared;
359 Stack.back().first.back().DefaultAttrLoc = Loc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000360 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000361 /// Set default data mapping attribute to 'tofrom:scalar'.
362 void setDefaultDMAToFromScalar(SourceLocation Loc) {
363 assert(!isStackEmpty());
364 Stack.back().first.back().DefaultMapAttr = DMA_tofrom_scalar;
365 Stack.back().first.back().DefaultMapAttrLoc = Loc;
366 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000367
368 DefaultDataSharingAttributes getDefaultDSA() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000369 return isStackEmpty() ? DSA_unspecified
370 : Stack.back().first.back().DefaultAttr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000371 }
Alexey Bataevbae9a792014-06-27 10:37:06 +0000372 SourceLocation getDefaultDSALocation() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000373 return isStackEmpty() ? SourceLocation()
374 : Stack.back().first.back().DefaultAttrLoc;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000375 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +0000376 DefaultMapAttributes getDefaultDMA() const {
377 return isStackEmpty() ? DMA_unspecified
378 : Stack.back().first.back().DefaultMapAttr;
379 }
380 DefaultMapAttributes getDefaultDMAAtLevel(unsigned Level) const {
381 return Stack.back().first[Level].DefaultMapAttr;
382 }
383 SourceLocation getDefaultDMALocation() const {
384 return isStackEmpty() ? SourceLocation()
385 : Stack.back().first.back().DefaultMapAttrLoc;
386 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000387
Alexey Bataevf29276e2014-06-18 04:14:57 +0000388 /// \brief Checks if the specified variable is a threadprivate.
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000389 bool isThreadPrivate(VarDecl *D) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000390 DSAVarData DVar = getTopDSA(D, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +0000391 return isOpenMPThreadPrivate(DVar.CKind);
Alexey Bataevd48bcd82014-03-31 03:36:38 +0000392 }
393
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000394 /// \brief Marks current region as ordered (it has an 'ordered' clause).
Alexey Bataev346265e2015-09-25 10:37:12 +0000395 void setOrderedRegion(bool IsOrdered, Expr *Param) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000396 assert(!isStackEmpty());
397 Stack.back().first.back().OrderedRegion.setInt(IsOrdered);
398 Stack.back().first.back().OrderedRegion.setPointer(Param);
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000399 }
400 /// \brief Returns true, if parent region is ordered (has associated
401 /// 'ordered' clause), false - otherwise.
402 bool isParentOrderedRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000403 if (isStackEmpty() || Stack.back().first.size() == 1)
404 return false;
405 return std::next(Stack.back().first.rbegin())->OrderedRegion.getInt();
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000406 }
Alexey Bataev346265e2015-09-25 10:37:12 +0000407 /// \brief Returns optional parameter for the ordered region.
408 Expr *getParentOrderedRegionParam() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000409 if (isStackEmpty() || Stack.back().first.size() == 1)
410 return nullptr;
411 return std::next(Stack.back().first.rbegin())->OrderedRegion.getPointer();
Alexey Bataev346265e2015-09-25 10:37:12 +0000412 }
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000413 /// \brief Marks current region as nowait (it has a 'nowait' clause).
414 void setNowaitRegion(bool IsNowait = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000415 assert(!isStackEmpty());
416 Stack.back().first.back().NowaitRegion = IsNowait;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000417 }
418 /// \brief Returns true, if parent region is nowait (has associated
419 /// 'nowait' clause), false - otherwise.
420 bool isParentNowaitRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000421 if (isStackEmpty() || Stack.back().first.size() == 1)
422 return false;
423 return std::next(Stack.back().first.rbegin())->NowaitRegion;
Alexey Bataev6d4ed052015-07-01 06:57:41 +0000424 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000425 /// \brief Marks parent region as cancel region.
426 void setParentCancelRegion(bool Cancel = true) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000427 if (!isStackEmpty() && Stack.back().first.size() > 1) {
428 auto &StackElemRef = *std::next(Stack.back().first.rbegin());
429 StackElemRef.CancelRegion |= StackElemRef.CancelRegion || Cancel;
430 }
Alexey Bataev25e5b442015-09-15 12:52:43 +0000431 }
432 /// \brief Return true if current region has inner cancel construct.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000433 bool isCancelRegion() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000434 return isStackEmpty() ? false : Stack.back().first.back().CancelRegion;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000435 }
Alexey Bataev9fb6e642014-07-22 06:45:04 +0000436
Alexey Bataev9c821032015-04-30 04:23:23 +0000437 /// \brief Set collapse value for the region.
Alexey Bataev4b465392017-04-26 15:06:24 +0000438 void setAssociatedLoops(unsigned Val) {
439 assert(!isStackEmpty());
440 Stack.back().first.back().AssociatedLoops = Val;
441 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000442 /// \brief Return collapse value for region.
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000443 unsigned getAssociatedLoops() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000444 return isStackEmpty() ? 0 : Stack.back().first.back().AssociatedLoops;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000445 }
Alexey Bataev9c821032015-04-30 04:23:23 +0000446
Alexey Bataev13314bf2014-10-09 04:18:56 +0000447 /// \brief Marks current target region as one with closely nested teams
448 /// region.
449 void setParentTeamsRegionLoc(SourceLocation TeamsRegionLoc) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000450 if (!isStackEmpty() && Stack.back().first.size() > 1) {
451 std::next(Stack.back().first.rbegin())->InnerTeamsRegionLoc =
452 TeamsRegionLoc;
453 }
Alexey Bataev13314bf2014-10-09 04:18:56 +0000454 }
455 /// \brief Returns true, if current region has closely nested teams region.
456 bool hasInnerTeamsRegion() const {
457 return getInnerTeamsRegionLoc().isValid();
458 }
459 /// \brief Returns location of the nested teams region (if any).
460 SourceLocation getInnerTeamsRegionLoc() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000461 return isStackEmpty() ? SourceLocation()
462 : Stack.back().first.back().InnerTeamsRegionLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000463 }
464
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000465 Scope *getCurScope() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000466 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000467 }
468 Scope *getCurScope() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000469 return isStackEmpty() ? nullptr : Stack.back().first.back().CurScope;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000470 }
471 SourceLocation getConstructLoc() {
Alexey Bataev4b465392017-04-26 15:06:24 +0000472 return isStackEmpty() ? SourceLocation()
473 : Stack.back().first.back().ConstructLoc;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000474 }
Kelvin Li0bff7af2015-11-23 05:32:03 +0000475
Samuel Antao4c8035b2016-12-12 18:00:20 +0000476 /// Do the check specified in \a Check to all component lists and return true
477 /// if any issue is found.
Samuel Antao90927002016-04-26 14:54:23 +0000478 bool checkMappableExprComponentListsForDecl(
479 ValueDecl *VD, bool CurrentRegionOnly,
Samuel Antao6890b092016-07-28 14:25:09 +0000480 const llvm::function_ref<
481 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
482 OpenMPClauseKind)> &Check) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000483 if (isStackEmpty())
484 return false;
485 auto SI = Stack.back().first.rbegin();
486 auto SE = Stack.back().first.rend();
Samuel Antao5de996e2016-01-22 20:21:36 +0000487
488 if (SI == SE)
489 return false;
490
491 if (CurrentRegionOnly) {
492 SE = std::next(SI);
493 } else {
494 ++SI;
495 }
496
497 for (; SI != SE; ++SI) {
Samuel Antao90927002016-04-26 14:54:23 +0000498 auto MI = SI->MappedExprComponents.find(VD);
499 if (MI != SI->MappedExprComponents.end())
Samuel Antao6890b092016-07-28 14:25:09 +0000500 for (auto &L : MI->second.Components)
501 if (Check(L, MI->second.Kind))
Samuel Antao5de996e2016-01-22 20:21:36 +0000502 return true;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000503 }
Samuel Antao5de996e2016-01-22 20:21:36 +0000504 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000505 }
506
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +0000507 /// Do the check specified in \a Check to all component lists at a given level
508 /// and return true if any issue is found.
509 bool checkMappableExprComponentListsForDeclAtLevel(
510 ValueDecl *VD, unsigned Level,
511 const llvm::function_ref<
512 bool(OMPClauseMappableExprCommon::MappableExprComponentListRef,
513 OpenMPClauseKind)> &Check) {
514 if (isStackEmpty())
515 return false;
516
517 auto StartI = Stack.back().first.begin();
518 auto EndI = Stack.back().first.end();
519 if (std::distance(StartI, EndI) <= (int)Level)
520 return false;
521 std::advance(StartI, Level);
522
523 auto MI = StartI->MappedExprComponents.find(VD);
524 if (MI != StartI->MappedExprComponents.end())
525 for (auto &L : MI->second.Components)
526 if (Check(L, MI->second.Kind))
527 return true;
528 return false;
529 }
530
Samuel Antao4c8035b2016-12-12 18:00:20 +0000531 /// Create a new mappable expression component list associated with a given
532 /// declaration and initialize it with the provided list of components.
Samuel Antao90927002016-04-26 14:54:23 +0000533 void addMappableExpressionComponents(
534 ValueDecl *VD,
Samuel Antao6890b092016-07-28 14:25:09 +0000535 OMPClauseMappableExprCommon::MappableExprComponentListRef Components,
536 OpenMPClauseKind WhereFoundClauseKind) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000537 assert(!isStackEmpty() &&
Samuel Antao90927002016-04-26 14:54:23 +0000538 "Not expecting to retrieve components from a empty stack!");
Alexey Bataev4b465392017-04-26 15:06:24 +0000539 auto &MEC = Stack.back().first.back().MappedExprComponents[VD];
Samuel Antao90927002016-04-26 14:54:23 +0000540 // Create new entry and append the new components there.
Samuel Antao6890b092016-07-28 14:25:09 +0000541 MEC.Components.resize(MEC.Components.size() + 1);
542 MEC.Components.back().append(Components.begin(), Components.end());
543 MEC.Kind = WhereFoundClauseKind;
Kelvin Li0bff7af2015-11-23 05:32:03 +0000544 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000545
546 unsigned getNestingLevel() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000547 assert(!isStackEmpty());
548 return Stack.back().first.size() - 1;
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000549 }
Alexey Bataev8b427062016-05-25 12:36:08 +0000550 void addDoacrossDependClause(OMPDependClause *C, OperatorOffsetTy &OpsOffs) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000551 assert(!isStackEmpty() && Stack.back().first.size() > 1);
552 auto &StackElem = *std::next(Stack.back().first.rbegin());
553 assert(isOpenMPWorksharingDirective(StackElem.Directive));
554 StackElem.DoacrossDepends.insert({C, OpsOffs});
Alexey Bataev8b427062016-05-25 12:36:08 +0000555 }
556 llvm::iterator_range<DoacrossDependMapTy::const_iterator>
557 getDoacrossDependClauses() const {
Alexey Bataev4b465392017-04-26 15:06:24 +0000558 assert(!isStackEmpty());
559 auto &StackElem = Stack.back().first.back();
560 if (isOpenMPWorksharingDirective(StackElem.Directive)) {
561 auto &Ref = StackElem.DoacrossDepends;
Alexey Bataev8b427062016-05-25 12:36:08 +0000562 return llvm::make_range(Ref.begin(), Ref.end());
563 }
Alexey Bataev4b465392017-04-26 15:06:24 +0000564 return llvm::make_range(StackElem.DoacrossDepends.end(),
565 StackElem.DoacrossDepends.end());
Alexey Bataev8b427062016-05-25 12:36:08 +0000566 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000567};
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000568bool isParallelOrTaskRegion(OpenMPDirectiveKind DKind) {
Alexey Bataev35aaee62016-04-13 13:36:48 +0000569 return isOpenMPParallelDirective(DKind) || isOpenMPTaskingDirective(DKind) ||
570 isOpenMPTeamsDirective(DKind) || DKind == OMPD_unknown;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000571}
Alexey Bataeved09d242014-05-28 05:53:51 +0000572} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +0000573
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000574static Expr *getExprAsWritten(Expr *E) {
575 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(E))
576 E = ExprTemp->getSubExpr();
577
578 if (auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E))
579 E = MTE->GetTemporaryExpr();
580
581 while (auto *Binder = dyn_cast<CXXBindTemporaryExpr>(E))
582 E = Binder->getSubExpr();
583
584 if (auto *ICE = dyn_cast<ImplicitCastExpr>(E))
585 E = ICE->getSubExprAsWritten();
586 return E->IgnoreParens();
587}
588
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000589static ValueDecl *getCanonicalDecl(ValueDecl *D) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +0000590 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(D))
591 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
592 D = ME->getMemberDecl();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000593 auto *VD = dyn_cast<VarDecl>(D);
594 auto *FD = dyn_cast<FieldDecl>(D);
David Majnemer9d168222016-08-05 17:44:54 +0000595 if (VD != nullptr) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000596 VD = VD->getCanonicalDecl();
597 D = VD;
598 } else {
599 assert(FD);
600 FD = FD->getCanonicalDecl();
601 D = FD;
602 }
603 return D;
604}
605
David Majnemer9d168222016-08-05 17:44:54 +0000606DSAStackTy::DSAVarData DSAStackTy::getDSA(StackTy::reverse_iterator &Iter,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000607 ValueDecl *D) {
608 D = getCanonicalDecl(D);
609 auto *VD = dyn_cast<VarDecl>(D);
610 auto *FD = dyn_cast<FieldDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000611 DSAVarData DVar;
Alexey Bataev4b465392017-04-26 15:06:24 +0000612 if (isStackEmpty() || Iter == Stack.back().first.rend()) {
Alexey Bataev750a58b2014-03-18 12:19:12 +0000613 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
614 // in a region but not in construct]
615 // File-scope or namespace-scope variables referenced in called routines
616 // in the region are shared unless they appear in a threadprivate
617 // directive.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000618 if (VD && !VD->isFunctionOrMethodVarDecl() && !isa<ParmVarDecl>(D))
Alexey Bataev750a58b2014-03-18 12:19:12 +0000619 DVar.CKind = OMPC_shared;
620
621 // OpenMP [2.9.1.2, Data-sharing Attribute Rules for Variables Referenced
622 // in a region but not in construct]
623 // Variables with static storage duration that are declared in called
624 // routines in the region are shared.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000625 if (VD && VD->hasGlobalStorage())
626 DVar.CKind = OMPC_shared;
627
628 // Non-static data members are shared by default.
629 if (FD)
Alexey Bataev750a58b2014-03-18 12:19:12 +0000630 DVar.CKind = OMPC_shared;
631
Alexey Bataev758e55e2013-09-06 18:03:48 +0000632 return DVar;
633 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000634
Alexey Bataevec3da872014-01-31 05:15:34 +0000635 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
636 // in a Construct, C/C++, predetermined, p.1]
637 // Variables with automatic storage duration that are declared in a scope
638 // inside the construct are private.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000639 if (VD && isOpenMPLocal(VD, Iter) && VD->isLocalVarDecl() &&
640 (VD->getStorageClass() == SC_Auto || VD->getStorageClass() == SC_None)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +0000641 DVar.CKind = OMPC_private;
642 return DVar;
Alexey Bataevec3da872014-01-31 05:15:34 +0000643 }
644
Alexey Bataeveffbdf12017-07-21 17:24:30 +0000645 DVar.DKind = Iter->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000646 // Explicitly specified attributes and local variables with predetermined
647 // attributes.
648 if (Iter->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000649 DVar.RefExpr = Iter->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +0000650 DVar.PrivateCopy = Iter->SharingMap[D].PrivateCopy;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000651 DVar.CKind = Iter->SharingMap[D].Attributes;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +0000652 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000653 return DVar;
654 }
655
656 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
657 // in a Construct, C/C++, implicitly determined, p.1]
658 // In a parallel or task construct, the data-sharing attributes of these
659 // variables are determined by the default clause, if present.
660 switch (Iter->DefaultAttr) {
661 case DSA_shared:
662 DVar.CKind = OMPC_shared;
Alexey Bataevbae9a792014-06-27 10:37:06 +0000663 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000664 return DVar;
665 case DSA_none:
666 return DVar;
667 case DSA_unspecified:
668 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
669 // in a Construct, implicitly determined, p.2]
670 // In a parallel construct, if no default clause is present, these
671 // variables are shared.
Alexey Bataevbae9a792014-06-27 10:37:06 +0000672 DVar.ImplicitDSALoc = Iter->DefaultAttrLoc;
Alexey Bataev13314bf2014-10-09 04:18:56 +0000673 if (isOpenMPParallelDirective(DVar.DKind) ||
674 isOpenMPTeamsDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000675 DVar.CKind = OMPC_shared;
676 return DVar;
677 }
678
679 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
680 // in a Construct, implicitly determined, p.4]
681 // In a task construct, if no default clause is present, a variable that in
682 // the enclosing context is determined to be shared by all implicit tasks
683 // bound to the current team is shared.
Alexey Bataev35aaee62016-04-13 13:36:48 +0000684 if (isOpenMPTaskingDirective(DVar.DKind)) {
Alexey Bataev758e55e2013-09-06 18:03:48 +0000685 DSAVarData DVarTemp;
Alexey Bataev4b465392017-04-26 15:06:24 +0000686 auto I = Iter, E = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000687 do {
688 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000689 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables
Alexey Bataev35aaee62016-04-13 13:36:48 +0000690 // Referenced in a Construct, implicitly determined, p.6]
Alexey Bataev758e55e2013-09-06 18:03:48 +0000691 // In a task construct, if no default clause is present, a variable
692 // whose data-sharing attribute is not determined by the rules above is
693 // firstprivate.
694 DVarTemp = getDSA(I, D);
695 if (DVarTemp.CKind != OMPC_shared) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000696 DVar.RefExpr = nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +0000697 DVar.CKind = OMPC_firstprivate;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000698 return DVar;
699 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000700 } while (I != E && !isParallelOrTaskRegion(I->Directive));
Alexey Bataev758e55e2013-09-06 18:03:48 +0000701 DVar.CKind =
Alexey Bataeved09d242014-05-28 05:53:51 +0000702 (DVarTemp.CKind == OMPC_unknown) ? OMPC_firstprivate : OMPC_shared;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000703 return DVar;
704 }
705 }
706 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
707 // in a Construct, implicitly determined, p.3]
708 // For constructs other than task, if no default clause is present, these
709 // variables inherit their data-sharing attributes from the enclosing
710 // context.
Dmitry Polukhindc78bc822016-04-01 09:52:30 +0000711 return getDSA(++Iter, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000712}
713
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000714Expr *DSAStackTy::addUniqueAligned(ValueDecl *D, Expr *NewDE) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000715 assert(!isStackEmpty() && "Data sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000716 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000717 auto &StackElem = Stack.back().first.back();
718 auto It = StackElem.AlignedMap.find(D);
719 if (It == StackElem.AlignedMap.end()) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000720 assert(NewDE && "Unexpected nullptr expr to be added into aligned map");
Alexey Bataev4b465392017-04-26 15:06:24 +0000721 StackElem.AlignedMap[D] = NewDE;
Alexander Musmanf0d76e72014-05-29 14:36:25 +0000722 return nullptr;
723 } else {
724 assert(It->second && "Unexpected nullptr expr in the aligned map");
725 return It->second;
726 }
727 return nullptr;
728}
729
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000730void DSAStackTy::addLoopControlVariable(ValueDecl *D, VarDecl *Capture) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000731 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000732 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000733 auto &StackElem = Stack.back().first.back();
734 StackElem.LCVMap.insert(
735 {D, LCDeclInfo(StackElem.LCVMap.size() + 1, Capture)});
Alexey Bataev9c821032015-04-30 04:23:23 +0000736}
737
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000738DSAStackTy::LCDeclInfo DSAStackTy::isLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000739 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000740 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000741 auto &StackElem = Stack.back().first.back();
742 auto It = StackElem.LCVMap.find(D);
743 if (It != StackElem.LCVMap.end())
744 return It->second;
745 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000746}
747
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000748DSAStackTy::LCDeclInfo DSAStackTy::isParentLoopControlVariable(ValueDecl *D) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000749 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
750 "Data-sharing attributes stack is empty");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000751 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +0000752 auto &StackElem = *std::next(Stack.back().first.rbegin());
753 auto It = StackElem.LCVMap.find(D);
754 if (It != StackElem.LCVMap.end())
755 return It->second;
756 return {0, nullptr};
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000757}
758
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000759ValueDecl *DSAStackTy::getParentLoopControlVariable(unsigned I) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000760 assert(!isStackEmpty() && Stack.back().first.size() > 1 &&
761 "Data-sharing attributes stack is empty");
762 auto &StackElem = *std::next(Stack.back().first.rbegin());
763 if (StackElem.LCVMap.size() < I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000764 return nullptr;
Alexey Bataev4b465392017-04-26 15:06:24 +0000765 for (auto &Pair : StackElem.LCVMap)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +0000766 if (Pair.second.first == I)
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000767 return Pair.first;
Alexey Bataeva636c7f2015-12-23 10:27:45 +0000768 return nullptr;
Alexey Bataev9c821032015-04-30 04:23:23 +0000769}
770
Alexey Bataev90c228f2016-02-08 09:29:13 +0000771void DSAStackTy::addDSA(ValueDecl *D, Expr *E, OpenMPClauseKind A,
772 DeclRefExpr *PrivateCopy) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000773 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000774 if (A == OMPC_threadprivate) {
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000775 auto &Data = Threadprivates[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000776 Data.Attributes = A;
777 Data.RefExpr.setPointer(E);
778 Data.PrivateCopy = nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000779 } else {
Alexey Bataev4b465392017-04-26 15:06:24 +0000780 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
781 auto &Data = Stack.back().first.back().SharingMap[D];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000782 assert(Data.Attributes == OMPC_unknown || (A == Data.Attributes) ||
783 (A == OMPC_firstprivate && Data.Attributes == OMPC_lastprivate) ||
784 (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) ||
785 (isLoopControlVariable(D).first && A == OMPC_private));
786 if (A == OMPC_lastprivate && Data.Attributes == OMPC_firstprivate) {
787 Data.RefExpr.setInt(/*IntVal=*/true);
788 return;
789 }
790 const bool IsLastprivate =
791 A == OMPC_lastprivate || Data.Attributes == OMPC_lastprivate;
792 Data.Attributes = A;
793 Data.RefExpr.setPointerAndInt(E, IsLastprivate);
794 Data.PrivateCopy = PrivateCopy;
795 if (PrivateCopy) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000796 auto &Data = Stack.back().first.back().SharingMap[PrivateCopy->getDecl()];
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000797 Data.Attributes = A;
798 Data.RefExpr.setPointerAndInt(PrivateCopy, IsLastprivate);
799 Data.PrivateCopy = nullptr;
800 }
Alexey Bataev758e55e2013-09-06 18:03:48 +0000801 }
802}
803
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000804/// \brief Build a variable declaration for OpenMP loop iteration variable.
805static VarDecl *buildVarDecl(Sema &SemaRef, SourceLocation Loc, QualType Type,
806 StringRef Name, const AttrVec *Attrs = nullptr) {
807 DeclContext *DC = SemaRef.CurContext;
808 IdentifierInfo *II = &SemaRef.PP.getIdentifierTable().get(Name);
809 TypeSourceInfo *TInfo = SemaRef.Context.getTrivialTypeSourceInfo(Type, Loc);
810 VarDecl *Decl =
811 VarDecl::Create(SemaRef.Context, DC, Loc, Loc, II, Type, TInfo, SC_None);
812 if (Attrs) {
813 for (specific_attr_iterator<AlignedAttr> I(Attrs->begin()), E(Attrs->end());
814 I != E; ++I)
815 Decl->addAttr(*I);
816 }
817 Decl->setImplicit();
818 return Decl;
819}
820
821static DeclRefExpr *buildDeclRefExpr(Sema &S, VarDecl *D, QualType Ty,
822 SourceLocation Loc,
823 bool RefersToCapture = false) {
824 D->setReferenced();
825 D->markUsed(S.Context);
826 return DeclRefExpr::Create(S.getASTContext(), NestedNameSpecifierLoc(),
827 SourceLocation(), D, RefersToCapture, Loc, Ty,
828 VK_LValue);
829}
830
831void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
832 BinaryOperatorKind BOK) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000833 D = getCanonicalDecl(D);
834 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000835 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000836 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000837 "Additional reduction info may be specified only for reduction items.");
838 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
839 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000840 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000841 "Additional reduction info may be specified only once for reduction "
842 "items.");
843 ReductionData.set(BOK, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000844 Expr *&TaskgroupReductionRef =
845 Stack.back().first.back().TaskgroupReductionRef;
846 if (!TaskgroupReductionRef) {
Alexey Bataevd070a582017-10-25 15:54:04 +0000847 auto *VD = buildVarDecl(SemaRef, SR.getBegin(),
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000848 SemaRef.Context.VoidPtrTy, ".task_red.");
Alexey Bataevd070a582017-10-25 15:54:04 +0000849 TaskgroupReductionRef =
850 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000851 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000852}
853
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000854void DSAStackTy::addTaskgroupReductionData(ValueDecl *D, SourceRange SR,
855 const Expr *ReductionRef) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000856 D = getCanonicalDecl(D);
857 assert(!isStackEmpty() && "Data-sharing attributes stack is empty");
Alexey Bataevfa312f32017-07-21 18:48:21 +0000858 assert(
Richard Trieu09f14112017-07-21 21:29:35 +0000859 Stack.back().first.back().SharingMap[D].Attributes == OMPC_reduction &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000860 "Additional reduction info may be specified only for reduction items.");
861 auto &ReductionData = Stack.back().first.back().ReductionMap[D];
862 assert(ReductionData.ReductionRange.isInvalid() &&
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000863 Stack.back().first.back().Directive == OMPD_taskgroup &&
Alexey Bataevfa312f32017-07-21 18:48:21 +0000864 "Additional reduction info may be specified only once for reduction "
865 "items.");
866 ReductionData.set(ReductionRef, SR);
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000867 Expr *&TaskgroupReductionRef =
868 Stack.back().first.back().TaskgroupReductionRef;
869 if (!TaskgroupReductionRef) {
Alexey Bataevd070a582017-10-25 15:54:04 +0000870 auto *VD = buildVarDecl(SemaRef, SR.getBegin(), SemaRef.Context.VoidPtrTy,
871 ".task_red.");
872 TaskgroupReductionRef =
873 buildDeclRefExpr(SemaRef, VD, SemaRef.Context.VoidPtrTy, SR.getBegin());
Alexey Bataev3b1b8952017-07-25 15:53:26 +0000874 }
Alexey Bataevfa312f32017-07-21 18:48:21 +0000875}
876
Alexey Bataevf189cb72017-07-24 14:52:13 +0000877DSAStackTy::DSAVarData
878DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000879 BinaryOperatorKind &BOK,
880 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000881 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000882 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
883 if (Stack.back().first.empty())
884 return DSAVarData();
885 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000886 E = Stack.back().first.rend();
887 I != E; std::advance(I, 1)) {
888 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000889 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000890 continue;
891 auto &ReductionData = I->ReductionMap[D];
892 if (!ReductionData.ReductionOp ||
893 ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000894 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000895 SR = ReductionData.ReductionRange;
Alexey Bataevf87fa882017-07-21 19:26:22 +0000896 BOK = ReductionData.ReductionOp.get<ReductionData::BOKPtrType>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000897 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
898 "expression for the descriptor is not "
899 "set.");
900 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000901 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
902 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000903 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000904 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000905}
906
Alexey Bataevf189cb72017-07-24 14:52:13 +0000907DSAStackTy::DSAVarData
908DSAStackTy::getTopMostTaskgroupReductionData(ValueDecl *D, SourceRange &SR,
Alexey Bataev88202be2017-07-27 13:20:36 +0000909 const Expr *&ReductionRef,
910 Expr *&TaskgroupDescriptor) {
Alexey Bataevfa312f32017-07-21 18:48:21 +0000911 D = getCanonicalDecl(D);
Alexey Bataevf189cb72017-07-24 14:52:13 +0000912 assert(!isStackEmpty() && "Data-sharing attributes stack is empty.");
913 if (Stack.back().first.empty())
914 return DSAVarData();
915 for (auto I = std::next(Stack.back().first.rbegin(), 1),
Alexey Bataevfa312f32017-07-21 18:48:21 +0000916 E = Stack.back().first.rend();
917 I != E; std::advance(I, 1)) {
918 auto &Data = I->SharingMap[D];
Alexey Bataevf189cb72017-07-24 14:52:13 +0000919 if (Data.Attributes != OMPC_reduction || I->Directive != OMPD_taskgroup)
Alexey Bataevfa312f32017-07-21 18:48:21 +0000920 continue;
921 auto &ReductionData = I->ReductionMap[D];
922 if (!ReductionData.ReductionOp ||
923 !ReductionData.ReductionOp.is<const Expr *>())
Alexey Bataevf189cb72017-07-24 14:52:13 +0000924 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000925 SR = ReductionData.ReductionRange;
926 ReductionRef = ReductionData.ReductionOp.get<const Expr *>();
Alexey Bataev88202be2017-07-27 13:20:36 +0000927 assert(I->TaskgroupReductionRef && "taskgroup reduction reference "
928 "expression for the descriptor is not "
929 "set.");
930 TaskgroupDescriptor = I->TaskgroupReductionRef;
Alexey Bataevf189cb72017-07-24 14:52:13 +0000931 return DSAVarData(OMPD_taskgroup, OMPC_reduction, Data.RefExpr.getPointer(),
932 Data.PrivateCopy, I->DefaultAttrLoc);
Alexey Bataevfa312f32017-07-21 18:48:21 +0000933 }
Alexey Bataevf189cb72017-07-24 14:52:13 +0000934 return DSAVarData();
Alexey Bataevfa312f32017-07-21 18:48:21 +0000935}
936
Alexey Bataeved09d242014-05-28 05:53:51 +0000937bool DSAStackTy::isOpenMPLocal(VarDecl *D, StackTy::reverse_iterator Iter) {
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +0000938 D = D->getCanonicalDecl();
Alexey Bataev852525d2018-03-02 17:17:12 +0000939 if (!isStackEmpty()) {
Alexey Bataev4b465392017-04-26 15:06:24 +0000940 reverse_iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000941 Scope *TopScope = nullptr;
Alexey Bataev852525d2018-03-02 17:17:12 +0000942 while (I != E && !isParallelOrTaskRegion(I->Directive) &&
943 !isOpenMPTargetExecutionDirective(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000944 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000945 if (I == E)
946 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000947 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000948 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000949 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000950 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000951 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000952 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000953 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000954}
955
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000956DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
957 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000958 DSAVarData DVar;
959
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000960 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000961 auto TI = Threadprivates.find(D);
962 if (TI != Threadprivates.end()) {
963 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000964 DVar.CKind = OMPC_threadprivate;
965 return DVar;
Alexey Bataev817d7f32017-11-14 21:01:01 +0000966 } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
967 DVar.RefExpr = buildDeclRefExpr(
968 SemaRef, VD, D->getType().getNonReferenceType(),
969 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
970 DVar.CKind = OMPC_threadprivate;
971 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev852525d2018-03-02 17:17:12 +0000972 return DVar;
973 }
974 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
975 // in a Construct, C/C++, predetermined, p.1]
976 // Variables appearing in threadprivate directives are threadprivate.
977 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
978 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
979 SemaRef.getLangOpts().OpenMPUseTLS &&
980 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
981 (VD && VD->getStorageClass() == SC_Register &&
982 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
983 DVar.RefExpr = buildDeclRefExpr(
984 SemaRef, VD, D->getType().getNonReferenceType(), D->getLocation());
985 DVar.CKind = OMPC_threadprivate;
986 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
987 return DVar;
988 }
989 if (SemaRef.getLangOpts().OpenMPCUDAMode && VD &&
990 VD->isLocalVarDeclOrParm() && !isStackEmpty() &&
991 !isLoopControlVariable(D).first) {
992 auto IterTarget =
993 std::find_if(Stack.back().first.rbegin(), Stack.back().first.rend(),
994 [](const SharingMapTy &Data) {
995 return isOpenMPTargetExecutionDirective(Data.Directive);
996 });
997 if (IterTarget != Stack.back().first.rend()) {
998 auto ParentIterTarget = std::next(IterTarget, 1);
999 auto Iter = Stack.back().first.rbegin();
1000 while (Iter != ParentIterTarget) {
1001 if (isOpenMPLocal(VD, Iter)) {
1002 DVar.RefExpr =
1003 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1004 D->getLocation());
1005 DVar.CKind = OMPC_threadprivate;
1006 return DVar;
1007 }
1008 std::advance(Iter, 1);
1009 }
1010 if (!isClauseParsingMode() || IterTarget != Stack.back().first.rbegin()) {
1011 auto DSAIter = IterTarget->SharingMap.find(D);
1012 if (DSAIter != IterTarget->SharingMap.end() &&
1013 isOpenMPPrivate(DSAIter->getSecond().Attributes)) {
1014 DVar.RefExpr = DSAIter->getSecond().RefExpr.getPointer();
1015 DVar.CKind = OMPC_threadprivate;
1016 return DVar;
1017 } else if (!SemaRef.IsOpenMPCapturedByRef(
1018 D, std::distance(ParentIterTarget,
1019 Stack.back().first.rend()))) {
1020 DVar.RefExpr =
1021 buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
1022 IterTarget->ConstructLoc);
1023 DVar.CKind = OMPC_threadprivate;
1024 return DVar;
1025 }
1026 }
1027 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001028 }
1029
Alexey Bataev4b465392017-04-26 15:06:24 +00001030 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001031 // Not in OpenMP execution region and top scope was already checked.
1032 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00001033
Alexey Bataev758e55e2013-09-06 18:03:48 +00001034 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001035 // in a Construct, C/C++, predetermined, p.4]
1036 // Static data members are shared.
1037 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1038 // in a Construct, C/C++, predetermined, p.7]
1039 // Variables with static storage duration that are declared in a scope
1040 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001041 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001042 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001043 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001044 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +00001045 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001046
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001047 DVar.CKind = OMPC_shared;
1048 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001049 }
1050
1051 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00001052 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
1053 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001054 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1055 // in a Construct, C/C++, predetermined, p.6]
1056 // Variables with const qualified type having no mutable member are
1057 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001058 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +00001059 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +00001060 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1061 if (auto *CTD = CTSD->getSpecializedTemplate())
1062 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001063 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +00001064 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1065 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001066 // Variables with const-qualified type having no mutable member may be
1067 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001068 DSAVarData DVarTemp = hasDSA(
1069 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
1070 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001071 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
Alexey Bataev9a757382018-02-16 19:16:54 +00001072 return DVarTemp;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001073
Alexey Bataev758e55e2013-09-06 18:03:48 +00001074 DVar.CKind = OMPC_shared;
1075 return DVar;
1076 }
1077
Alexey Bataev758e55e2013-09-06 18:03:48 +00001078 // Explicitly specified attributes and local variables with predetermined
1079 // attributes.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001080 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001081 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001082 if (FromParent && I != EndI)
1083 std::advance(I, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001084 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001085 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +00001086 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001087 DVar.CKind = I->SharingMap[D].Attributes;
1088 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001089 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001090 }
1091
1092 return DVar;
1093}
1094
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001095DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1096 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001097 if (isStackEmpty()) {
1098 StackTy::reverse_iterator I;
1099 return getDSA(I, D);
1100 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001101 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001102 auto StartI = Stack.back().first.rbegin();
1103 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001104 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001105 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001106 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001107}
1108
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001109DSAStackTy::DSAVarData
1110DSAStackTy::hasDSA(ValueDecl *D,
1111 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1112 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1113 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001114 if (isStackEmpty())
1115 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001116 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001117 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001118 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001119 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001120 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001121 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001122 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001123 continue;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001124 auto NewI = I;
1125 DSAVarData DVar = getDSA(NewI, D);
1126 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001127 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001128 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001129 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001130}
1131
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001132DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1133 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1134 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1135 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001136 if (isStackEmpty())
1137 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001138 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001139 auto StartI = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001140 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001141 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001142 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001143 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001144 return {};
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001145 auto NewI = StartI;
1146 DSAVarData DVar = getDSA(NewI, D);
1147 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001148}
1149
Alexey Bataevaac108a2015-06-23 04:51:00 +00001150bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001151 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001152 unsigned Level, bool NotLastprivate) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001153 if (isStackEmpty())
1154 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001155 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001156 auto StartI = Stack.back().first.begin();
1157 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001158 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001159 return false;
1160 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001161 return (StartI->SharingMap.count(D) > 0) &&
1162 StartI->SharingMap[D].RefExpr.getPointer() &&
1163 CPred(StartI->SharingMap[D].Attributes) &&
1164 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +00001165}
1166
Samuel Antao4be30e92015-10-02 17:14:03 +00001167bool DSAStackTy::hasExplicitDirective(
1168 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1169 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001170 if (isStackEmpty())
1171 return false;
1172 auto StartI = Stack.back().first.begin();
1173 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001174 if (std::distance(StartI, EndI) <= (int)Level)
1175 return false;
1176 std::advance(StartI, Level);
1177 return DPred(StartI->Directive);
1178}
1179
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001180bool DSAStackTy::hasDirective(
1181 const llvm::function_ref<bool(OpenMPDirectiveKind,
1182 const DeclarationNameInfo &, SourceLocation)>
1183 &DPred,
1184 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +00001185 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001186 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001187 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001188 auto StartI = std::next(Stack.back().first.rbegin());
1189 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001190 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001191 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001192 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1193 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1194 return true;
1195 }
1196 return false;
1197}
1198
Alexey Bataev758e55e2013-09-06 18:03:48 +00001199void Sema::InitDataSharingAttributesStack() {
1200 VarDataSharingAttributesStack = new DSAStackTy(*this);
1201}
1202
1203#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1204
Alexey Bataev4b465392017-04-26 15:06:24 +00001205void Sema::pushOpenMPFunctionRegion() {
1206 DSAStack->pushFunction();
1207}
1208
1209void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1210 DSAStack->popFunction(OldFSI);
1211}
1212
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001213bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001214 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1215
1216 auto &Ctx = getASTContext();
1217 bool IsByRef = true;
1218
1219 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001220 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001221 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001222
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001223 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001224 // This table summarizes how a given variable should be passed to the device
1225 // given its type and the clauses where it appears. This table is based on
1226 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1227 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1228 //
1229 // =========================================================================
1230 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1231 // | |(tofrom:scalar)| | pvt | | | |
1232 // =========================================================================
1233 // | scl | | | | - | | bycopy|
1234 // | scl | | - | x | - | - | bycopy|
1235 // | scl | | x | - | - | - | null |
1236 // | scl | x | | | - | | byref |
1237 // | scl | x | - | x | - | - | bycopy|
1238 // | scl | x | x | - | - | - | null |
1239 // | scl | | - | - | - | x | byref |
1240 // | scl | x | - | - | - | x | byref |
1241 //
1242 // | agg | n.a. | | | - | | byref |
1243 // | agg | n.a. | - | x | - | - | byref |
1244 // | agg | n.a. | x | - | - | - | null |
1245 // | agg | n.a. | - | - | - | x | byref |
1246 // | agg | n.a. | - | - | - | x[] | byref |
1247 //
1248 // | ptr | n.a. | | | - | | bycopy|
1249 // | ptr | n.a. | - | x | - | - | bycopy|
1250 // | ptr | n.a. | x | - | - | - | null |
1251 // | ptr | n.a. | - | - | - | x | byref |
1252 // | ptr | n.a. | - | - | - | x[] | bycopy|
1253 // | ptr | n.a. | - | - | x | | bycopy|
1254 // | ptr | n.a. | - | - | x | x | bycopy|
1255 // | ptr | n.a. | - | - | x | x[] | bycopy|
1256 // =========================================================================
1257 // Legend:
1258 // scl - scalar
1259 // ptr - pointer
1260 // agg - aggregate
1261 // x - applies
1262 // - - invalid in this combination
1263 // [] - mapped with an array section
1264 // byref - should be mapped by reference
1265 // byval - should be mapped by value
1266 // null - initialize a local variable to null on the device
1267 //
1268 // Observations:
1269 // - All scalar declarations that show up in a map clause have to be passed
1270 // by reference, because they may have been mapped in the enclosing data
1271 // environment.
1272 // - If the scalar value does not fit the size of uintptr, it has to be
1273 // passed by reference, regardless the result in the table above.
1274 // - For pointers mapped by value that have either an implicit map or an
1275 // array section, the runtime library may pass the NULL value to the
1276 // device instead of the value passed to it by the compiler.
1277
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001278 if (Ty->isReferenceType())
1279 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001280
1281 // Locate map clauses and see if the variable being captured is referred to
1282 // in any of those clauses. Here we only care about variables, not fields,
1283 // because fields are part of aggregates.
1284 bool IsVariableUsedInMapClause = false;
1285 bool IsVariableAssociatedWithSection = false;
1286
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001287 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1288 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001289 MapExprComponents,
1290 OpenMPClauseKind WhereFoundClauseKind) {
1291 // Only the map clause information influences how a variable is
1292 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001293 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001294 if (WhereFoundClauseKind != OMPC_map)
1295 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001296
1297 auto EI = MapExprComponents.rbegin();
1298 auto EE = MapExprComponents.rend();
1299
1300 assert(EI != EE && "Invalid map expression!");
1301
1302 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1303 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1304
1305 ++EI;
1306 if (EI == EE)
1307 return false;
1308
1309 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1310 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1311 isa<MemberExpr>(EI->getAssociatedExpression())) {
1312 IsVariableAssociatedWithSection = true;
1313 // There is nothing more we need to know about this variable.
1314 return true;
1315 }
1316
1317 // Keep looking for more map info.
1318 return false;
1319 });
1320
1321 if (IsVariableUsedInMapClause) {
1322 // If variable is identified in a map clause it is always captured by
1323 // reference except if it is a pointer that is dereferenced somehow.
1324 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1325 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001326 // By default, all the data that has a scalar type is mapped by copy
1327 // (except for reduction variables).
1328 IsByRef =
1329 !Ty->isScalarType() ||
1330 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1331 DSAStack->hasExplicitDSA(
1332 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001333 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001334 }
1335
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001336 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001337 IsByRef =
1338 !DSAStack->hasExplicitDSA(
1339 D,
1340 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1341 Level, /*NotLastprivate=*/true) &&
1342 // If the variable is artificial and must be captured by value - try to
1343 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001344 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1345 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001346 }
1347
Samuel Antao86ace552016-04-27 22:40:57 +00001348 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001349 // and alignment, because the runtime library only deals with uintptr types.
1350 // If it does not fit the uintptr size, we need to pass the data by reference
1351 // instead.
1352 if (!IsByRef &&
1353 (Ctx.getTypeSizeInChars(Ty) >
1354 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001355 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001356 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001357 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001358
1359 return IsByRef;
1360}
1361
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001362unsigned Sema::getOpenMPNestingLevel() const {
1363 assert(getLangOpts().OpenMP);
1364 return DSAStack->getNestingLevel();
1365}
1366
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001367bool Sema::isInOpenMPTargetExecutionDirective() const {
1368 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1369 !DSAStack->isClauseParsingMode()) ||
1370 DSAStack->hasDirective(
1371 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1372 SourceLocation) -> bool {
1373 return isOpenMPTargetExecutionDirective(K);
1374 },
1375 false);
1376}
1377
Alexey Bataev90c228f2016-02-08 09:29:13 +00001378VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001379 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001380 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001381
1382 // If we are attempting to capture a global variable in a directive with
1383 // 'target' we return true so that this global is also mapped to the device.
1384 //
1385 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1386 // then it should not be captured. Therefore, an extra check has to be
1387 // inserted here once support for 'declare target' is added.
1388 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001389 auto *VD = dyn_cast<VarDecl>(D);
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001390 if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective())
1391 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001392
Alexey Bataev48977c32015-08-04 08:10:48 +00001393 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1394 (!DSAStack->isClauseParsingMode() ||
1395 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001396 auto &&Info = DSAStack->isLoopControlVariable(D);
1397 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001398 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001399 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001400 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001401 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001402 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001403 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001404 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001405 DVarPrivate = DSAStack->hasDSA(
1406 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1407 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001408 if (DVarPrivate.CKind != OMPC_unknown)
1409 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001410 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001411 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001412}
1413
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001414void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1415 unsigned Level) const {
1416 SmallVector<OpenMPDirectiveKind, 4> Regions;
1417 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1418 FunctionScopesIndex -= Regions.size();
1419}
1420
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001421bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001422 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1423 return DSAStack->hasExplicitDSA(
Alexey Bataev88202be2017-07-27 13:20:36 +00001424 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1425 Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001426 (DSAStack->isClauseParsingMode() &&
1427 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001428 // Consider taskgroup reduction descriptor variable a private to avoid
1429 // possible capture in the region.
1430 (DSAStack->hasExplicitDirective(
1431 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1432 Level) &&
1433 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001434}
1435
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001436void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
1437 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1438 D = getCanonicalDecl(D);
1439 OpenMPClauseKind OMPC = OMPC_unknown;
1440 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1441 const unsigned NewLevel = I - 1;
1442 if (DSAStack->hasExplicitDSA(D,
1443 [&OMPC](const OpenMPClauseKind K) {
1444 if (isOpenMPPrivate(K)) {
1445 OMPC = K;
1446 return true;
1447 }
1448 return false;
1449 },
1450 NewLevel))
1451 break;
1452 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1453 D, NewLevel,
1454 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1455 OpenMPClauseKind) { return true; })) {
1456 OMPC = OMPC_map;
1457 break;
1458 }
1459 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1460 NewLevel)) {
1461 OMPC = OMPC_firstprivate;
1462 break;
1463 }
1464 }
1465 if (OMPC != OMPC_unknown)
1466 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1467}
1468
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001469bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001470 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1471 // Return true if the current level is no longer enclosed in a target region.
1472
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001473 auto *VD = dyn_cast<VarDecl>(D);
1474 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001475 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1476 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001477}
1478
Alexey Bataeved09d242014-05-28 05:53:51 +00001479void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001480
1481void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1482 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001483 Scope *CurScope, SourceLocation Loc) {
1484 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001485 PushExpressionEvaluationContext(
1486 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001487}
1488
Alexey Bataevaac108a2015-06-23 04:51:00 +00001489void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1490 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001491}
1492
Alexey Bataevaac108a2015-06-23 04:51:00 +00001493void Sema::EndOpenMPClause() {
1494 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001495}
1496
Alexey Bataev758e55e2013-09-06 18:03:48 +00001497void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001498 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1499 // A variable of class type (or array thereof) that appears in a lastprivate
1500 // clause requires an accessible, unambiguous default constructor for the
1501 // class type, unless the list item is also specified in a firstprivate
1502 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001503 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001504 for (auto *C : D->clauses()) {
1505 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1506 SmallVector<Expr *, 8> PrivateCopies;
1507 for (auto *DE : Clause->varlists()) {
1508 if (DE->isValueDependent() || DE->isTypeDependent()) {
1509 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001510 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001511 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001512 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001513 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1514 QualType Type = VD->getType().getNonReferenceType();
1515 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001516 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001517 // Generate helper private variable and initialize it with the
1518 // default value. The address of the original variable is replaced
1519 // by the address of the new private variable in CodeGen. This new
1520 // variable is not added to IdResolver, so the code in the OpenMP
1521 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001522 auto *VDPrivate = buildVarDecl(
1523 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001524 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001525 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001526 if (VDPrivate->isInvalidDecl())
1527 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001528 PrivateCopies.push_back(buildDeclRefExpr(
1529 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001530 } else {
1531 // The variable is also a firstprivate, so initialization sequence
1532 // for private copy is generated already.
1533 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001534 }
1535 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001536 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001537 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001538 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001539 }
1540 }
1541 }
1542
Alexey Bataev758e55e2013-09-06 18:03:48 +00001543 DSAStack->pop();
1544 DiscardCleanupsInEvaluationContext();
1545 PopExpressionEvaluationContext();
1546}
1547
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001548static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1549 Expr *NumIterations, Sema &SemaRef,
1550 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001551
Alexey Bataeva769e072013-03-22 06:34:35 +00001552namespace {
1553
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001554class VarDeclFilterCCC : public CorrectionCandidateCallback {
1555private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001556 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001557
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001558public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001559 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001560 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001561 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001562 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001563 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001564 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1565 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001566 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001567 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001568 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001569};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001570
1571class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1572private:
1573 Sema &SemaRef;
1574
1575public:
1576 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1577 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1578 NamedDecl *ND = Candidate.getCorrectionDecl();
Kelvin Li59e3d192017-11-30 18:52:06 +00001579 if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001580 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1581 SemaRef.getCurScope());
1582 }
1583 return false;
1584 }
1585};
1586
Alexey Bataeved09d242014-05-28 05:53:51 +00001587} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001588
1589ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1590 CXXScopeSpec &ScopeSpec,
1591 const DeclarationNameInfo &Id) {
1592 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1593 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1594
1595 if (Lookup.isAmbiguous())
1596 return ExprError();
1597
1598 VarDecl *VD;
1599 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001600 if (TypoCorrection Corrected = CorrectTypo(
1601 Id, LookupOrdinaryName, CurScope, nullptr,
1602 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001603 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001604 PDiag(Lookup.empty()
1605 ? diag::err_undeclared_var_use_suggest
1606 : diag::err_omp_expected_var_arg_suggest)
1607 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001608 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001609 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001610 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1611 : diag::err_omp_expected_var_arg)
1612 << Id.getName();
1613 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001614 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001615 } else {
1616 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001617 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001618 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1619 return ExprError();
1620 }
1621 }
1622 Lookup.suppressDiagnostics();
1623
1624 // OpenMP [2.9.2, Syntax, C/C++]
1625 // Variables must be file-scope, namespace-scope, or static block-scope.
1626 if (!VD->hasGlobalStorage()) {
1627 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001628 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1629 bool IsDecl =
1630 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001631 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001632 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1633 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001634 return ExprError();
1635 }
1636
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001637 VarDecl *CanonicalVD = VD->getCanonicalDecl();
George Burgess IV00f70bd2018-03-01 05:43:23 +00001638 NamedDecl *ND = CanonicalVD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001639 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1640 // A threadprivate directive for file-scope variables must appear outside
1641 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001642 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1643 !getCurLexicalContext()->isTranslationUnit()) {
1644 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001645 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1646 bool IsDecl =
1647 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1648 Diag(VD->getLocation(),
1649 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1650 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001651 return ExprError();
1652 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001653 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1654 // A threadprivate directive for static class member variables must appear
1655 // in the class definition, in the same scope in which the member
1656 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001657 if (CanonicalVD->isStaticDataMember() &&
1658 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1659 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001660 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1661 bool IsDecl =
1662 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1663 Diag(VD->getLocation(),
1664 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1665 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001666 return ExprError();
1667 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001668 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1669 // A threadprivate directive for namespace-scope variables must appear
1670 // outside any definition or declaration other than the namespace
1671 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001672 if (CanonicalVD->getDeclContext()->isNamespace() &&
1673 (!getCurLexicalContext()->isFileContext() ||
1674 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1675 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001676 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1677 bool IsDecl =
1678 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1679 Diag(VD->getLocation(),
1680 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1681 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001682 return ExprError();
1683 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001684 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1685 // A threadprivate directive for static block-scope variables must appear
1686 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001687 if (CanonicalVD->isStaticLocal() && CurScope &&
1688 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001689 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001690 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1691 bool IsDecl =
1692 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1693 Diag(VD->getLocation(),
1694 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1695 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001696 return ExprError();
1697 }
1698
1699 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1700 // A threadprivate directive must lexically precede all references to any
1701 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001702 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001703 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001704 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001705 return ExprError();
1706 }
1707
1708 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001709 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1710 SourceLocation(), VD,
1711 /*RefersToEnclosingVariableOrCapture=*/false,
1712 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001713}
1714
Alexey Bataeved09d242014-05-28 05:53:51 +00001715Sema::DeclGroupPtrTy
1716Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1717 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001718 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001719 CurContext->addDecl(D);
1720 return DeclGroupPtrTy::make(DeclGroupRef(D));
1721 }
David Blaikie0403cb12016-01-15 23:43:25 +00001722 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001723}
1724
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001725namespace {
1726class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1727 Sema &SemaRef;
1728
1729public:
1730 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001731 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001732 if (VD->hasLocalStorage()) {
1733 SemaRef.Diag(E->getLocStart(),
1734 diag::err_omp_local_var_in_threadprivate_init)
1735 << E->getSourceRange();
1736 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1737 << VD << VD->getSourceRange();
1738 return true;
1739 }
1740 }
1741 return false;
1742 }
1743 bool VisitStmt(const Stmt *S) {
1744 for (auto Child : S->children()) {
1745 if (Child && Visit(Child))
1746 return true;
1747 }
1748 return false;
1749 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001750 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001751};
1752} // namespace
1753
Alexey Bataeved09d242014-05-28 05:53:51 +00001754OMPThreadPrivateDecl *
1755Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001756 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001757 for (auto &RefExpr : VarList) {
1758 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001759 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1760 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001761
Alexey Bataev376b4a42016-02-09 09:41:09 +00001762 // Mark variable as used.
1763 VD->setReferenced();
1764 VD->markUsed(Context);
1765
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001766 QualType QType = VD->getType();
1767 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1768 // It will be analyzed later.
1769 Vars.push_back(DE);
1770 continue;
1771 }
1772
Alexey Bataeva769e072013-03-22 06:34:35 +00001773 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1774 // A threadprivate variable must not have an incomplete type.
1775 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001776 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001777 continue;
1778 }
1779
1780 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1781 // A threadprivate variable must not have a reference type.
1782 if (VD->getType()->isReferenceType()) {
1783 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001784 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1785 bool IsDecl =
1786 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1787 Diag(VD->getLocation(),
1788 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1789 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001790 continue;
1791 }
1792
Samuel Antaof8b50122015-07-13 22:54:53 +00001793 // Check if this is a TLS variable. If TLS is not being supported, produce
1794 // the corresponding diagnostic.
1795 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1796 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1797 getLangOpts().OpenMPUseTLS &&
1798 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001799 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1800 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001801 Diag(ILoc, diag::err_omp_var_thread_local)
1802 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001803 bool IsDecl =
1804 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1805 Diag(VD->getLocation(),
1806 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1807 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001808 continue;
1809 }
1810
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001811 // Check if initial value of threadprivate variable reference variable with
1812 // local storage (it is not supported by runtime).
1813 if (auto Init = VD->getAnyInitializer()) {
1814 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001815 if (Checker.Visit(Init))
1816 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001817 }
1818
Alexey Bataeved09d242014-05-28 05:53:51 +00001819 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001820 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001821 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1822 Context, SourceRange(Loc, Loc)));
1823 if (auto *ML = Context.getASTMutationListener())
1824 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001825 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001826 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001827 if (!Vars.empty()) {
1828 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1829 Vars);
1830 D->setAccess(AS_public);
1831 }
1832 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001833}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001834
Alexey Bataev7ff55242014-06-19 09:13:45 +00001835static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001836 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001837 bool IsLoopIterVar = false) {
1838 if (DVar.RefExpr) {
1839 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1840 << getOpenMPClauseName(DVar.CKind);
1841 return;
1842 }
1843 enum {
1844 PDSA_StaticMemberShared,
1845 PDSA_StaticLocalVarShared,
1846 PDSA_LoopIterVarPrivate,
1847 PDSA_LoopIterVarLinear,
1848 PDSA_LoopIterVarLastprivate,
1849 PDSA_ConstVarShared,
1850 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001851 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001852 PDSA_LocalVarPrivate,
1853 PDSA_Implicit
1854 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001855 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001856 auto ReportLoc = D->getLocation();
1857 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001858 if (IsLoopIterVar) {
1859 if (DVar.CKind == OMPC_private)
1860 Reason = PDSA_LoopIterVarPrivate;
1861 else if (DVar.CKind == OMPC_lastprivate)
1862 Reason = PDSA_LoopIterVarLastprivate;
1863 else
1864 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001865 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1866 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001867 Reason = PDSA_TaskVarFirstprivate;
1868 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001869 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001870 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001871 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001872 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001873 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001874 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001875 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001876 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001877 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001878 ReportHint = true;
1879 Reason = PDSA_LocalVarPrivate;
1880 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001881 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001882 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001883 << Reason << ReportHint
1884 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1885 } else if (DVar.ImplicitDSALoc.isValid()) {
1886 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1887 << getOpenMPClauseName(DVar.CKind);
1888 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001889}
1890
Alexey Bataev758e55e2013-09-06 18:03:48 +00001891namespace {
1892class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1893 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001894 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001895 bool ErrorFound;
1896 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001897 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001898 llvm::SmallVector<Expr *, 8> ImplicitMap;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001899 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001900 llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00001901
Alexey Bataev758e55e2013-09-06 18:03:48 +00001902public:
1903 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001904 if (E->isTypeDependent() || E->isValueDependent() ||
1905 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1906 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001907 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001908 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001909 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001910 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00001911 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001912
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001913 auto DVar = Stack->getTopDSA(VD, false);
1914 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001915 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00001916 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001917
Alexey Bataevafe50572017-10-06 17:00:28 +00001918 // Skip internally declared static variables.
1919 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
1920 return;
1921
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001922 auto ELoc = E->getExprLoc();
1923 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001924 // The default(none) clause requires that each variable that is referenced
1925 // in the construct, and does not have a predetermined data-sharing
1926 // attribute, must have its data-sharing attribute explicitly determined
1927 // by being listed in a data-sharing attribute clause.
1928 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001929 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001930 VarsWithInheritedDSA.count(VD) == 0) {
1931 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001932 return;
1933 }
1934
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001935 if (isOpenMPTargetExecutionDirective(DKind) &&
1936 !Stack->isLoopControlVariable(VD).first) {
1937 if (!Stack->checkMappableExprComponentListsForDecl(
1938 VD, /*CurrentRegionOnly=*/true,
1939 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1940 StackComponents,
1941 OpenMPClauseKind) {
1942 // Variable is used if it has been marked as an array, array
1943 // section or the variable iself.
1944 return StackComponents.size() == 1 ||
1945 std::all_of(
1946 std::next(StackComponents.rbegin()),
1947 StackComponents.rend(),
1948 [](const OMPClauseMappableExprCommon::
1949 MappableComponent &MC) {
1950 return MC.getAssociatedDeclaration() ==
1951 nullptr &&
1952 (isa<OMPArraySectionExpr>(
1953 MC.getAssociatedExpression()) ||
1954 isa<ArraySubscriptExpr>(
1955 MC.getAssociatedExpression()));
1956 });
1957 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001958 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001959 // By default lambdas are captured as firstprivates.
1960 if (const auto *RD =
1961 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001962 IsFirstprivate = RD->isLambda();
1963 IsFirstprivate =
1964 IsFirstprivate ||
1965 (VD->getType().getNonReferenceType()->isScalarType() &&
1966 Stack->getDefaultDMA() != DMA_tofrom_scalar);
1967 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001968 ImplicitFirstprivate.emplace_back(E);
1969 else
1970 ImplicitMap.emplace_back(E);
1971 return;
1972 }
1973 }
1974
Alexey Bataev758e55e2013-09-06 18:03:48 +00001975 // OpenMP [2.9.3.6, Restrictions, p.2]
1976 // A list item that appears in a reduction clause of the innermost
1977 // enclosing worksharing or parallel construct may not be accessed in an
1978 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001979 DVar = Stack->hasInnermostDSA(
1980 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1981 [](OpenMPDirectiveKind K) -> bool {
1982 return isOpenMPParallelDirective(K) ||
1983 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1984 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001985 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001986 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001987 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001988 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1989 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001990 return;
1991 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001992
1993 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001994 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001995 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1996 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001997 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001998 }
1999 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002000 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00002001 if (E->isTypeDependent() || E->isValueDependent() ||
2002 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
2003 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002004 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002005 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002006 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002007 if (!FD)
2008 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002009 auto DVar = Stack->getTopDSA(FD, false);
2010 // Check if the variable has explicit DSA set and stop analysis if it
2011 // so.
2012 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
2013 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002014
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002015 if (isOpenMPTargetExecutionDirective(DKind) &&
2016 !Stack->isLoopControlVariable(FD).first &&
2017 !Stack->checkMappableExprComponentListsForDecl(
2018 FD, /*CurrentRegionOnly=*/true,
2019 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
2020 StackComponents,
2021 OpenMPClauseKind) {
2022 return isa<CXXThisExpr>(
2023 cast<MemberExpr>(
2024 StackComponents.back().getAssociatedExpression())
2025 ->getBase()
2026 ->IgnoreParens());
2027 })) {
2028 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
2029 // A bit-field cannot appear in a map clause.
2030 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002031 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002032 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002033 ImplicitMap.emplace_back(E);
2034 return;
2035 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002036
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002037 auto ELoc = E->getExprLoc();
2038 // OpenMP [2.9.3.6, Restrictions, p.2]
2039 // A list item that appears in a reduction clause of the innermost
2040 // enclosing worksharing or parallel construct may not be accessed in
2041 // an explicit task.
2042 DVar = Stack->hasInnermostDSA(
2043 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
2044 [](OpenMPDirectiveKind K) -> bool {
2045 return isOpenMPParallelDirective(K) ||
2046 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2047 },
2048 /*FromParent=*/true);
2049 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2050 ErrorFound = true;
2051 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2052 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
2053 return;
2054 }
2055
2056 // Define implicit data-sharing attributes for task.
2057 DVar = Stack->getImplicitDSA(FD, false);
2058 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2059 !Stack->isLoopControlVariable(FD).first)
2060 ImplicitFirstprivate.push_back(E);
2061 return;
2062 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002063 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002064 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002065 if (!CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
2066 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002067 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002068 auto *VD = cast<ValueDecl>(
2069 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2070 if (!Stack->checkMappableExprComponentListsForDecl(
2071 VD, /*CurrentRegionOnly=*/true,
2072 [&CurComponents](
2073 OMPClauseMappableExprCommon::MappableExprComponentListRef
2074 StackComponents,
2075 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002076 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002077 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002078 for (const auto &SC : llvm::reverse(StackComponents)) {
2079 // Do both expressions have the same kind?
2080 if (CCI->getAssociatedExpression()->getStmtClass() !=
2081 SC.getAssociatedExpression()->getStmtClass())
2082 if (!(isa<OMPArraySectionExpr>(
2083 SC.getAssociatedExpression()) &&
2084 isa<ArraySubscriptExpr>(
2085 CCI->getAssociatedExpression())))
2086 return false;
2087
2088 Decl *CCD = CCI->getAssociatedDeclaration();
2089 Decl *SCD = SC.getAssociatedDeclaration();
2090 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2091 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2092 if (SCD != CCD)
2093 return false;
2094 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002095 if (CCI == CCE)
2096 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002097 }
2098 return true;
2099 })) {
2100 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002101 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002102 } else
2103 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002104 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002105 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002106 for (auto *C : S->clauses()) {
2107 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002108 // for task|target directives.
2109 // Skip analysis of arguments of implicitly defined map clause for target
2110 // directives.
2111 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2112 C->isImplicit())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002113 for (auto *CC : C->children()) {
2114 if (CC)
2115 Visit(CC);
2116 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002117 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002118 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002119 }
2120 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002121 for (auto *C : S->children()) {
2122 if (C && !isa<OMPExecutableDirective>(C))
2123 Visit(C);
2124 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002125 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002126
2127 bool isErrorFound() { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002128 ArrayRef<Expr *> getImplicitFirstprivate() const {
2129 return ImplicitFirstprivate;
2130 }
2131 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002132 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002133 return VarsWithInheritedDSA;
2134 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002135
Alexey Bataev7ff55242014-06-19 09:13:45 +00002136 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2137 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002138};
Alexey Bataeved09d242014-05-28 05:53:51 +00002139} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002140
Alexey Bataevbae9a792014-06-27 10:37:06 +00002141void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002142 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002143 case OMPD_parallel:
2144 case OMPD_parallel_for:
2145 case OMPD_parallel_for_simd:
2146 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002147 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002148 case OMPD_teams_distribute:
2149 case OMPD_teams_distribute_simd: {
Alexey Bataev9959db52014-05-06 10:08:46 +00002150 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002151 QualType KmpInt32PtrTy =
2152 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002153 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002154 std::make_pair(".global_tid.", KmpInt32PtrTy),
2155 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2156 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002157 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002158 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2159 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002160 break;
2161 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002162 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002163 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002164 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002165 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002166 case OMPD_target_teams_distribute:
2167 case OMPD_target_teams_distribute_simd: {
Alexey Bataev8451efa2018-01-15 19:06:12 +00002168 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2169 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2170 FunctionProtoType::ExtProtoInfo EPI;
2171 EPI.Variadic = true;
2172 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2173 Sema::CapturedParamNameType Params[] = {
2174 std::make_pair(".global_tid.", KmpInt32Ty),
2175 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2176 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2177 std::make_pair(".copy_fn.",
2178 Context.getPointerType(CopyFnType).withConst()),
2179 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2180 std::make_pair(StringRef(), QualType()) // __context with shared vars
2181 };
2182 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2183 Params);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002184 // Mark this captured region as inlined, because we don't use outlined
2185 // function directly.
2186 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2187 AlwaysInlineAttr::CreateImplicit(
2188 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002189 Sema::CapturedParamNameType ParamsTarget[] = {
2190 std::make_pair(StringRef(), QualType()) // __context with shared vars
2191 };
2192 // Start a captured region for 'target' with no implicit parameters.
2193 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2194 ParamsTarget);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002195 QualType KmpInt32PtrTy =
2196 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002197 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002198 std::make_pair(".global_tid.", KmpInt32PtrTy),
2199 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2200 std::make_pair(StringRef(), QualType()) // __context with shared vars
2201 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002202 // Start a captured region for 'teams' or 'parallel'. Both regions have
2203 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002204 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002205 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002206 break;
2207 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002208 case OMPD_target:
2209 case OMPD_target_simd: {
2210 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2211 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2212 FunctionProtoType::ExtProtoInfo EPI;
2213 EPI.Variadic = true;
2214 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2215 Sema::CapturedParamNameType Params[] = {
2216 std::make_pair(".global_tid.", KmpInt32Ty),
2217 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2218 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2219 std::make_pair(".copy_fn.",
2220 Context.getPointerType(CopyFnType).withConst()),
2221 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2222 std::make_pair(StringRef(), QualType()) // __context with shared vars
2223 };
2224 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2225 Params);
2226 // Mark this captured region as inlined, because we don't use outlined
2227 // function directly.
2228 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2229 AlwaysInlineAttr::CreateImplicit(
2230 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2231 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2232 std::make_pair(StringRef(), QualType()));
2233 break;
2234 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002235 case OMPD_simd:
2236 case OMPD_for:
2237 case OMPD_for_simd:
2238 case OMPD_sections:
2239 case OMPD_section:
2240 case OMPD_single:
2241 case OMPD_master:
2242 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002243 case OMPD_taskgroup:
2244 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002245 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002246 case OMPD_ordered:
2247 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002248 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002249 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002250 std::make_pair(StringRef(), QualType()) // __context with shared vars
2251 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002252 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2253 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002254 break;
2255 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002256 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002257 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002258 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2259 FunctionProtoType::ExtProtoInfo EPI;
2260 EPI.Variadic = true;
2261 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002262 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002263 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002264 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2265 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2266 std::make_pair(".copy_fn.",
2267 Context.getPointerType(CopyFnType).withConst()),
2268 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002269 std::make_pair(StringRef(), QualType()) // __context with shared vars
2270 };
2271 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2272 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002273 // Mark this captured region as inlined, because we don't use outlined
2274 // function directly.
2275 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2276 AlwaysInlineAttr::CreateImplicit(
2277 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002278 break;
2279 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002280 case OMPD_taskloop:
2281 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002282 QualType KmpInt32Ty =
2283 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2284 QualType KmpUInt64Ty =
2285 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
2286 QualType KmpInt64Ty =
2287 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
2288 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2289 FunctionProtoType::ExtProtoInfo EPI;
2290 EPI.Variadic = true;
2291 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002292 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002293 std::make_pair(".global_tid.", KmpInt32Ty),
2294 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2295 std::make_pair(".privates.",
2296 Context.VoidPtrTy.withConst().withRestrict()),
2297 std::make_pair(
2298 ".copy_fn.",
2299 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2300 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2301 std::make_pair(".lb.", KmpUInt64Ty),
2302 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
2303 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002304 std::make_pair(".reductions.",
2305 Context.VoidPtrTy.withConst().withRestrict()),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002306 std::make_pair(StringRef(), QualType()) // __context with shared vars
2307 };
2308 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2309 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002310 // Mark this captured region as inlined, because we don't use outlined
2311 // function directly.
2312 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2313 AlwaysInlineAttr::CreateImplicit(
2314 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002315 break;
2316 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002317 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002318 case OMPD_distribute_parallel_for: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00002319 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2320 QualType KmpInt32PtrTy =
2321 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2322 Sema::CapturedParamNameType Params[] = {
2323 std::make_pair(".global_tid.", KmpInt32PtrTy),
2324 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2325 std::make_pair(".previous.lb.", Context.getSizeType()),
2326 std::make_pair(".previous.ub.", Context.getSizeType()),
2327 std::make_pair(StringRef(), QualType()) // __context with shared vars
2328 };
2329 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2330 Params);
2331 break;
2332 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002333 case OMPD_target_teams_distribute_parallel_for:
2334 case OMPD_target_teams_distribute_parallel_for_simd: {
Carlo Bertolli52978c32018-01-03 21:12:44 +00002335 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2336 QualType KmpInt32PtrTy =
2337 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2338
Alexey Bataev8451efa2018-01-15 19:06:12 +00002339 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2340 FunctionProtoType::ExtProtoInfo EPI;
2341 EPI.Variadic = true;
2342 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2343 Sema::CapturedParamNameType Params[] = {
2344 std::make_pair(".global_tid.", KmpInt32Ty),
2345 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2346 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2347 std::make_pair(".copy_fn.",
2348 Context.getPointerType(CopyFnType).withConst()),
2349 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2350 std::make_pair(StringRef(), QualType()) // __context with shared vars
2351 };
2352 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2353 Params);
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00002354 // Mark this captured region as inlined, because we don't use outlined
2355 // function directly.
2356 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2357 AlwaysInlineAttr::CreateImplicit(
2358 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Carlo Bertolli52978c32018-01-03 21:12:44 +00002359 Sema::CapturedParamNameType ParamsTarget[] = {
2360 std::make_pair(StringRef(), QualType()) // __context with shared vars
2361 };
2362 // Start a captured region for 'target' with no implicit parameters.
2363 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2364 ParamsTarget);
2365
2366 Sema::CapturedParamNameType ParamsTeams[] = {
2367 std::make_pair(".global_tid.", KmpInt32PtrTy),
2368 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2369 std::make_pair(StringRef(), QualType()) // __context with shared vars
2370 };
2371 // Start a captured region for 'target' with no implicit parameters.
2372 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2373 ParamsTeams);
2374
2375 Sema::CapturedParamNameType ParamsParallel[] = {
2376 std::make_pair(".global_tid.", KmpInt32PtrTy),
2377 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2378 std::make_pair(".previous.lb.", Context.getSizeType()),
2379 std::make_pair(".previous.ub.", Context.getSizeType()),
2380 std::make_pair(StringRef(), QualType()) // __context with shared vars
2381 };
2382 // Start a captured region for 'teams' or 'parallel'. Both regions have
2383 // the same implicit parameters.
2384 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2385 ParamsParallel);
2386 break;
2387 }
2388
Alexey Bataev46506272017-12-05 17:41:34 +00002389 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00002390 case OMPD_teams_distribute_parallel_for_simd: {
Carlo Bertolli62fae152017-11-20 20:46:39 +00002391 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2392 QualType KmpInt32PtrTy =
2393 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2394
2395 Sema::CapturedParamNameType ParamsTeams[] = {
2396 std::make_pair(".global_tid.", KmpInt32PtrTy),
2397 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2398 std::make_pair(StringRef(), QualType()) // __context with shared vars
2399 };
2400 // Start a captured region for 'target' with no implicit parameters.
2401 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2402 ParamsTeams);
2403
2404 Sema::CapturedParamNameType ParamsParallel[] = {
2405 std::make_pair(".global_tid.", KmpInt32PtrTy),
2406 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2407 std::make_pair(".previous.lb.", Context.getSizeType()),
2408 std::make_pair(".previous.ub.", Context.getSizeType()),
2409 std::make_pair(StringRef(), QualType()) // __context with shared vars
2410 };
2411 // Start a captured region for 'teams' or 'parallel'. Both regions have
2412 // the same implicit parameters.
2413 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2414 ParamsParallel);
2415 break;
2416 }
Alexey Bataev7828b252017-11-21 17:08:48 +00002417 case OMPD_target_update:
2418 case OMPD_target_enter_data:
2419 case OMPD_target_exit_data: {
2420 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2421 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2422 FunctionProtoType::ExtProtoInfo EPI;
2423 EPI.Variadic = true;
2424 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2425 Sema::CapturedParamNameType Params[] = {
2426 std::make_pair(".global_tid.", KmpInt32Ty),
2427 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2428 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2429 std::make_pair(".copy_fn.",
2430 Context.getPointerType(CopyFnType).withConst()),
2431 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2432 std::make_pair(StringRef(), QualType()) // __context with shared vars
2433 };
2434 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2435 Params);
2436 // Mark this captured region as inlined, because we don't use outlined
2437 // function directly.
2438 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2439 AlwaysInlineAttr::CreateImplicit(
2440 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2441 break;
2442 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002443 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002444 case OMPD_taskyield:
2445 case OMPD_barrier:
2446 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002447 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002448 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002449 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002450 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002451 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002452 case OMPD_declare_target:
2453 case OMPD_end_declare_target:
Alexey Bataev9959db52014-05-06 10:08:46 +00002454 llvm_unreachable("OpenMP Directive is not allowed");
2455 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002456 llvm_unreachable("Unknown OpenMP directive");
2457 }
2458}
2459
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002460int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2461 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2462 getOpenMPCaptureRegions(CaptureRegions, DKind);
2463 return CaptureRegions.size();
2464}
2465
Alexey Bataev3392d762016-02-16 11:18:12 +00002466static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002467 Expr *CaptureExpr, bool WithInit,
2468 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002469 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002470 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002471 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002472 QualType Ty = Init->getType();
2473 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002474 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00002475 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002476 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00002477 Ty = C.getPointerType(Ty);
2478 ExprResult Res =
2479 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2480 if (!Res.isUsable())
2481 return nullptr;
2482 Init = Res.get();
2483 }
Alexey Bataev61205072016-03-02 04:57:40 +00002484 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002485 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002486 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2487 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002488 if (!WithInit)
2489 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00002490 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002491 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002492 return CED;
2493}
2494
Alexey Bataev61205072016-03-02 04:57:40 +00002495static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2496 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002497 OMPCapturedExprDecl *CD;
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002498 if (auto *VD = S.IsOpenMPCapturedDecl(D)) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002499 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002500 } else {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002501 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2502 /*AsExpression=*/false);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002503 }
Alexey Bataev3392d762016-02-16 11:18:12 +00002504 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002505 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002506}
2507
Alexey Bataev5a3af132016-03-29 08:58:54 +00002508static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002509 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002510 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002511 OMPCapturedExprDecl *CD = buildCaptureDecl(
2512 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2513 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00002514 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2515 CaptureExpr->getExprLoc());
2516 }
2517 ExprResult Res = Ref;
2518 if (!S.getLangOpts().CPlusPlus &&
2519 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002520 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002521 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002522 if (!Res.isUsable())
2523 return ExprError();
2524 }
2525 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002526}
2527
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002528namespace {
2529// OpenMP directives parsed in this section are represented as a
2530// CapturedStatement with an associated statement. If a syntax error
2531// is detected during the parsing of the associated statement, the
2532// compiler must abort processing and close the CapturedStatement.
2533//
2534// Combined directives such as 'target parallel' have more than one
2535// nested CapturedStatements. This RAII ensures that we unwind out
2536// of all the nested CapturedStatements when an error is found.
2537class CaptureRegionUnwinderRAII {
2538private:
2539 Sema &S;
2540 bool &ErrorFound;
2541 OpenMPDirectiveKind DKind;
2542
2543public:
2544 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2545 OpenMPDirectiveKind DKind)
2546 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2547 ~CaptureRegionUnwinderRAII() {
2548 if (ErrorFound) {
2549 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2550 while (--ThisCaptureLevel >= 0)
2551 S.ActOnCapturedRegionError();
2552 }
2553 }
2554};
2555} // namespace
2556
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002557StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2558 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002559 bool ErrorFound = false;
2560 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2561 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002562 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002563 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002564 return StmtError();
2565 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002566
Alexey Bataev2ba67042017-11-28 21:11:44 +00002567 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2568 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00002569 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002570 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002571 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002572 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002573 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002574 for (auto *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002575 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2576 Clause->getClauseKind() == OMPC_in_reduction) {
2577 // Capture taskgroup task_reduction descriptors inside the tasking regions
2578 // with the corresponding in_reduction items.
2579 auto *IRC = cast<OMPInReductionClause>(Clause);
2580 for (auto *E : IRC->taskgroup_descriptors())
2581 if (E)
2582 MarkDeclarationsReferencedInExpr(E);
2583 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002584 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002585 Clause->getClauseKind() == OMPC_copyprivate ||
2586 (getLangOpts().OpenMPUseTLS &&
2587 getASTContext().getTargetInfo().isTLSSupported() &&
2588 Clause->getClauseKind() == OMPC_copyin)) {
2589 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002590 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002591 for (auto *VarRef : Clause->children()) {
2592 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002593 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002594 }
2595 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002596 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00002597 } else if (CaptureRegions.size() > 1 ||
2598 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002599 if (auto *C = OMPClauseWithPreInit::get(Clause))
2600 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002601 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2602 if (auto *E = C->getPostUpdateExpr())
2603 MarkDeclarationsReferencedInExpr(E);
2604 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002605 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002606 if (Clause->getClauseKind() == OMPC_schedule)
2607 SC = cast<OMPScheduleClause>(Clause);
2608 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002609 OC = cast<OMPOrderedClause>(Clause);
2610 else if (Clause->getClauseKind() == OMPC_linear)
2611 LCs.push_back(cast<OMPLinearClause>(Clause));
2612 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002613 // OpenMP, 2.7.1 Loop Construct, Restrictions
2614 // The nonmonotonic modifier cannot be specified if an ordered clause is
2615 // specified.
2616 if (SC &&
2617 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2618 SC->getSecondScheduleModifier() ==
2619 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2620 OC) {
2621 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2622 ? SC->getFirstScheduleModifierLoc()
2623 : SC->getSecondScheduleModifierLoc(),
2624 diag::err_omp_schedule_nonmonotonic_ordered)
2625 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2626 ErrorFound = true;
2627 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002628 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2629 for (auto *C : LCs) {
2630 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2631 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2632 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002633 ErrorFound = true;
2634 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002635 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2636 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2637 OC->getNumForLoops()) {
2638 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2639 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2640 ErrorFound = true;
2641 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002642 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002643 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002644 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002645 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00002646 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002647 // Mark all variables in private list clauses as used in inner region.
2648 // Required for proper codegen of combined directives.
2649 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00002650 if (ThisCaptureRegion != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002651 for (auto *C : PICs) {
2652 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2653 // Find the particular capture region for the clause if the
2654 // directive is a combined one with multiple capture regions.
2655 // If the directive is not a combined one, the capture region
2656 // associated with the clause is OMPD_unknown and is generated
2657 // only once.
2658 if (CaptureRegion == ThisCaptureRegion ||
2659 CaptureRegion == OMPD_unknown) {
2660 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2661 for (auto *D : DS->decls())
2662 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2663 }
2664 }
2665 }
2666 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002667 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002668 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002669 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002670}
2671
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002672static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2673 OpenMPDirectiveKind CancelRegion,
2674 SourceLocation StartLoc) {
2675 // CancelRegion is only needed for cancel and cancellation_point.
2676 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2677 return false;
2678
2679 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2680 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2681 return false;
2682
2683 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2684 << getOpenMPDirectiveName(CancelRegion);
2685 return true;
2686}
2687
2688static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002689 OpenMPDirectiveKind CurrentRegion,
2690 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002691 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002692 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002693 if (Stack->getCurScope()) {
2694 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002695 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002696 bool NestingProhibited = false;
2697 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002698 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002699 enum {
2700 NoRecommend,
2701 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002702 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002703 ShouldBeInTargetRegion,
2704 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002705 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002706 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002707 // OpenMP [2.16, Nesting of Regions]
2708 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002709 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002710 // An ordered construct with the simd clause is the only OpenMP
2711 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002712 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002713 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2714 // message.
2715 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2716 ? diag::err_omp_prohibited_region_simd
2717 : diag::warn_omp_nesting_simd);
2718 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002719 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002720 if (ParentRegion == OMPD_atomic) {
2721 // OpenMP [2.16, Nesting of Regions]
2722 // OpenMP constructs may not be nested inside an atomic region.
2723 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2724 return true;
2725 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002726 if (CurrentRegion == OMPD_section) {
2727 // OpenMP [2.7.2, sections Construct, Restrictions]
2728 // Orphaned section directives are prohibited. That is, the section
2729 // directives must appear within the sections construct and must not be
2730 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002731 if (ParentRegion != OMPD_sections &&
2732 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002733 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2734 << (ParentRegion != OMPD_unknown)
2735 << getOpenMPDirectiveName(ParentRegion);
2736 return true;
2737 }
2738 return false;
2739 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002740 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002741 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002742 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002743 if (ParentRegion == OMPD_unknown &&
2744 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002745 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002746 if (CurrentRegion == OMPD_cancellation_point ||
2747 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002748 // OpenMP [2.16, Nesting of Regions]
2749 // A cancellation point construct for which construct-type-clause is
2750 // taskgroup must be nested inside a task construct. A cancellation
2751 // point construct for which construct-type-clause is not taskgroup must
2752 // be closely nested inside an OpenMP construct that matches the type
2753 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002754 // A cancel construct for which construct-type-clause is taskgroup must be
2755 // nested inside a task construct. A cancel construct for which
2756 // construct-type-clause is not taskgroup must be closely nested inside an
2757 // OpenMP construct that matches the type specified in
2758 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002759 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002760 !((CancelRegion == OMPD_parallel &&
2761 (ParentRegion == OMPD_parallel ||
2762 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002763 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002764 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002765 ParentRegion == OMPD_target_parallel_for ||
2766 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00002767 ParentRegion == OMPD_teams_distribute_parallel_for ||
2768 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002769 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2770 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002771 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2772 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002773 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002774 // OpenMP [2.16, Nesting of Regions]
2775 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002776 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002777 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002778 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002779 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2780 // OpenMP [2.16, Nesting of Regions]
2781 // A critical region may not be nested (closely or otherwise) inside a
2782 // critical region with the same name. Note that this restriction is not
2783 // sufficient to prevent deadlock.
2784 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002785 bool DeadLock = Stack->hasDirective(
2786 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2787 const DeclarationNameInfo &DNI,
2788 SourceLocation Loc) -> bool {
2789 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2790 PreviousCriticalLoc = Loc;
2791 return true;
2792 } else
2793 return false;
2794 },
2795 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002796 if (DeadLock) {
2797 SemaRef.Diag(StartLoc,
2798 diag::err_omp_prohibited_region_critical_same_name)
2799 << CurrentName.getName();
2800 if (PreviousCriticalLoc.isValid())
2801 SemaRef.Diag(PreviousCriticalLoc,
2802 diag::note_omp_previous_critical_region);
2803 return true;
2804 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002805 } else if (CurrentRegion == OMPD_barrier) {
2806 // OpenMP [2.16, Nesting of Regions]
2807 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002808 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002809 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2810 isOpenMPTaskingDirective(ParentRegion) ||
2811 ParentRegion == OMPD_master ||
2812 ParentRegion == OMPD_critical ||
2813 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002814 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002815 !isOpenMPParallelDirective(CurrentRegion) &&
2816 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002817 // OpenMP [2.16, Nesting of Regions]
2818 // A worksharing region may not be closely nested inside a worksharing,
2819 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002820 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2821 isOpenMPTaskingDirective(ParentRegion) ||
2822 ParentRegion == OMPD_master ||
2823 ParentRegion == OMPD_critical ||
2824 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002825 Recommend = ShouldBeInParallelRegion;
2826 } else if (CurrentRegion == OMPD_ordered) {
2827 // OpenMP [2.16, Nesting of Regions]
2828 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002829 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002830 // An ordered region must be closely nested inside a loop region (or
2831 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002832 // OpenMP [2.8.1,simd Construct, Restrictions]
2833 // An ordered construct with the simd clause is the only OpenMP construct
2834 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002835 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002836 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002837 !(isOpenMPSimdDirective(ParentRegion) ||
2838 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002839 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002840 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002841 // OpenMP [2.16, Nesting of Regions]
2842 // If specified, a teams construct must be contained within a target
2843 // construct.
2844 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002845 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002846 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002847 }
Kelvin Libf594a52016-12-17 05:48:59 +00002848 if (!NestingProhibited &&
2849 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2850 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2851 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002852 // OpenMP [2.16, Nesting of Regions]
2853 // distribute, parallel, parallel sections, parallel workshare, and the
2854 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2855 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002856 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2857 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002858 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002859 }
David Majnemer9d168222016-08-05 17:44:54 +00002860 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002861 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002862 // OpenMP 4.5 [2.17 Nesting of Regions]
2863 // The region associated with the distribute construct must be strictly
2864 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002865 NestingProhibited =
2866 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002867 Recommend = ShouldBeInTeamsRegion;
2868 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002869 if (!NestingProhibited &&
2870 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2871 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2872 // OpenMP 4.5 [2.17 Nesting of Regions]
2873 // If a target, target update, target data, target enter data, or
2874 // target exit data construct is encountered during execution of a
2875 // target region, the behavior is unspecified.
2876 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002877 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2878 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002879 if (isOpenMPTargetExecutionDirective(K)) {
2880 OffendingRegion = K;
2881 return true;
2882 } else
2883 return false;
2884 },
2885 false /* don't skip top directive */);
2886 CloseNesting = false;
2887 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002888 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002889 if (OrphanSeen) {
2890 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2891 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2892 } else {
2893 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2894 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2895 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2896 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002897 return true;
2898 }
2899 }
2900 return false;
2901}
2902
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002903static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2904 ArrayRef<OMPClause *> Clauses,
2905 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2906 bool ErrorFound = false;
2907 unsigned NamedModifiersNumber = 0;
2908 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2909 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002910 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002911 for (const auto *C : Clauses) {
2912 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2913 // At most one if clause without a directive-name-modifier can appear on
2914 // the directive.
2915 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2916 if (FoundNameModifiers[CurNM]) {
2917 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2918 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2919 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2920 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002921 } else if (CurNM != OMPD_unknown) {
2922 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002923 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002924 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002925 FoundNameModifiers[CurNM] = IC;
2926 if (CurNM == OMPD_unknown)
2927 continue;
2928 // Check if the specified name modifier is allowed for the current
2929 // directive.
2930 // At most one if clause with the particular directive-name-modifier can
2931 // appear on the directive.
2932 bool MatchFound = false;
2933 for (auto NM : AllowedNameModifiers) {
2934 if (CurNM == NM) {
2935 MatchFound = true;
2936 break;
2937 }
2938 }
2939 if (!MatchFound) {
2940 S.Diag(IC->getNameModifierLoc(),
2941 diag::err_omp_wrong_if_directive_name_modifier)
2942 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2943 ErrorFound = true;
2944 }
2945 }
2946 }
2947 // If any if clause on the directive includes a directive-name-modifier then
2948 // all if clauses on the directive must include a directive-name-modifier.
2949 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2950 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2951 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2952 diag::err_omp_no_more_if_clause);
2953 } else {
2954 std::string Values;
2955 std::string Sep(", ");
2956 unsigned AllowedCnt = 0;
2957 unsigned TotalAllowedNum =
2958 AllowedNameModifiers.size() - NamedModifiersNumber;
2959 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2960 ++Cnt) {
2961 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2962 if (!FoundNameModifiers[NM]) {
2963 Values += "'";
2964 Values += getOpenMPDirectiveName(NM);
2965 Values += "'";
2966 if (AllowedCnt + 2 == TotalAllowedNum)
2967 Values += " or ";
2968 else if (AllowedCnt + 1 != TotalAllowedNum)
2969 Values += Sep;
2970 ++AllowedCnt;
2971 }
2972 }
2973 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2974 diag::err_omp_unnamed_if_clause)
2975 << (TotalAllowedNum > 1) << Values;
2976 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002977 for (auto Loc : NameModifierLoc) {
2978 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2979 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002980 ErrorFound = true;
2981 }
2982 return ErrorFound;
2983}
2984
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002985StmtResult Sema::ActOnOpenMPExecutableDirective(
2986 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2987 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2988 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002989 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002990 // First check CancelRegion which is then used in checkNestingOfRegions.
2991 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2992 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002993 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002994 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002995
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002996 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002997 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002998 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002999 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00003000 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003001 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
3002
3003 // Check default data sharing attributes for referenced variables.
3004 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00003005 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
3006 Stmt *S = AStmt;
3007 while (--ThisCaptureLevel >= 0)
3008 S = cast<CapturedStmt>(S)->getCapturedStmt();
3009 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00003010 if (DSAChecker.isErrorFound())
3011 return StmtError();
3012 // Generate list of implicitly defined firstprivate variables.
3013 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00003014
Alexey Bataev88202be2017-07-27 13:20:36 +00003015 SmallVector<Expr *, 4> ImplicitFirstprivates(
3016 DSAChecker.getImplicitFirstprivate().begin(),
3017 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003018 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
3019 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00003020 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
3021 for (auto *C : Clauses) {
3022 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
3023 for (auto *E : IRC->taskgroup_descriptors())
3024 if (E)
3025 ImplicitFirstprivates.emplace_back(E);
3026 }
3027 }
3028 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003029 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00003030 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
3031 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00003032 ClausesWithImplicit.push_back(Implicit);
3033 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00003034 ImplicitFirstprivates.size();
Alexey Bataev68446b72014-07-18 07:47:19 +00003035 } else
3036 ErrorFound = true;
3037 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00003038 if (!ImplicitMaps.empty()) {
3039 if (OMPClause *Implicit = ActOnOpenMPMapClause(
3040 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
3041 SourceLocation(), SourceLocation(), ImplicitMaps,
3042 SourceLocation(), SourceLocation(), SourceLocation())) {
3043 ClausesWithImplicit.emplace_back(Implicit);
3044 ErrorFound |=
3045 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
3046 } else
3047 ErrorFound = true;
3048 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003049 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003050
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003051 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003052 switch (Kind) {
3053 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003054 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3055 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003056 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003057 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003058 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003059 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3060 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003061 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003062 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003063 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3064 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003065 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003066 case OMPD_for_simd:
3067 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3068 EndLoc, VarsWithInheritedDSA);
3069 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003070 case OMPD_sections:
3071 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3072 EndLoc);
3073 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003074 case OMPD_section:
3075 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003076 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003077 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3078 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003079 case OMPD_single:
3080 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3081 EndLoc);
3082 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003083 case OMPD_master:
3084 assert(ClausesWithImplicit.empty() &&
3085 "No clauses are allowed for 'omp master' directive");
3086 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3087 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003088 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003089 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3090 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003091 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003092 case OMPD_parallel_for:
3093 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3094 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003095 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003096 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003097 case OMPD_parallel_for_simd:
3098 Res = ActOnOpenMPParallelForSimdDirective(
3099 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003100 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003101 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003102 case OMPD_parallel_sections:
3103 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3104 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003105 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003106 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003107 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003108 Res =
3109 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003110 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003111 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003112 case OMPD_taskyield:
3113 assert(ClausesWithImplicit.empty() &&
3114 "No clauses are allowed for 'omp taskyield' directive");
3115 assert(AStmt == nullptr &&
3116 "No associated statement allowed for 'omp taskyield' directive");
3117 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3118 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003119 case OMPD_barrier:
3120 assert(ClausesWithImplicit.empty() &&
3121 "No clauses are allowed for 'omp barrier' directive");
3122 assert(AStmt == nullptr &&
3123 "No associated statement allowed for 'omp barrier' directive");
3124 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3125 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003126 case OMPD_taskwait:
3127 assert(ClausesWithImplicit.empty() &&
3128 "No clauses are allowed for 'omp taskwait' directive");
3129 assert(AStmt == nullptr &&
3130 "No associated statement allowed for 'omp taskwait' directive");
3131 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3132 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003133 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003134 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3135 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003136 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003137 case OMPD_flush:
3138 assert(AStmt == nullptr &&
3139 "No associated statement allowed for 'omp flush' directive");
3140 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3141 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003142 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003143 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3144 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003145 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003146 case OMPD_atomic:
3147 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3148 EndLoc);
3149 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003150 case OMPD_teams:
3151 Res =
3152 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3153 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003154 case OMPD_target:
3155 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3156 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003157 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003158 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003159 case OMPD_target_parallel:
3160 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3161 StartLoc, EndLoc);
3162 AllowedNameModifiers.push_back(OMPD_target);
3163 AllowedNameModifiers.push_back(OMPD_parallel);
3164 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003165 case OMPD_target_parallel_for:
3166 Res = ActOnOpenMPTargetParallelForDirective(
3167 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3168 AllowedNameModifiers.push_back(OMPD_target);
3169 AllowedNameModifiers.push_back(OMPD_parallel);
3170 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003171 case OMPD_cancellation_point:
3172 assert(ClausesWithImplicit.empty() &&
3173 "No clauses are allowed for 'omp cancellation point' directive");
3174 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3175 "cancellation point' directive");
3176 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3177 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003178 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003179 assert(AStmt == nullptr &&
3180 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003181 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3182 CancelRegion);
3183 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003184 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003185 case OMPD_target_data:
3186 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3187 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003188 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003189 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003190 case OMPD_target_enter_data:
3191 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003192 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003193 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3194 break;
Samuel Antao72590762016-01-19 20:04:50 +00003195 case OMPD_target_exit_data:
3196 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003197 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003198 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3199 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003200 case OMPD_taskloop:
3201 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3202 EndLoc, VarsWithInheritedDSA);
3203 AllowedNameModifiers.push_back(OMPD_taskloop);
3204 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003205 case OMPD_taskloop_simd:
3206 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3207 EndLoc, VarsWithInheritedDSA);
3208 AllowedNameModifiers.push_back(OMPD_taskloop);
3209 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003210 case OMPD_distribute:
3211 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3212 EndLoc, VarsWithInheritedDSA);
3213 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003214 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003215 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3216 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003217 AllowedNameModifiers.push_back(OMPD_target_update);
3218 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003219 case OMPD_distribute_parallel_for:
3220 Res = ActOnOpenMPDistributeParallelForDirective(
3221 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3222 AllowedNameModifiers.push_back(OMPD_parallel);
3223 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003224 case OMPD_distribute_parallel_for_simd:
3225 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3226 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3227 AllowedNameModifiers.push_back(OMPD_parallel);
3228 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003229 case OMPD_distribute_simd:
3230 Res = ActOnOpenMPDistributeSimdDirective(
3231 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3232 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003233 case OMPD_target_parallel_for_simd:
3234 Res = ActOnOpenMPTargetParallelForSimdDirective(
3235 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3236 AllowedNameModifiers.push_back(OMPD_target);
3237 AllowedNameModifiers.push_back(OMPD_parallel);
3238 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003239 case OMPD_target_simd:
3240 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3241 EndLoc, VarsWithInheritedDSA);
3242 AllowedNameModifiers.push_back(OMPD_target);
3243 break;
Kelvin Li02532872016-08-05 14:37:37 +00003244 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003245 Res = ActOnOpenMPTeamsDistributeDirective(
3246 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003247 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003248 case OMPD_teams_distribute_simd:
3249 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3250 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3251 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003252 case OMPD_teams_distribute_parallel_for_simd:
3253 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3254 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3255 AllowedNameModifiers.push_back(OMPD_parallel);
3256 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003257 case OMPD_teams_distribute_parallel_for:
3258 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3259 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3260 AllowedNameModifiers.push_back(OMPD_parallel);
3261 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003262 case OMPD_target_teams:
3263 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3264 EndLoc);
3265 AllowedNameModifiers.push_back(OMPD_target);
3266 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003267 case OMPD_target_teams_distribute:
3268 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3269 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3270 AllowedNameModifiers.push_back(OMPD_target);
3271 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003272 case OMPD_target_teams_distribute_parallel_for:
3273 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3274 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3275 AllowedNameModifiers.push_back(OMPD_target);
3276 AllowedNameModifiers.push_back(OMPD_parallel);
3277 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003278 case OMPD_target_teams_distribute_parallel_for_simd:
3279 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3280 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3281 AllowedNameModifiers.push_back(OMPD_target);
3282 AllowedNameModifiers.push_back(OMPD_parallel);
3283 break;
Kelvin Lida681182017-01-10 18:08:18 +00003284 case OMPD_target_teams_distribute_simd:
3285 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3286 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3287 AllowedNameModifiers.push_back(OMPD_target);
3288 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003289 case OMPD_declare_target:
3290 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003291 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003292 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003293 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003294 llvm_unreachable("OpenMP Directive is not allowed");
3295 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003296 llvm_unreachable("Unknown OpenMP directive");
3297 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003298
Alexey Bataev4acb8592014-07-07 13:01:15 +00003299 for (auto P : VarsWithInheritedDSA) {
3300 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3301 << P.first << P.second->getSourceRange();
3302 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003303 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3304
3305 if (!AllowedNameModifiers.empty())
3306 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3307 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003308
Alexey Bataeved09d242014-05-28 05:53:51 +00003309 if (ErrorFound)
3310 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003311 return Res;
3312}
3313
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003314Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3315 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003316 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003317 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3318 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003319 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003320 assert(Linears.size() == LinModifiers.size());
3321 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003322 if (!DG || DG.get().isNull())
3323 return DeclGroupPtrTy();
3324
3325 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003326 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003327 return DG;
3328 }
3329 auto *ADecl = DG.get().getSingleDecl();
3330 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3331 ADecl = FTD->getTemplatedDecl();
3332
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003333 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3334 if (!FD) {
3335 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003336 return DeclGroupPtrTy();
3337 }
3338
Alexey Bataev2af33e32016-04-07 12:45:37 +00003339 // OpenMP [2.8.2, declare simd construct, Description]
3340 // The parameter of the simdlen clause must be a constant positive integer
3341 // expression.
3342 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003343 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003344 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003345 // OpenMP [2.8.2, declare simd construct, Description]
3346 // The special this pointer can be used as if was one of the arguments to the
3347 // function in any of the linear, aligned, or uniform clauses.
3348 // The uniform clause declares one or more arguments to have an invariant
3349 // value for all concurrent invocations of the function in the execution of a
3350 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00003351 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3352 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003353 for (auto *E : Uniforms) {
3354 E = E->IgnoreParenImpCasts();
3355 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3356 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3357 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3358 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003359 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3360 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003361 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003362 }
3363 if (isa<CXXThisExpr>(E)) {
3364 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003365 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003366 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003367 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3368 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003369 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003370 // OpenMP [2.8.2, declare simd construct, Description]
3371 // The aligned clause declares that the object to which each list item points
3372 // is aligned to the number of bytes expressed in the optional parameter of
3373 // the aligned clause.
3374 // The special this pointer can be used as if was one of the arguments to the
3375 // function in any of the linear, aligned, or uniform clauses.
3376 // The type of list items appearing in the aligned clause must be array,
3377 // pointer, reference to array, or reference to pointer.
3378 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3379 Expr *AlignedThis = nullptr;
3380 for (auto *E : Aligneds) {
3381 E = E->IgnoreParenImpCasts();
3382 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3383 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3384 auto *CanonPVD = PVD->getCanonicalDecl();
3385 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3386 FD->getParamDecl(PVD->getFunctionScopeIndex())
3387 ->getCanonicalDecl() == CanonPVD) {
3388 // OpenMP [2.8.1, simd construct, Restrictions]
3389 // A list-item cannot appear in more than one aligned clause.
3390 if (AlignedArgs.count(CanonPVD) > 0) {
3391 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3392 << 1 << E->getSourceRange();
3393 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3394 diag::note_omp_explicit_dsa)
3395 << getOpenMPClauseName(OMPC_aligned);
3396 continue;
3397 }
3398 AlignedArgs[CanonPVD] = E;
3399 QualType QTy = PVD->getType()
3400 .getNonReferenceType()
3401 .getUnqualifiedType()
3402 .getCanonicalType();
3403 const Type *Ty = QTy.getTypePtrOrNull();
3404 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3405 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3406 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3407 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3408 }
3409 continue;
3410 }
3411 }
3412 if (isa<CXXThisExpr>(E)) {
3413 if (AlignedThis) {
3414 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3415 << 2 << E->getSourceRange();
3416 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3417 << getOpenMPClauseName(OMPC_aligned);
3418 }
3419 AlignedThis = E;
3420 continue;
3421 }
3422 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3423 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3424 }
3425 // The optional parameter of the aligned clause, alignment, must be a constant
3426 // positive integer expression. If no optional parameter is specified,
3427 // implementation-defined default alignments for SIMD instructions on the
3428 // target platforms are assumed.
3429 SmallVector<Expr *, 4> NewAligns;
3430 for (auto *E : Alignments) {
3431 ExprResult Align;
3432 if (E)
3433 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3434 NewAligns.push_back(Align.get());
3435 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003436 // OpenMP [2.8.2, declare simd construct, Description]
3437 // The linear clause declares one or more list items to be private to a SIMD
3438 // lane and to have a linear relationship with respect to the iteration space
3439 // of a loop.
3440 // The special this pointer can be used as if was one of the arguments to the
3441 // function in any of the linear, aligned, or uniform clauses.
3442 // When a linear-step expression is specified in a linear clause it must be
3443 // either a constant integer expression or an integer-typed parameter that is
3444 // specified in a uniform clause on the directive.
3445 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3446 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3447 auto MI = LinModifiers.begin();
3448 for (auto *E : Linears) {
3449 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3450 ++MI;
3451 E = E->IgnoreParenImpCasts();
3452 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3453 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3454 auto *CanonPVD = PVD->getCanonicalDecl();
3455 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3456 FD->getParamDecl(PVD->getFunctionScopeIndex())
3457 ->getCanonicalDecl() == CanonPVD) {
3458 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3459 // A list-item cannot appear in more than one linear clause.
3460 if (LinearArgs.count(CanonPVD) > 0) {
3461 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3462 << getOpenMPClauseName(OMPC_linear)
3463 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3464 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3465 diag::note_omp_explicit_dsa)
3466 << getOpenMPClauseName(OMPC_linear);
3467 continue;
3468 }
3469 // Each argument can appear in at most one uniform or linear clause.
3470 if (UniformedArgs.count(CanonPVD) > 0) {
3471 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3472 << getOpenMPClauseName(OMPC_linear)
3473 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3474 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3475 diag::note_omp_explicit_dsa)
3476 << getOpenMPClauseName(OMPC_uniform);
3477 continue;
3478 }
3479 LinearArgs[CanonPVD] = E;
3480 if (E->isValueDependent() || E->isTypeDependent() ||
3481 E->isInstantiationDependent() ||
3482 E->containsUnexpandedParameterPack())
3483 continue;
3484 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3485 PVD->getOriginalType());
3486 continue;
3487 }
3488 }
3489 if (isa<CXXThisExpr>(E)) {
3490 if (UniformedLinearThis) {
3491 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3492 << getOpenMPClauseName(OMPC_linear)
3493 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3494 << E->getSourceRange();
3495 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3496 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3497 : OMPC_linear);
3498 continue;
3499 }
3500 UniformedLinearThis = E;
3501 if (E->isValueDependent() || E->isTypeDependent() ||
3502 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3503 continue;
3504 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3505 E->getType());
3506 continue;
3507 }
3508 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3509 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3510 }
3511 Expr *Step = nullptr;
3512 Expr *NewStep = nullptr;
3513 SmallVector<Expr *, 4> NewSteps;
3514 for (auto *E : Steps) {
3515 // Skip the same step expression, it was checked already.
3516 if (Step == E || !E) {
3517 NewSteps.push_back(E ? NewStep : nullptr);
3518 continue;
3519 }
3520 Step = E;
3521 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3522 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3523 auto *CanonPVD = PVD->getCanonicalDecl();
3524 if (UniformedArgs.count(CanonPVD) == 0) {
3525 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3526 << Step->getSourceRange();
3527 } else if (E->isValueDependent() || E->isTypeDependent() ||
3528 E->isInstantiationDependent() ||
3529 E->containsUnexpandedParameterPack() ||
3530 CanonPVD->getType()->hasIntegerRepresentation())
3531 NewSteps.push_back(Step);
3532 else {
3533 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3534 << Step->getSourceRange();
3535 }
3536 continue;
3537 }
3538 NewStep = Step;
3539 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3540 !Step->isInstantiationDependent() &&
3541 !Step->containsUnexpandedParameterPack()) {
3542 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3543 .get();
3544 if (NewStep)
3545 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3546 }
3547 NewSteps.push_back(NewStep);
3548 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003549 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3550 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003551 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003552 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3553 const_cast<Expr **>(Linears.data()), Linears.size(),
3554 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3555 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003556 ADecl->addAttr(NewAttr);
3557 return ConvertDeclToDeclGroup(ADecl);
3558}
3559
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003560StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3561 Stmt *AStmt,
3562 SourceLocation StartLoc,
3563 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003564 if (!AStmt)
3565 return StmtError();
3566
Alexey Bataev9959db52014-05-06 10:08:46 +00003567 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3568 // 1.2.2 OpenMP Language Terminology
3569 // Structured block - An executable statement with a single entry at the
3570 // top and a single exit at the bottom.
3571 // The point of exit cannot be a branch out of the structured block.
3572 // longjmp() and throw() must not violate the entry/exit criteria.
3573 CS->getCapturedDecl()->setNothrow();
3574
Reid Kleckner8d485b82018-03-08 01:12:22 +00003575 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003576
Alexey Bataev25e5b442015-09-15 12:52:43 +00003577 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3578 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003579}
3580
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003581namespace {
3582/// \brief Helper class for checking canonical form of the OpenMP loops and
3583/// extracting iteration space of each loop in the loop nest, that will be used
3584/// for IR generation.
3585class OpenMPIterationSpaceChecker {
3586 /// \brief Reference to Sema.
3587 Sema &SemaRef;
3588 /// \brief A location for diagnostics (when there is no some better location).
3589 SourceLocation DefaultLoc;
3590 /// \brief A location for diagnostics (when increment is not compatible).
3591 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003592 /// \brief A source location for referring to loop init later.
3593 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003594 /// \brief A source location for referring to condition later.
3595 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003596 /// \brief A source location for referring to increment later.
3597 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003598 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003599 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003600 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003601 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003602 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003603 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003604 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003605 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003606 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003607 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003608 /// \brief This flag is true when condition is one of:
3609 /// Var < UB
3610 /// Var <= UB
3611 /// UB > Var
3612 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003613 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003614 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003615 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003616 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003617 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003618
3619public:
3620 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003621 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003622 /// \brief Check init-expr for canonical loop form and save loop counter
3623 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003624 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003625 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3626 /// for less/greater and for strict/non-strict comparison.
3627 bool CheckCond(Expr *S);
3628 /// \brief Check incr-expr for canonical loop form and return true if it
3629 /// does not conform, otherwise save loop step (#Step).
3630 bool CheckInc(Expr *S);
3631 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003632 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003633 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003634 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003635 /// \brief Source range of the loop init.
3636 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3637 /// \brief Source range of the loop condition.
3638 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3639 /// \brief Source range of the loop increment.
3640 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3641 /// \brief True if the step should be subtracted.
3642 bool ShouldSubtractStep() const { return SubtractStep; }
3643 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003644 Expr *
3645 BuildNumIterations(Scope *S, const bool LimitedType,
3646 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003647 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003648 Expr *BuildPreCond(Scope *S, Expr *Cond,
3649 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003650 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003651 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3652 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003653 /// \brief Build reference expression to the private counter be used for
3654 /// codegen.
3655 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003656 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003657 Expr *BuildCounterInit() const;
3658 /// \brief Build step of the counter be used for codegen.
3659 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003660 /// \brief Return true if any expression is dependent.
3661 bool Dependent() const;
3662
3663private:
3664 /// \brief Check the right-hand side of an assignment in the increment
3665 /// expression.
3666 bool CheckIncRHS(Expr *RHS);
3667 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003668 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003669 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003670 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003671 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003672 /// \brief Helper to set loop increment.
3673 bool SetStep(Expr *NewStep, bool Subtract);
3674};
3675
3676bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003677 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003678 assert(!LB && !UB && !Step);
3679 return false;
3680 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003681 return LCDecl->getType()->isDependentType() ||
3682 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3683 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003684}
3685
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003686bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3687 Expr *NewLCRefExpr,
3688 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003689 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003690 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003691 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003692 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003693 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003694 LCDecl = getCanonicalDecl(NewLCDecl);
3695 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003696 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3697 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003698 if ((Ctor->isCopyOrMoveConstructor() ||
3699 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3700 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003701 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003702 LB = NewLB;
3703 return false;
3704}
3705
3706bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003707 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003708 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003709 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3710 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003711 if (!NewUB)
3712 return true;
3713 UB = NewUB;
3714 TestIsLessOp = LessOp;
3715 TestIsStrictOp = StrictOp;
3716 ConditionSrcRange = SR;
3717 ConditionLoc = SL;
3718 return false;
3719}
3720
3721bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3722 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003723 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003724 if (!NewStep)
3725 return true;
3726 if (!NewStep->isValueDependent()) {
3727 // Check that the step is integer expression.
3728 SourceLocation StepLoc = NewStep->getLocStart();
Alexey Bataev5372fb82017-08-31 23:06:52 +00003729 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3730 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003731 if (Val.isInvalid())
3732 return true;
3733 NewStep = Val.get();
3734
3735 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3736 // If test-expr is of form var relational-op b and relational-op is < or
3737 // <= then incr-expr must cause var to increase on each iteration of the
3738 // loop. If test-expr is of form var relational-op b and relational-op is
3739 // > or >= then incr-expr must cause var to decrease on each iteration of
3740 // the loop.
3741 // If test-expr is of form b relational-op var and relational-op is < or
3742 // <= then incr-expr must cause var to decrease on each iteration of the
3743 // loop. If test-expr is of form b relational-op var and relational-op is
3744 // > or >= then incr-expr must cause var to increase on each iteration of
3745 // the loop.
3746 llvm::APSInt Result;
3747 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3748 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3749 bool IsConstNeg =
3750 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003751 bool IsConstPos =
3752 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003753 bool IsConstZero = IsConstant && !Result.getBoolValue();
3754 if (UB && (IsConstZero ||
3755 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003756 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003757 SemaRef.Diag(NewStep->getExprLoc(),
3758 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003759 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003760 SemaRef.Diag(ConditionLoc,
3761 diag::note_omp_loop_cond_requres_compatible_incr)
3762 << TestIsLessOp << ConditionSrcRange;
3763 return true;
3764 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003765 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003766 NewStep =
3767 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3768 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003769 Subtract = !Subtract;
3770 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003771 }
3772
3773 Step = NewStep;
3774 SubtractStep = Subtract;
3775 return false;
3776}
3777
Alexey Bataev9c821032015-04-30 04:23:23 +00003778bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003779 // Check init-expr for canonical loop form and save loop counter
3780 // variable - #Var and its initialization value - #LB.
3781 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3782 // var = lb
3783 // integer-type var = lb
3784 // random-access-iterator-type var = lb
3785 // pointer-type var = lb
3786 //
3787 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003788 if (EmitDiags) {
3789 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3790 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003791 return true;
3792 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003793 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3794 if (!ExprTemp->cleanupsHaveSideEffects())
3795 S = ExprTemp->getSubExpr();
3796
Alexander Musmana5f070a2014-10-01 06:03:56 +00003797 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003798 if (Expr *E = dyn_cast<Expr>(S))
3799 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003800 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003801 if (BO->getOpcode() == BO_Assign) {
3802 auto *LHS = BO->getLHS()->IgnoreParens();
3803 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3804 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3805 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3806 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3807 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3808 }
3809 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3810 if (ME->isArrow() &&
3811 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3812 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3813 }
3814 }
David Majnemer9d168222016-08-05 17:44:54 +00003815 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003816 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003817 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003818 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003819 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003820 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003821 SemaRef.Diag(S->getLocStart(),
3822 diag::ext_omp_loop_not_canonical_init)
3823 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003824 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003825 }
3826 }
3827 }
David Majnemer9d168222016-08-05 17:44:54 +00003828 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003829 if (CE->getOperator() == OO_Equal) {
3830 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003831 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003832 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3833 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3834 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3835 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3836 }
3837 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3838 if (ME->isArrow() &&
3839 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3840 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3841 }
3842 }
3843 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003844
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003845 if (Dependent() || SemaRef.CurContext->isDependentContext())
3846 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003847 if (EmitDiags) {
3848 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3849 << S->getSourceRange();
3850 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003851 return true;
3852}
3853
Alexey Bataev23b69422014-06-18 07:08:49 +00003854/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003855/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003856static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003857 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003858 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003859 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003860 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3861 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003862 if ((Ctor->isCopyOrMoveConstructor() ||
3863 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3864 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003865 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003866 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003867 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003868 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003869 }
3870 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3871 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3872 return getCanonicalDecl(ME->getMemberDecl());
3873 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003874}
3875
3876bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3877 // Check test-expr for canonical form, save upper-bound UB, flags for
3878 // less/greater and for strict/non-strict comparison.
3879 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3880 // var relational-op b
3881 // b relational-op var
3882 //
3883 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003884 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003885 return true;
3886 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003887 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003888 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003889 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003890 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003891 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003892 return SetUB(BO->getRHS(),
3893 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3894 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3895 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003896 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003897 return SetUB(BO->getLHS(),
3898 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3899 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3900 BO->getSourceRange(), BO->getOperatorLoc());
3901 }
David Majnemer9d168222016-08-05 17:44:54 +00003902 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003903 if (CE->getNumArgs() == 2) {
3904 auto Op = CE->getOperator();
3905 switch (Op) {
3906 case OO_Greater:
3907 case OO_GreaterEqual:
3908 case OO_Less:
3909 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003910 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003911 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3912 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3913 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003914 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003915 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3916 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3917 CE->getOperatorLoc());
3918 break;
3919 default:
3920 break;
3921 }
3922 }
3923 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003924 if (Dependent() || SemaRef.CurContext->isDependentContext())
3925 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003926 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003927 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003928 return true;
3929}
3930
3931bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3932 // RHS of canonical loop form increment can be:
3933 // var + incr
3934 // incr + var
3935 // var - incr
3936 //
3937 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003938 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003939 if (BO->isAdditiveOp()) {
3940 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003941 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003942 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003943 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003944 return SetStep(BO->getLHS(), false);
3945 }
David Majnemer9d168222016-08-05 17:44:54 +00003946 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003947 bool IsAdd = CE->getOperator() == OO_Plus;
3948 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003949 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003950 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003951 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003952 return SetStep(CE->getArg(0), false);
3953 }
3954 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003955 if (Dependent() || SemaRef.CurContext->isDependentContext())
3956 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003957 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003958 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003959 return true;
3960}
3961
3962bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3963 // Check incr-expr for canonical loop form and return true if it
3964 // does not conform.
3965 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3966 // ++var
3967 // var++
3968 // --var
3969 // var--
3970 // var += incr
3971 // var -= incr
3972 // var = var + incr
3973 // var = incr + var
3974 // var = var - incr
3975 //
3976 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003977 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003978 return true;
3979 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003980 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3981 if (!ExprTemp->cleanupsHaveSideEffects())
3982 S = ExprTemp->getSubExpr();
3983
Alexander Musmana5f070a2014-10-01 06:03:56 +00003984 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003985 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003986 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003987 if (UO->isIncrementDecrementOp() &&
3988 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003989 return SetStep(SemaRef
3990 .ActOnIntegerConstant(UO->getLocStart(),
3991 (UO->isDecrementOp() ? -1 : 1))
3992 .get(),
3993 false);
3994 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003995 switch (BO->getOpcode()) {
3996 case BO_AddAssign:
3997 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003998 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003999 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
4000 break;
4001 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004002 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004003 return CheckIncRHS(BO->getRHS());
4004 break;
4005 default:
4006 break;
4007 }
David Majnemer9d168222016-08-05 17:44:54 +00004008 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004009 switch (CE->getOperator()) {
4010 case OO_PlusPlus:
4011 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004012 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00004013 return SetStep(SemaRef
4014 .ActOnIntegerConstant(
4015 CE->getLocStart(),
4016 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
4017 .get(),
4018 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004019 break;
4020 case OO_PlusEqual:
4021 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004022 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004023 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
4024 break;
4025 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004026 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004027 return CheckIncRHS(CE->getArg(1));
4028 break;
4029 default:
4030 break;
4031 }
4032 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004033 if (Dependent() || SemaRef.CurContext->isDependentContext())
4034 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004035 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004036 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004037 return true;
4038}
Alexander Musmana5f070a2014-10-01 06:03:56 +00004039
Alexey Bataev5a3af132016-03-29 08:58:54 +00004040static ExprResult
4041tryBuildCapture(Sema &SemaRef, Expr *Capture,
4042 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00004043 if (SemaRef.CurContext->isDependentContext())
4044 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00004045 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
4046 return SemaRef.PerformImplicitConversion(
4047 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
4048 /*AllowExplicit=*/true);
4049 auto I = Captures.find(Capture);
4050 if (I != Captures.end())
4051 return buildCapture(SemaRef, Capture, I->second);
4052 DeclRefExpr *Ref = nullptr;
4053 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4054 Captures[Capture] = Ref;
4055 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004056}
4057
Alexander Musmana5f070a2014-10-01 06:03:56 +00004058/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004059Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
4060 Scope *S, const bool LimitedType,
4061 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004062 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004063 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004064 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004065 SemaRef.getLangOpts().CPlusPlus) {
4066 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004067 auto *UBExpr = TestIsLessOp ? UB : LB;
4068 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004069 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4070 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004071 if (!Upper || !Lower)
4072 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004073
4074 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4075
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004076 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004077 // BuildBinOp already emitted error, this one is to point user to upper
4078 // and lower bound, and to tell what is passed to 'operator-'.
4079 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
4080 << Upper->getSourceRange() << Lower->getSourceRange();
4081 return nullptr;
4082 }
4083 }
4084
4085 if (!Diff.isUsable())
4086 return nullptr;
4087
4088 // Upper - Lower [- 1]
4089 if (TestIsStrictOp)
4090 Diff = SemaRef.BuildBinOp(
4091 S, DefaultLoc, BO_Sub, Diff.get(),
4092 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4093 if (!Diff.isUsable())
4094 return nullptr;
4095
4096 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00004097 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
4098 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004099 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004100 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004101 if (!Diff.isUsable())
4102 return nullptr;
4103
4104 // Parentheses (for dumping/debugging purposes only).
4105 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4106 if (!Diff.isUsable())
4107 return nullptr;
4108
4109 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004110 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004111 if (!Diff.isUsable())
4112 return nullptr;
4113
Alexander Musman174b3ca2014-10-06 11:16:29 +00004114 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004115 QualType Type = Diff.get()->getType();
4116 auto &C = SemaRef.Context;
4117 bool UseVarType = VarType->hasIntegerRepresentation() &&
4118 C.getTypeSize(Type) > C.getTypeSize(VarType);
4119 if (!Type->isIntegerType() || UseVarType) {
4120 unsigned NewSize =
4121 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4122 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4123 : Type->hasSignedIntegerRepresentation();
4124 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004125 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4126 Diff = SemaRef.PerformImplicitConversion(
4127 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4128 if (!Diff.isUsable())
4129 return nullptr;
4130 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004131 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004132 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004133 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4134 if (NewSize != C.getTypeSize(Type)) {
4135 if (NewSize < C.getTypeSize(Type)) {
4136 assert(NewSize == 64 && "incorrect loop var size");
4137 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4138 << InitSrcRange << ConditionSrcRange;
4139 }
4140 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004141 NewSize, Type->hasSignedIntegerRepresentation() ||
4142 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004143 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4144 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4145 Sema::AA_Converting, true);
4146 if (!Diff.isUsable())
4147 return nullptr;
4148 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004149 }
4150 }
4151
Alexander Musmana5f070a2014-10-01 06:03:56 +00004152 return Diff.get();
4153}
4154
Alexey Bataev5a3af132016-03-29 08:58:54 +00004155Expr *OpenMPIterationSpaceChecker::BuildPreCond(
4156 Scope *S, Expr *Cond,
4157 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004158 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4159 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4160 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004161
Alexey Bataev5a3af132016-03-29 08:58:54 +00004162 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
4163 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
4164 if (!NewLB.isUsable() || !NewUB.isUsable())
4165 return nullptr;
4166
Alexey Bataev62dbb972015-04-22 11:59:37 +00004167 auto CondExpr = SemaRef.BuildBinOp(
4168 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
4169 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004170 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004171 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004172 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4173 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004174 CondExpr = SemaRef.PerformImplicitConversion(
4175 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4176 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004177 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004178 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4179 // Otherwise use original loop conditon and evaluate it in runtime.
4180 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4181}
4182
Alexander Musmana5f070a2014-10-01 06:03:56 +00004183/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004184DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004185 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004186 auto *VD = dyn_cast<VarDecl>(LCDecl);
4187 if (!VD) {
4188 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
4189 auto *Ref = buildDeclRefExpr(
4190 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004191 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4192 // If the loop control decl is explicitly marked as private, do not mark it
4193 // as captured again.
4194 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4195 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004196 return Ref;
4197 }
4198 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004199 DefaultLoc);
4200}
4201
4202Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004203 if (LCDecl && !LCDecl->isInvalidDecl()) {
4204 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00004205 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004206 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
4207 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004208 if (PrivateVar->isInvalidDecl())
4209 return nullptr;
4210 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4211 }
4212 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004213}
4214
Samuel Antao4c8035b2016-12-12 18:00:20 +00004215/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004216Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4217
4218/// \brief Build step of the counter be used for codegen.
4219Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4220
4221/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004222struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004223 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004224 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004225 /// \brief This expression calculates the number of iterations in the loop.
4226 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004227 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004228 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004229 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00004230 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004231 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004232 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004233 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004234 /// \brief This is step for the #CounterVar used to generate its update:
4235 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004236 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004237 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004238 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004239 /// \brief Source range of the loop init.
4240 SourceRange InitSrcRange;
4241 /// \brief Source range of the loop condition.
4242 SourceRange CondSrcRange;
4243 /// \brief Source range of the loop increment.
4244 SourceRange IncSrcRange;
4245};
4246
Alexey Bataev23b69422014-06-18 07:08:49 +00004247} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004248
Alexey Bataev9c821032015-04-30 04:23:23 +00004249void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4250 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4251 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004252 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4253 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004254 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4255 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004256 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4257 if (auto *D = ISC.GetLoopDecl()) {
4258 auto *VD = dyn_cast<VarDecl>(D);
4259 if (!VD) {
4260 if (auto *Private = IsOpenMPCapturedDecl(D))
4261 VD = Private;
4262 else {
4263 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4264 /*WithInit=*/false);
4265 VD = cast<VarDecl>(Ref->getDecl());
4266 }
4267 }
4268 DSAStack->addLoopControlVariable(D, VD);
4269 }
4270 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004271 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004272 }
4273}
4274
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004275/// \brief Called on a for stmt to check and extract its iteration space
4276/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00004277static bool CheckOpenMPIterationSpace(
4278 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4279 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004280 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004281 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004282 LoopIterationSpace &ResultIterSpace,
4283 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004284 // OpenMP [2.6, Canonical Loop Form]
4285 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004286 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004287 if (!For) {
4288 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004289 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4290 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4291 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4292 if (NestedLoopCount > 1) {
4293 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4294 SemaRef.Diag(DSA.getConstructLoc(),
4295 diag::note_omp_collapse_ordered_expr)
4296 << 2 << CollapseLoopCountExpr->getSourceRange()
4297 << OrderedLoopCountExpr->getSourceRange();
4298 else if (CollapseLoopCountExpr)
4299 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4300 diag::note_omp_collapse_ordered_expr)
4301 << 0 << CollapseLoopCountExpr->getSourceRange();
4302 else
4303 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4304 diag::note_omp_collapse_ordered_expr)
4305 << 1 << OrderedLoopCountExpr->getSourceRange();
4306 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004307 return true;
4308 }
4309 assert(For->getBody());
4310
4311 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4312
4313 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00004314 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004315 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004316 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004317
4318 bool HasErrors = false;
4319
4320 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004321 if (auto *LCDecl = ISC.GetLoopDecl()) {
4322 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004323
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004324 // OpenMP [2.6, Canonical Loop Form]
4325 // Var is one of the following:
4326 // A variable of signed or unsigned integer type.
4327 // For C++, a variable of a random access iterator type.
4328 // For C, a variable of a pointer type.
4329 auto VarType = LCDecl->getType().getNonReferenceType();
4330 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4331 !VarType->isPointerType() &&
4332 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4333 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4334 << SemaRef.getLangOpts().CPlusPlus;
4335 HasErrors = true;
4336 }
4337
4338 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4339 // a Construct
4340 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4341 // parallel for construct is (are) private.
4342 // The loop iteration variable in the associated for-loop of a simd
4343 // construct with just one associated for-loop is linear with a
4344 // constant-linear-step that is the increment of the associated for-loop.
4345 // Exclude loop var from the list of variables with implicitly defined data
4346 // sharing attributes.
4347 VarsWithImplicitDSA.erase(LCDecl);
4348
4349 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4350 // in a Construct, C/C++].
4351 // The loop iteration variable in the associated for-loop of a simd
4352 // construct with just one associated for-loop may be listed in a linear
4353 // clause with a constant-linear-step that is the increment of the
4354 // associated for-loop.
4355 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4356 // parallel for construct may be listed in a private or lastprivate clause.
4357 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4358 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4359 // declared in the loop and it is predetermined as a private.
4360 auto PredeterminedCKind =
4361 isOpenMPSimdDirective(DKind)
4362 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4363 : OMPC_private;
4364 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4365 DVar.CKind != PredeterminedCKind) ||
4366 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4367 isOpenMPDistributeDirective(DKind)) &&
4368 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4369 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4370 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4371 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4372 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4373 << getOpenMPClauseName(PredeterminedCKind);
4374 if (DVar.RefExpr == nullptr)
4375 DVar.CKind = PredeterminedCKind;
4376 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4377 HasErrors = true;
4378 } else if (LoopDeclRefExpr != nullptr) {
4379 // Make the loop iteration variable private (for worksharing constructs),
4380 // linear (for simd directives with the only one associated loop) or
4381 // lastprivate (for simd directives with several collapsed or ordered
4382 // loops).
4383 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004384 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4385 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004386 /*FromParent=*/false);
4387 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4388 }
4389
4390 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4391
4392 // Check test-expr.
4393 HasErrors |= ISC.CheckCond(For->getCond());
4394
4395 // Check incr-expr.
4396 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004397 }
4398
Alexander Musmana5f070a2014-10-01 06:03:56 +00004399 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004400 return HasErrors;
4401
Alexander Musmana5f070a2014-10-01 06:03:56 +00004402 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004403 ResultIterSpace.PreCond =
4404 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00004405 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004406 DSA.getCurScope(),
4407 (isOpenMPWorksharingDirective(DKind) ||
4408 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4409 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004410 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00004411 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004412 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4413 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4414 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4415 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4416 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4417 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4418
Alexey Bataev62dbb972015-04-22 11:59:37 +00004419 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4420 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004421 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004422 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004423 ResultIterSpace.CounterInit == nullptr ||
4424 ResultIterSpace.CounterStep == nullptr);
4425
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004426 return HasErrors;
4427}
4428
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004429/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004430static ExprResult
4431BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4432 ExprResult Start,
4433 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004434 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004435 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4436 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004437 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004438 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004439 VarRef.get()->getType())) {
4440 NewStart = SemaRef.PerformImplicitConversion(
4441 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4442 /*AllowExplicit=*/true);
4443 if (!NewStart.isUsable())
4444 return ExprError();
4445 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004446
4447 auto Init =
4448 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4449 return Init;
4450}
4451
Alexander Musmana5f070a2014-10-01 06:03:56 +00004452/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004453static ExprResult
4454BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4455 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4456 ExprResult Step, bool Subtract,
4457 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004458 // Add parentheses (for debugging purposes only).
4459 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4460 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4461 !Step.isUsable())
4462 return ExprError();
4463
Alexey Bataev5a3af132016-03-29 08:58:54 +00004464 ExprResult NewStep = Step;
4465 if (Captures)
4466 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004467 if (NewStep.isInvalid())
4468 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004469 ExprResult Update =
4470 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004471 if (!Update.isUsable())
4472 return ExprError();
4473
Alexey Bataevc0214e02016-02-16 12:13:49 +00004474 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4475 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004476 ExprResult NewStart = Start;
4477 if (Captures)
4478 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004479 if (NewStart.isInvalid())
4480 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004481
Alexey Bataevc0214e02016-02-16 12:13:49 +00004482 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4483 ExprResult SavedUpdate = Update;
4484 ExprResult UpdateVal;
4485 if (VarRef.get()->getType()->isOverloadableType() ||
4486 NewStart.get()->getType()->isOverloadableType() ||
4487 Update.get()->getType()->isOverloadableType()) {
4488 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4489 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4490 Update =
4491 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4492 if (Update.isUsable()) {
4493 UpdateVal =
4494 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4495 VarRef.get(), SavedUpdate.get());
4496 if (UpdateVal.isUsable()) {
4497 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4498 UpdateVal.get());
4499 }
4500 }
4501 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4502 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004503
Alexey Bataevc0214e02016-02-16 12:13:49 +00004504 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4505 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4506 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4507 NewStart.get(), SavedUpdate.get());
4508 if (!Update.isUsable())
4509 return ExprError();
4510
Alexey Bataev11481f52016-02-17 10:29:05 +00004511 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4512 VarRef.get()->getType())) {
4513 Update = SemaRef.PerformImplicitConversion(
4514 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4515 if (!Update.isUsable())
4516 return ExprError();
4517 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004518
4519 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4520 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004521 return Update;
4522}
4523
4524/// \brief Convert integer expression \a E to make it have at least \a Bits
4525/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004526static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004527 if (E == nullptr)
4528 return ExprError();
4529 auto &C = SemaRef.Context;
4530 QualType OldType = E->getType();
4531 unsigned HasBits = C.getTypeSize(OldType);
4532 if (HasBits >= Bits)
4533 return ExprResult(E);
4534 // OK to convert to signed, because new type has more bits than old.
4535 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4536 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4537 true);
4538}
4539
4540/// \brief Check if the given expression \a E is a constant integer that fits
4541/// into \a Bits bits.
4542static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4543 if (E == nullptr)
4544 return false;
4545 llvm::APSInt Result;
4546 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4547 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4548 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004549}
4550
Alexey Bataev5a3af132016-03-29 08:58:54 +00004551/// Build preinits statement for the given declarations.
4552static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00004553 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004554 if (!PreInits.empty()) {
4555 return new (Context) DeclStmt(
4556 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4557 SourceLocation(), SourceLocation());
4558 }
4559 return nullptr;
4560}
4561
4562/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00004563static Stmt *
4564buildPreInits(ASTContext &Context,
4565 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004566 if (!Captures.empty()) {
4567 SmallVector<Decl *, 16> PreInits;
4568 for (auto &Pair : Captures)
4569 PreInits.push_back(Pair.second->getDecl());
4570 return buildPreInits(Context, PreInits);
4571 }
4572 return nullptr;
4573}
4574
4575/// Build postupdate expression for the given list of postupdates expressions.
4576static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4577 Expr *PostUpdate = nullptr;
4578 if (!PostUpdates.empty()) {
4579 for (auto *E : PostUpdates) {
4580 Expr *ConvE = S.BuildCStyleCastExpr(
4581 E->getExprLoc(),
4582 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4583 E->getExprLoc(), E)
4584 .get();
4585 PostUpdate = PostUpdate
4586 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4587 PostUpdate, ConvE)
4588 .get()
4589 : ConvE;
4590 }
4591 }
4592 return PostUpdate;
4593}
4594
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004595/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004596/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4597/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004598static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004599CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4600 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4601 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004602 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004603 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004604 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004605 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004606 // Found 'collapse' clause - calculate collapse number.
4607 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004608 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004609 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004610 }
4611 if (OrderedLoopCountExpr) {
4612 // Found 'ordered' clause - calculate collapse number.
4613 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004614 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4615 if (Result.getLimitedValue() < NestedLoopCount) {
4616 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4617 diag::err_omp_wrong_ordered_loop_count)
4618 << OrderedLoopCountExpr->getSourceRange();
4619 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4620 diag::note_collapse_loop_count)
4621 << CollapseLoopCountExpr->getSourceRange();
4622 }
4623 NestedLoopCount = Result.getLimitedValue();
4624 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004625 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004626 // This is helper routine for loop directives (e.g., 'for', 'simd',
4627 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004628 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004629 SmallVector<LoopIterationSpace, 4> IterSpaces;
4630 IterSpaces.resize(NestedLoopCount);
4631 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004632 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004633 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004634 NestedLoopCount, CollapseLoopCountExpr,
4635 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004636 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004637 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004638 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004639 // OpenMP [2.8.1, simd construct, Restrictions]
4640 // All loops associated with the construct must be perfectly nested; that
4641 // is, there must be no intervening code nor any OpenMP directive between
4642 // any two loops.
4643 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004644 }
4645
Alexander Musmana5f070a2014-10-01 06:03:56 +00004646 Built.clear(/* size */ NestedLoopCount);
4647
4648 if (SemaRef.CurContext->isDependentContext())
4649 return NestedLoopCount;
4650
4651 // An example of what is generated for the following code:
4652 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004653 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004654 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004655 // for (k = 0; k < NK; ++k)
4656 // for (j = J0; j < NJ; j+=2) {
4657 // <loop body>
4658 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004659 //
4660 // We generate the code below.
4661 // Note: the loop body may be outlined in CodeGen.
4662 // Note: some counters may be C++ classes, operator- is used to find number of
4663 // iterations and operator+= to calculate counter value.
4664 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4665 // or i64 is currently supported).
4666 //
4667 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4668 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4669 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4670 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4671 // // similar updates for vars in clauses (e.g. 'linear')
4672 // <loop body (using local i and j)>
4673 // }
4674 // i = NI; // assign final values of counters
4675 // j = NJ;
4676 //
4677
4678 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4679 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004680 // Precondition tests if there is at least one iteration (all conditions are
4681 // true).
4682 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004683 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004684 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004685 32 /* Bits */, SemaRef
4686 .PerformImplicitConversion(
4687 N0->IgnoreImpCasts(), N0->getType(),
4688 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004689 .get(),
4690 SemaRef);
4691 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004692 64 /* Bits */, SemaRef
4693 .PerformImplicitConversion(
4694 N0->IgnoreImpCasts(), N0->getType(),
4695 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004696 .get(),
4697 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004698
4699 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4700 return NestedLoopCount;
4701
4702 auto &C = SemaRef.Context;
4703 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4704
4705 Scope *CurScope = DSA.getCurScope();
4706 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004707 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004708 PreCond =
4709 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4710 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004711 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004712 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004713 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004714 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4715 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004716 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004717 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004718 SemaRef
4719 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4720 Sema::AA_Converting,
4721 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004722 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004723 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004724 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004725 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004726 SemaRef
4727 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4728 Sema::AA_Converting,
4729 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004730 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004731 }
4732
4733 // Choose either the 32-bit or 64-bit version.
4734 ExprResult LastIteration = LastIteration64;
4735 if (LastIteration32.isUsable() &&
4736 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4737 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4738 FitsInto(
4739 32 /* Bits */,
4740 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4741 LastIteration64.get(), SemaRef)))
4742 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004743 QualType VType = LastIteration.get()->getType();
4744 QualType RealVType = VType;
4745 QualType StrideVType = VType;
4746 if (isOpenMPTaskLoopDirective(DKind)) {
4747 VType =
4748 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4749 StrideVType =
4750 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4751 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004752
4753 if (!LastIteration.isUsable())
4754 return 0;
4755
4756 // Save the number of iterations.
4757 ExprResult NumIterations = LastIteration;
4758 {
4759 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004760 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4761 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004762 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4763 if (!LastIteration.isUsable())
4764 return 0;
4765 }
4766
4767 // Calculate the last iteration number beforehand instead of doing this on
4768 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4769 llvm::APSInt Result;
4770 bool IsConstant =
4771 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4772 ExprResult CalcLastIteration;
4773 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004774 ExprResult SaveRef =
4775 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004776 LastIteration = SaveRef;
4777
4778 // Prepare SaveRef + 1.
4779 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004780 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004781 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4782 if (!NumIterations.isUsable())
4783 return 0;
4784 }
4785
4786 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4787
David Majnemer9d168222016-08-05 17:44:54 +00004788 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004789 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004790 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4791 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004792 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004793 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4794 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004795 SemaRef.AddInitializerToDecl(LBDecl,
4796 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4797 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004798
4799 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004800 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4801 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004802 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004803 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004804
4805 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4806 // This will be used to implement clause 'lastprivate'.
4807 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004808 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4809 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004810 SemaRef.AddInitializerToDecl(ILDecl,
4811 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4812 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004813
4814 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004815 VarDecl *STDecl =
4816 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4817 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004818 SemaRef.AddInitializerToDecl(STDecl,
4819 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4820 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004821
4822 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004823 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004824 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4825 UB.get(), LastIteration.get());
4826 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4827 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4828 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4829 CondOp.get());
4830 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004831
4832 // If we have a combined directive that combines 'distribute', 'for' or
4833 // 'simd' we need to be able to access the bounds of the schedule of the
4834 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4835 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4836 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004837
Carlo Bertolliffafe102017-04-20 00:39:39 +00004838 // Lower bound variable, initialized with zero.
4839 VarDecl *CombLBDecl =
4840 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4841 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4842 SemaRef.AddInitializerToDecl(
4843 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4844 /*DirectInit*/ false);
4845
4846 // Upper bound variable, initialized with last iteration number.
4847 VarDecl *CombUBDecl =
4848 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4849 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4850 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4851 /*DirectInit*/ false);
4852
4853 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4854 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4855 ExprResult CombCondOp =
4856 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4857 LastIteration.get(), CombUB.get());
4858 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4859 CombCondOp.get());
4860 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4861
4862 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004863 // We expect to have at least 2 more parameters than the 'parallel'
4864 // directive does - the lower and upper bounds of the previous schedule.
4865 assert(CD->getNumParams() >= 4 &&
4866 "Unexpected number of parameters in loop combined directive");
4867
4868 // Set the proper type for the bounds given what we learned from the
4869 // enclosed loops.
4870 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4871 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4872
4873 // Previous lower and upper bounds are obtained from the region
4874 // parameters.
4875 PrevLB =
4876 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4877 PrevUB =
4878 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4879 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004880 }
4881
4882 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004883 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004884 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004885 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004886 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4887 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004888 Expr *RHS =
4889 (isOpenMPWorksharingDirective(DKind) ||
4890 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4891 ? LB.get()
4892 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004893 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4894 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004895
4896 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4897 Expr *CombRHS =
4898 (isOpenMPWorksharingDirective(DKind) ||
4899 isOpenMPTaskLoopDirective(DKind) ||
4900 isOpenMPDistributeDirective(DKind))
4901 ? CombLB.get()
4902 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4903 CombInit =
4904 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4905 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4906 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004907 }
4908
Alexander Musmanc6388682014-12-15 07:07:06 +00004909 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00004910 SourceLocation CondLoc = AStmt->getLocStart();
Alexander Musmanc6388682014-12-15 07:07:06 +00004911 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004912 (isOpenMPWorksharingDirective(DKind) ||
4913 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004914 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4915 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4916 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004917 ExprResult CombCond;
4918 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4919 CombCond =
4920 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4921 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004922 // Loop increment (IV = IV + 1)
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00004923 SourceLocation IncLoc = AStmt->getLocStart();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004924 ExprResult Inc =
4925 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4926 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4927 if (!Inc.isUsable())
4928 return 0;
4929 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004930 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4931 if (!Inc.isUsable())
4932 return 0;
4933
4934 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4935 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004936 // In combined construct, add combined version that use CombLB and CombUB
4937 // base variables for the update
4938 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004939 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4940 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004941 // LB + ST
4942 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4943 if (!NextLB.isUsable())
4944 return 0;
4945 // LB = LB + ST
4946 NextLB =
4947 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4948 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4949 if (!NextLB.isUsable())
4950 return 0;
4951 // UB + ST
4952 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4953 if (!NextUB.isUsable())
4954 return 0;
4955 // UB = UB + ST
4956 NextUB =
4957 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4958 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4959 if (!NextUB.isUsable())
4960 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004961 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4962 CombNextLB =
4963 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4964 if (!NextLB.isUsable())
4965 return 0;
4966 // LB = LB + ST
4967 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4968 CombNextLB.get());
4969 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4970 if (!CombNextLB.isUsable())
4971 return 0;
4972 // UB + ST
4973 CombNextUB =
4974 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4975 if (!CombNextUB.isUsable())
4976 return 0;
4977 // UB = UB + ST
4978 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4979 CombNextUB.get());
4980 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4981 if (!CombNextUB.isUsable())
4982 return 0;
4983 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004984 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004985
Carlo Bertolliffafe102017-04-20 00:39:39 +00004986 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004987 // directive with for as IV = IV + ST; ensure upper bound expression based
4988 // on PrevUB instead of NumIterations - used to implement 'for' when found
4989 // in combination with 'distribute', like in 'distribute parallel for'
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00004990 SourceLocation DistIncLoc = AStmt->getLocStart();
Carlo Bertolli8429d812017-02-17 21:29:13 +00004991 ExprResult DistCond, DistInc, PrevEUB;
4992 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4993 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4994 assert(DistCond.isUsable() && "distribute cond expr was not built");
4995
4996 DistInc =
4997 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4998 assert(DistInc.isUsable() && "distribute inc expr was not built");
4999 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
5000 DistInc.get());
5001 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
5002 assert(DistInc.isUsable() && "distribute inc expr was not built");
5003
5004 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
5005 // construct
Alexey Bataeva9b9cc02018-01-23 18:12:38 +00005006 SourceLocation DistEUBLoc = AStmt->getLocStart();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005007 ExprResult IsUBGreater =
5008 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
5009 ExprResult CondOp = SemaRef.ActOnConditionalOp(
5010 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
5011 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
5012 CondOp.get());
5013 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
5014 }
5015
Alexander Musmana5f070a2014-10-01 06:03:56 +00005016 // Build updates and final values of the loop counters.
5017 bool HasErrors = false;
5018 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005019 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005020 Built.Updates.resize(NestedLoopCount);
5021 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00005022 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00005023 {
5024 ExprResult Div;
5025 // Go from inner nested loop to outer.
5026 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5027 LoopIterationSpace &IS = IterSpaces[Cnt];
5028 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
5029 // Build: Iter = (IV / Div) % IS.NumIters
5030 // where Div is product of previous iterations' IS.NumIters.
5031 ExprResult Iter;
5032 if (Div.isUsable()) {
5033 Iter =
5034 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
5035 } else {
5036 Iter = IV;
5037 assert((Cnt == (int)NestedLoopCount - 1) &&
5038 "unusable div expected on first iteration only");
5039 }
5040
5041 if (Cnt != 0 && Iter.isUsable())
5042 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
5043 IS.NumIterations);
5044 if (!Iter.isUsable()) {
5045 HasErrors = true;
5046 break;
5047 }
5048
Alexey Bataev39f915b82015-05-08 10:41:21 +00005049 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005050 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
5051 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
5052 IS.CounterVar->getExprLoc(),
5053 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005054 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005055 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005056 if (!Init.isUsable()) {
5057 HasErrors = true;
5058 break;
5059 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00005060 ExprResult Update = BuildCounterUpdate(
5061 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5062 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005063 if (!Update.isUsable()) {
5064 HasErrors = true;
5065 break;
5066 }
5067
5068 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
5069 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00005070 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005071 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005072 if (!Final.isUsable()) {
5073 HasErrors = true;
5074 break;
5075 }
5076
5077 // Build Div for the next iteration: Div <- Div * IS.NumIters
5078 if (Cnt != 0) {
5079 if (Div.isUnset())
5080 Div = IS.NumIterations;
5081 else
5082 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
5083 IS.NumIterations);
5084
5085 // Add parentheses (for debugging purposes only).
5086 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00005087 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005088 if (!Div.isUsable()) {
5089 HasErrors = true;
5090 break;
5091 }
Alexey Bataev8b427062016-05-25 12:36:08 +00005092 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005093 }
5094 if (!Update.isUsable() || !Final.isUsable()) {
5095 HasErrors = true;
5096 break;
5097 }
5098 // Save results
5099 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00005100 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005101 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005102 Built.Updates[Cnt] = Update.get();
5103 Built.Finals[Cnt] = Final.get();
5104 }
5105 }
5106
5107 if (HasErrors)
5108 return 0;
5109
5110 // Save results
5111 Built.IterationVarRef = IV.get();
5112 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00005113 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005114 Built.CalcLastIteration =
5115 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005116 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00005117 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005118 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005119 Built.Init = Init.get();
5120 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005121 Built.LB = LB.get();
5122 Built.UB = UB.get();
5123 Built.IL = IL.get();
5124 Built.ST = ST.get();
5125 Built.EUB = EUB.get();
5126 Built.NLB = NextLB.get();
5127 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005128 Built.PrevLB = PrevLB.get();
5129 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005130 Built.DistInc = DistInc.get();
5131 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00005132 Built.DistCombinedFields.LB = CombLB.get();
5133 Built.DistCombinedFields.UB = CombUB.get();
5134 Built.DistCombinedFields.EUB = CombEUB.get();
5135 Built.DistCombinedFields.Init = CombInit.get();
5136 Built.DistCombinedFields.Cond = CombCond.get();
5137 Built.DistCombinedFields.NLB = CombNextLB.get();
5138 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005139
Alexey Bataev8b427062016-05-25 12:36:08 +00005140 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
5141 // Fill data for doacross depend clauses.
5142 for (auto Pair : DSA.getDoacrossDependClauses()) {
5143 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5144 Pair.first->setCounterValue(CounterVal);
5145 else {
5146 if (NestedLoopCount != Pair.second.size() ||
5147 NestedLoopCount != LoopMultipliers.size() + 1) {
5148 // Erroneous case - clause has some problems.
5149 Pair.first->setCounterValue(CounterVal);
5150 continue;
5151 }
5152 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
5153 auto I = Pair.second.rbegin();
5154 auto IS = IterSpaces.rbegin();
5155 auto ILM = LoopMultipliers.rbegin();
5156 Expr *UpCounterVal = CounterVal;
5157 Expr *Multiplier = nullptr;
5158 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5159 if (I->first) {
5160 assert(IS->CounterStep);
5161 Expr *NormalizedOffset =
5162 SemaRef
5163 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
5164 I->first, IS->CounterStep)
5165 .get();
5166 if (Multiplier) {
5167 NormalizedOffset =
5168 SemaRef
5169 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
5170 NormalizedOffset, Multiplier)
5171 .get();
5172 }
5173 assert(I->second == OO_Plus || I->second == OO_Minus);
5174 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00005175 UpCounterVal = SemaRef
5176 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
5177 UpCounterVal, NormalizedOffset)
5178 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00005179 }
5180 Multiplier = *ILM;
5181 ++I;
5182 ++IS;
5183 ++ILM;
5184 }
5185 Pair.first->setCounterValue(UpCounterVal);
5186 }
5187 }
5188
Alexey Bataevabfc0692014-06-25 06:52:00 +00005189 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005190}
5191
Alexey Bataev10e775f2015-07-30 11:36:16 +00005192static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005193 auto CollapseClauses =
5194 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5195 if (CollapseClauses.begin() != CollapseClauses.end())
5196 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005197 return nullptr;
5198}
5199
Alexey Bataev10e775f2015-07-30 11:36:16 +00005200static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005201 auto OrderedClauses =
5202 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5203 if (OrderedClauses.begin() != OrderedClauses.end())
5204 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005205 return nullptr;
5206}
5207
Kelvin Lic5609492016-07-15 04:39:07 +00005208static bool checkSimdlenSafelenSpecified(Sema &S,
5209 const ArrayRef<OMPClause *> Clauses) {
5210 OMPSafelenClause *Safelen = nullptr;
5211 OMPSimdlenClause *Simdlen = nullptr;
5212
5213 for (auto *Clause : Clauses) {
5214 if (Clause->getClauseKind() == OMPC_safelen)
5215 Safelen = cast<OMPSafelenClause>(Clause);
5216 else if (Clause->getClauseKind() == OMPC_simdlen)
5217 Simdlen = cast<OMPSimdlenClause>(Clause);
5218 if (Safelen && Simdlen)
5219 break;
5220 }
5221
5222 if (Simdlen && Safelen) {
5223 llvm::APSInt SimdlenRes, SafelenRes;
5224 auto SimdlenLength = Simdlen->getSimdlen();
5225 auto SafelenLength = Safelen->getSafelen();
5226 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5227 SimdlenLength->isInstantiationDependent() ||
5228 SimdlenLength->containsUnexpandedParameterPack())
5229 return false;
5230 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5231 SafelenLength->isInstantiationDependent() ||
5232 SafelenLength->containsUnexpandedParameterPack())
5233 return false;
5234 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5235 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5236 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5237 // If both simdlen and safelen clauses are specified, the value of the
5238 // simdlen parameter must be less than or equal to the value of the safelen
5239 // parameter.
5240 if (SimdlenRes > SafelenRes) {
5241 S.Diag(SimdlenLength->getExprLoc(),
5242 diag::err_omp_wrong_simdlen_safelen_values)
5243 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5244 return true;
5245 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005246 }
5247 return false;
5248}
5249
Alexey Bataev4acb8592014-07-07 13:01:15 +00005250StmtResult Sema::ActOnOpenMPSimdDirective(
5251 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5252 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005253 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005254 if (!AStmt)
5255 return StmtError();
5256
5257 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005258 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005259 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5260 // define the nested loops number.
5261 unsigned NestedLoopCount = CheckOpenMPLoop(
5262 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5263 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005264 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005265 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005266
Alexander Musmana5f070a2014-10-01 06:03:56 +00005267 assert((CurContext->isDependentContext() || B.builtAll()) &&
5268 "omp simd loop exprs were not built");
5269
Alexander Musman3276a272015-03-21 10:12:56 +00005270 if (!CurContext->isDependentContext()) {
5271 // Finalize the clauses that need pre-built expressions for CodeGen.
5272 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005273 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005274 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005275 B.NumIterations, *this, CurScope,
5276 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005277 return StmtError();
5278 }
5279 }
5280
Kelvin Lic5609492016-07-15 04:39:07 +00005281 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005282 return StmtError();
5283
Reid Kleckner8d485b82018-03-08 01:12:22 +00005284 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005285 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5286 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005287}
5288
Alexey Bataev4acb8592014-07-07 13:01:15 +00005289StmtResult Sema::ActOnOpenMPForDirective(
5290 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5291 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005292 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005293 if (!AStmt)
5294 return StmtError();
5295
5296 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005297 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005298 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5299 // define the nested loops number.
5300 unsigned NestedLoopCount = CheckOpenMPLoop(
5301 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5302 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005303 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005304 return StmtError();
5305
Alexander Musmana5f070a2014-10-01 06:03:56 +00005306 assert((CurContext->isDependentContext() || B.builtAll()) &&
5307 "omp for loop exprs were not built");
5308
Alexey Bataev54acd402015-08-04 11:18:19 +00005309 if (!CurContext->isDependentContext()) {
5310 // Finalize the clauses that need pre-built expressions for CodeGen.
5311 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005312 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005313 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005314 B.NumIterations, *this, CurScope,
5315 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005316 return StmtError();
5317 }
5318 }
5319
Reid Kleckner8d485b82018-03-08 01:12:22 +00005320 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005321 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005322 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005323}
5324
Alexander Musmanf82886e2014-09-18 05:12:34 +00005325StmtResult Sema::ActOnOpenMPForSimdDirective(
5326 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5327 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005328 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005329 if (!AStmt)
5330 return StmtError();
5331
5332 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005333 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005334 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5335 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005336 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005337 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5338 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5339 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005340 if (NestedLoopCount == 0)
5341 return StmtError();
5342
Alexander Musmanc6388682014-12-15 07:07:06 +00005343 assert((CurContext->isDependentContext() || B.builtAll()) &&
5344 "omp for simd loop exprs were not built");
5345
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005346 if (!CurContext->isDependentContext()) {
5347 // Finalize the clauses that need pre-built expressions for CodeGen.
5348 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005349 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005350 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005351 B.NumIterations, *this, CurScope,
5352 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005353 return StmtError();
5354 }
5355 }
5356
Kelvin Lic5609492016-07-15 04:39:07 +00005357 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005358 return StmtError();
5359
Reid Kleckner8d485b82018-03-08 01:12:22 +00005360 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005361 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5362 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005363}
5364
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005365StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5366 Stmt *AStmt,
5367 SourceLocation StartLoc,
5368 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005369 if (!AStmt)
5370 return StmtError();
5371
5372 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005373 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005374 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005375 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005376 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005377 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005378 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005379 return StmtError();
5380 // All associated statements must be '#pragma omp section' except for
5381 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005382 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005383 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5384 if (SectionStmt)
5385 Diag(SectionStmt->getLocStart(),
5386 diag::err_omp_sections_substmt_not_section);
5387 return StmtError();
5388 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005389 cast<OMPSectionDirective>(SectionStmt)
5390 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005391 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005392 } else {
5393 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5394 return StmtError();
5395 }
5396
Reid Kleckner8d485b82018-03-08 01:12:22 +00005397 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005398
Alexey Bataev25e5b442015-09-15 12:52:43 +00005399 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5400 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005401}
5402
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005403StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5404 SourceLocation StartLoc,
5405 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005406 if (!AStmt)
5407 return StmtError();
5408
5409 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005410
Reid Kleckner8d485b82018-03-08 01:12:22 +00005411 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005412 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005413
Alexey Bataev25e5b442015-09-15 12:52:43 +00005414 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5415 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005416}
5417
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005418StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5419 Stmt *AStmt,
5420 SourceLocation StartLoc,
5421 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005422 if (!AStmt)
5423 return StmtError();
5424
5425 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005426
Reid Kleckner8d485b82018-03-08 01:12:22 +00005427 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005428
Alexey Bataev3255bf32015-01-19 05:20:46 +00005429 // OpenMP [2.7.3, single Construct, Restrictions]
5430 // The copyprivate clause must not be used with the nowait clause.
5431 OMPClause *Nowait = nullptr;
5432 OMPClause *Copyprivate = nullptr;
5433 for (auto *Clause : Clauses) {
5434 if (Clause->getClauseKind() == OMPC_nowait)
5435 Nowait = Clause;
5436 else if (Clause->getClauseKind() == OMPC_copyprivate)
5437 Copyprivate = Clause;
5438 if (Copyprivate && Nowait) {
5439 Diag(Copyprivate->getLocStart(),
5440 diag::err_omp_single_copyprivate_with_nowait);
5441 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5442 return StmtError();
5443 }
5444 }
5445
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005446 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5447}
5448
Alexander Musman80c22892014-07-17 08:54:58 +00005449StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5450 SourceLocation StartLoc,
5451 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005452 if (!AStmt)
5453 return StmtError();
5454
5455 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005456
Reid Kleckner8d485b82018-03-08 01:12:22 +00005457 getCurFunction()->setHasBranchProtectedScope();
Alexander Musman80c22892014-07-17 08:54:58 +00005458
5459 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5460}
5461
Alexey Bataev28c75412015-12-15 08:19:24 +00005462StmtResult Sema::ActOnOpenMPCriticalDirective(
5463 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5464 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005465 if (!AStmt)
5466 return StmtError();
5467
5468 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005469
Alexey Bataev28c75412015-12-15 08:19:24 +00005470 bool ErrorFound = false;
5471 llvm::APSInt Hint;
5472 SourceLocation HintLoc;
5473 bool DependentHint = false;
5474 for (auto *C : Clauses) {
5475 if (C->getClauseKind() == OMPC_hint) {
5476 if (!DirName.getName()) {
5477 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5478 ErrorFound = true;
5479 }
5480 Expr *E = cast<OMPHintClause>(C)->getHint();
5481 if (E->isTypeDependent() || E->isValueDependent() ||
5482 E->isInstantiationDependent())
5483 DependentHint = true;
5484 else {
5485 Hint = E->EvaluateKnownConstInt(Context);
5486 HintLoc = C->getLocStart();
5487 }
5488 }
5489 }
5490 if (ErrorFound)
5491 return StmtError();
5492 auto Pair = DSAStack->getCriticalWithHint(DirName);
5493 if (Pair.first && DirName.getName() && !DependentHint) {
5494 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5495 Diag(StartLoc, diag::err_omp_critical_with_hint);
5496 if (HintLoc.isValid()) {
5497 Diag(HintLoc, diag::note_omp_critical_hint_here)
5498 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5499 } else
5500 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5501 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5502 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5503 << 1
5504 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5505 /*Radix=*/10, /*Signed=*/false);
5506 } else
5507 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5508 }
5509 }
5510
Reid Kleckner8d485b82018-03-08 01:12:22 +00005511 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005512
Alexey Bataev28c75412015-12-15 08:19:24 +00005513 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5514 Clauses, AStmt);
5515 if (!Pair.first && DirName.getName() && !DependentHint)
5516 DSAStack->addCriticalWithHint(Dir, Hint);
5517 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005518}
5519
Alexey Bataev4acb8592014-07-07 13:01:15 +00005520StmtResult Sema::ActOnOpenMPParallelForDirective(
5521 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5522 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005523 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005524 if (!AStmt)
5525 return StmtError();
5526
Alexey Bataev4acb8592014-07-07 13:01:15 +00005527 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5528 // 1.2.2 OpenMP Language Terminology
5529 // Structured block - An executable statement with a single entry at the
5530 // top and a single exit at the bottom.
5531 // The point of exit cannot be a branch out of the structured block.
5532 // longjmp() and throw() must not violate the entry/exit criteria.
5533 CS->getCapturedDecl()->setNothrow();
5534
Alexander Musmanc6388682014-12-15 07:07:06 +00005535 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005536 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5537 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005538 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005539 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5540 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5541 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005542 if (NestedLoopCount == 0)
5543 return StmtError();
5544
Alexander Musmana5f070a2014-10-01 06:03:56 +00005545 assert((CurContext->isDependentContext() || B.builtAll()) &&
5546 "omp parallel for loop exprs were not built");
5547
Alexey Bataev54acd402015-08-04 11:18:19 +00005548 if (!CurContext->isDependentContext()) {
5549 // Finalize the clauses that need pre-built expressions for CodeGen.
5550 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005551 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005552 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005553 B.NumIterations, *this, CurScope,
5554 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005555 return StmtError();
5556 }
5557 }
5558
Reid Kleckner8d485b82018-03-08 01:12:22 +00005559 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005560 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005561 NestedLoopCount, Clauses, AStmt, B,
5562 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005563}
5564
Alexander Musmane4e893b2014-09-23 09:33:00 +00005565StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5566 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5567 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005568 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005569 if (!AStmt)
5570 return StmtError();
5571
Alexander Musmane4e893b2014-09-23 09:33:00 +00005572 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5573 // 1.2.2 OpenMP Language Terminology
5574 // Structured block - An executable statement with a single entry at the
5575 // top and a single exit at the bottom.
5576 // The point of exit cannot be a branch out of the structured block.
5577 // longjmp() and throw() must not violate the entry/exit criteria.
5578 CS->getCapturedDecl()->setNothrow();
5579
Alexander Musmanc6388682014-12-15 07:07:06 +00005580 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005581 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5582 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005583 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005584 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5585 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5586 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005587 if (NestedLoopCount == 0)
5588 return StmtError();
5589
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005590 if (!CurContext->isDependentContext()) {
5591 // Finalize the clauses that need pre-built expressions for CodeGen.
5592 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005593 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005594 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005595 B.NumIterations, *this, CurScope,
5596 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005597 return StmtError();
5598 }
5599 }
5600
Kelvin Lic5609492016-07-15 04:39:07 +00005601 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005602 return StmtError();
5603
Reid Kleckner8d485b82018-03-08 01:12:22 +00005604 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005605 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005606 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005607}
5608
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005609StmtResult
5610Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5611 Stmt *AStmt, SourceLocation StartLoc,
5612 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005613 if (!AStmt)
5614 return StmtError();
5615
5616 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005617 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005618 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005619 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005620 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005621 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005622 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005623 return StmtError();
5624 // All associated statements must be '#pragma omp section' except for
5625 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005626 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005627 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5628 if (SectionStmt)
5629 Diag(SectionStmt->getLocStart(),
5630 diag::err_omp_parallel_sections_substmt_not_section);
5631 return StmtError();
5632 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005633 cast<OMPSectionDirective>(SectionStmt)
5634 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005635 }
5636 } else {
5637 Diag(AStmt->getLocStart(),
5638 diag::err_omp_parallel_sections_not_compound_stmt);
5639 return StmtError();
5640 }
5641
Reid Kleckner8d485b82018-03-08 01:12:22 +00005642 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005643
Alexey Bataev25e5b442015-09-15 12:52:43 +00005644 return OMPParallelSectionsDirective::Create(
5645 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005646}
5647
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005648StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5649 Stmt *AStmt, SourceLocation StartLoc,
5650 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005651 if (!AStmt)
5652 return StmtError();
5653
David Majnemer9d168222016-08-05 17:44:54 +00005654 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005655 // 1.2.2 OpenMP Language Terminology
5656 // Structured block - An executable statement with a single entry at the
5657 // top and a single exit at the bottom.
5658 // The point of exit cannot be a branch out of the structured block.
5659 // longjmp() and throw() must not violate the entry/exit criteria.
5660 CS->getCapturedDecl()->setNothrow();
5661
Reid Kleckner8d485b82018-03-08 01:12:22 +00005662 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005663
Alexey Bataev25e5b442015-09-15 12:52:43 +00005664 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5665 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005666}
5667
Alexey Bataev68446b72014-07-18 07:47:19 +00005668StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5669 SourceLocation EndLoc) {
5670 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5671}
5672
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005673StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5674 SourceLocation EndLoc) {
5675 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5676}
5677
Alexey Bataev2df347a2014-07-18 10:17:07 +00005678StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5679 SourceLocation EndLoc) {
5680 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5681}
5682
Alexey Bataev169d96a2017-07-18 20:17:46 +00005683StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5684 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005685 SourceLocation StartLoc,
5686 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005687 if (!AStmt)
5688 return StmtError();
5689
5690 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005691
Reid Kleckner8d485b82018-03-08 01:12:22 +00005692 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005693
Alexey Bataev169d96a2017-07-18 20:17:46 +00005694 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005695 AStmt,
5696 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005697}
5698
Alexey Bataev6125da92014-07-21 11:26:11 +00005699StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5700 SourceLocation StartLoc,
5701 SourceLocation EndLoc) {
5702 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5703 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5704}
5705
Alexey Bataev346265e2015-09-25 10:37:12 +00005706StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5707 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005708 SourceLocation StartLoc,
5709 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005710 OMPClause *DependFound = nullptr;
5711 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005712 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005713 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005714 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005715 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005716 for (auto *C : Clauses) {
5717 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5718 DependFound = C;
5719 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5720 if (DependSourceClause) {
5721 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5722 << getOpenMPDirectiveName(OMPD_ordered)
5723 << getOpenMPClauseName(OMPC_depend) << 2;
5724 ErrorFound = true;
5725 } else
5726 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005727 if (DependSinkClause) {
5728 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5729 << 0;
5730 ErrorFound = true;
5731 }
5732 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5733 if (DependSourceClause) {
5734 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5735 << 1;
5736 ErrorFound = true;
5737 }
5738 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005739 }
5740 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005741 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005742 else if (C->getClauseKind() == OMPC_simd)
5743 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005744 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005745 if (!ErrorFound && !SC &&
5746 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005747 // OpenMP [2.8.1,simd Construct, Restrictions]
5748 // An ordered construct with the simd clause is the only OpenMP construct
5749 // that can appear in the simd region.
5750 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005751 ErrorFound = true;
5752 } else if (DependFound && (TC || SC)) {
5753 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5754 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5755 ErrorFound = true;
5756 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5757 Diag(DependFound->getLocStart(),
5758 diag::err_omp_ordered_directive_without_param);
5759 ErrorFound = true;
5760 } else if (TC || Clauses.empty()) {
5761 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5762 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5763 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5764 << (TC != nullptr);
5765 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5766 ErrorFound = true;
5767 }
5768 }
5769 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005770 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005771
5772 if (AStmt) {
5773 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5774
Reid Kleckner8d485b82018-03-08 01:12:22 +00005775 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005776 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005777
5778 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005779}
5780
Alexey Bataev1d160b12015-03-13 12:27:31 +00005781namespace {
5782/// \brief Helper class for checking expression in 'omp atomic [update]'
5783/// construct.
5784class OpenMPAtomicUpdateChecker {
5785 /// \brief Error results for atomic update expressions.
5786 enum ExprAnalysisErrorCode {
5787 /// \brief A statement is not an expression statement.
5788 NotAnExpression,
5789 /// \brief Expression is not builtin binary or unary operation.
5790 NotABinaryOrUnaryExpression,
5791 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5792 NotAnUnaryIncDecExpression,
5793 /// \brief An expression is not of scalar type.
5794 NotAScalarType,
5795 /// \brief A binary operation is not an assignment operation.
5796 NotAnAssignmentOp,
5797 /// \brief RHS part of the binary operation is not a binary expression.
5798 NotABinaryExpression,
5799 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5800 /// expression.
5801 NotABinaryOperator,
5802 /// \brief RHS binary operation does not have reference to the updated LHS
5803 /// part.
5804 NotAnUpdateExpression,
5805 /// \brief No errors is found.
5806 NoError
5807 };
5808 /// \brief Reference to Sema.
5809 Sema &SemaRef;
5810 /// \brief A location for note diagnostics (when error is found).
5811 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005812 /// \brief 'x' lvalue part of the source atomic expression.
5813 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005814 /// \brief 'expr' rvalue part of the source atomic expression.
5815 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005816 /// \brief Helper expression of the form
5817 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5818 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5819 Expr *UpdateExpr;
5820 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5821 /// important for non-associative operations.
5822 bool IsXLHSInRHSPart;
5823 BinaryOperatorKind Op;
5824 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005825 /// \brief true if the source expression is a postfix unary operation, false
5826 /// if it is a prefix unary operation.
5827 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005828
5829public:
5830 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005831 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005832 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005833 /// \brief Check specified statement that it is suitable for 'atomic update'
5834 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005835 /// expression. If DiagId and NoteId == 0, then only check is performed
5836 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005837 /// \param DiagId Diagnostic which should be emitted if error is found.
5838 /// \param NoteId Diagnostic note for the main error message.
5839 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005840 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005841 /// \brief Return the 'x' lvalue part of the source atomic expression.
5842 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005843 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5844 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005845 /// \brief Return the update expression used in calculation of the updated
5846 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5847 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5848 Expr *getUpdateExpr() const { return UpdateExpr; }
5849 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5850 /// false otherwise.
5851 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5852
Alexey Bataevb78ca832015-04-01 03:33:17 +00005853 /// \brief true if the source expression is a postfix unary operation, false
5854 /// if it is a prefix unary operation.
5855 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5856
Alexey Bataev1d160b12015-03-13 12:27:31 +00005857private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005858 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5859 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005860};
5861} // namespace
5862
5863bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5864 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5865 ExprAnalysisErrorCode ErrorFound = NoError;
5866 SourceLocation ErrorLoc, NoteLoc;
5867 SourceRange ErrorRange, NoteRange;
5868 // Allowed constructs are:
5869 // x = x binop expr;
5870 // x = expr binop x;
5871 if (AtomicBinOp->getOpcode() == BO_Assign) {
5872 X = AtomicBinOp->getLHS();
5873 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5874 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5875 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5876 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5877 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005878 Op = AtomicInnerBinOp->getOpcode();
5879 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005880 auto *LHS = AtomicInnerBinOp->getLHS();
5881 auto *RHS = AtomicInnerBinOp->getRHS();
5882 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5883 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5884 /*Canonical=*/true);
5885 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5886 /*Canonical=*/true);
5887 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5888 /*Canonical=*/true);
5889 if (XId == LHSId) {
5890 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005891 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005892 } else if (XId == RHSId) {
5893 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005894 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005895 } else {
5896 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5897 ErrorRange = AtomicInnerBinOp->getSourceRange();
5898 NoteLoc = X->getExprLoc();
5899 NoteRange = X->getSourceRange();
5900 ErrorFound = NotAnUpdateExpression;
5901 }
5902 } else {
5903 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5904 ErrorRange = AtomicInnerBinOp->getSourceRange();
5905 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5906 NoteRange = SourceRange(NoteLoc, NoteLoc);
5907 ErrorFound = NotABinaryOperator;
5908 }
5909 } else {
5910 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5911 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5912 ErrorFound = NotABinaryExpression;
5913 }
5914 } else {
5915 ErrorLoc = AtomicBinOp->getExprLoc();
5916 ErrorRange = AtomicBinOp->getSourceRange();
5917 NoteLoc = AtomicBinOp->getOperatorLoc();
5918 NoteRange = SourceRange(NoteLoc, NoteLoc);
5919 ErrorFound = NotAnAssignmentOp;
5920 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005921 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005922 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5923 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5924 return true;
5925 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005926 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005927 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005928}
5929
5930bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5931 unsigned NoteId) {
5932 ExprAnalysisErrorCode ErrorFound = NoError;
5933 SourceLocation ErrorLoc, NoteLoc;
5934 SourceRange ErrorRange, NoteRange;
5935 // Allowed constructs are:
5936 // x++;
5937 // x--;
5938 // ++x;
5939 // --x;
5940 // x binop= expr;
5941 // x = x binop expr;
5942 // x = expr binop x;
5943 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5944 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5945 if (AtomicBody->getType()->isScalarType() ||
5946 AtomicBody->isInstantiationDependent()) {
5947 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5948 AtomicBody->IgnoreParenImpCasts())) {
5949 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005950 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005951 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005952 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005953 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005954 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005955 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005956 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5957 AtomicBody->IgnoreParenImpCasts())) {
5958 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005959 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005960 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005961 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5962 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005963 // Check for Unary Operation
5964 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005965 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005966 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5967 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005968 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005969 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5970 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005971 } else {
5972 ErrorFound = NotAnUnaryIncDecExpression;
5973 ErrorLoc = AtomicUnaryOp->getExprLoc();
5974 ErrorRange = AtomicUnaryOp->getSourceRange();
5975 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5976 NoteRange = SourceRange(NoteLoc, NoteLoc);
5977 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005978 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005979 ErrorFound = NotABinaryOrUnaryExpression;
5980 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5981 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5982 }
5983 } else {
5984 ErrorFound = NotAScalarType;
5985 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5986 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5987 }
5988 } else {
5989 ErrorFound = NotAnExpression;
5990 NoteLoc = ErrorLoc = S->getLocStart();
5991 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5992 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005993 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005994 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5995 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5996 return true;
5997 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005998 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005999 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00006000 // Build an update expression of form 'OpaqueValueExpr(x) binop
6001 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
6002 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
6003 auto *OVEX = new (SemaRef.getASTContext())
6004 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
6005 auto *OVEExpr = new (SemaRef.getASTContext())
6006 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
6007 auto Update =
6008 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
6009 IsXLHSInRHSPart ? OVEExpr : OVEX);
6010 if (Update.isInvalid())
6011 return true;
6012 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
6013 Sema::AA_Casting);
6014 if (Update.isInvalid())
6015 return true;
6016 UpdateExpr = Update.get();
6017 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00006018 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00006019}
6020
Alexey Bataev0162e452014-07-22 10:10:35 +00006021StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
6022 Stmt *AStmt,
6023 SourceLocation StartLoc,
6024 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006025 if (!AStmt)
6026 return StmtError();
6027
David Majnemer9d168222016-08-05 17:44:54 +00006028 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00006029 // 1.2.2 OpenMP Language Terminology
6030 // Structured block - An executable statement with a single entry at the
6031 // top and a single exit at the bottom.
6032 // The point of exit cannot be a branch out of the structured block.
6033 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00006034 OpenMPClauseKind AtomicKind = OMPC_unknown;
6035 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006036 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00006037 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00006038 C->getClauseKind() == OMPC_update ||
6039 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00006040 if (AtomicKind != OMPC_unknown) {
6041 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
6042 << SourceRange(C->getLocStart(), C->getLocEnd());
6043 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
6044 << getOpenMPClauseName(AtomicKind);
6045 } else {
6046 AtomicKind = C->getClauseKind();
6047 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00006048 }
6049 }
6050 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006051
Alexey Bataev459dec02014-07-24 06:46:57 +00006052 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00006053 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6054 Body = EWC->getSubExpr();
6055
Alexey Bataev62cec442014-11-18 10:14:22 +00006056 Expr *X = nullptr;
6057 Expr *V = nullptr;
6058 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006059 Expr *UE = nullptr;
6060 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006061 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006062 // OpenMP [2.12.6, atomic Construct]
6063 // In the next expressions:
6064 // * x and v (as applicable) are both l-value expressions with scalar type.
6065 // * During the execution of an atomic region, multiple syntactic
6066 // occurrences of x must designate the same storage location.
6067 // * Neither of v and expr (as applicable) may access the storage location
6068 // designated by x.
6069 // * Neither of x and expr (as applicable) may access the storage location
6070 // designated by v.
6071 // * expr is an expression with scalar type.
6072 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6073 // * binop, binop=, ++, and -- are not overloaded operators.
6074 // * The expression x binop expr must be numerically equivalent to x binop
6075 // (expr). This requirement is satisfied if the operators in expr have
6076 // precedence greater than binop, or by using parentheses around expr or
6077 // subexpressions of expr.
6078 // * The expression expr binop x must be numerically equivalent to (expr)
6079 // binop x. This requirement is satisfied if the operators in expr have
6080 // precedence equal to or greater than binop, or by using parentheses around
6081 // expr or subexpressions of expr.
6082 // * For forms that allow multiple occurrences of x, the number of times
6083 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006084 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006085 enum {
6086 NotAnExpression,
6087 NotAnAssignmentOp,
6088 NotAScalarType,
6089 NotAnLValue,
6090 NoError
6091 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006092 SourceLocation ErrorLoc, NoteLoc;
6093 SourceRange ErrorRange, NoteRange;
6094 // If clause is read:
6095 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00006096 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6097 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006098 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6099 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6100 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6101 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6102 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6103 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6104 if (!X->isLValue() || !V->isLValue()) {
6105 auto NotLValueExpr = X->isLValue() ? V : X;
6106 ErrorFound = NotAnLValue;
6107 ErrorLoc = AtomicBinOp->getExprLoc();
6108 ErrorRange = AtomicBinOp->getSourceRange();
6109 NoteLoc = NotLValueExpr->getExprLoc();
6110 NoteRange = NotLValueExpr->getSourceRange();
6111 }
6112 } else if (!X->isInstantiationDependent() ||
6113 !V->isInstantiationDependent()) {
6114 auto NotScalarExpr =
6115 (X->isInstantiationDependent() || X->getType()->isScalarType())
6116 ? V
6117 : X;
6118 ErrorFound = NotAScalarType;
6119 ErrorLoc = AtomicBinOp->getExprLoc();
6120 ErrorRange = AtomicBinOp->getSourceRange();
6121 NoteLoc = NotScalarExpr->getExprLoc();
6122 NoteRange = NotScalarExpr->getSourceRange();
6123 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006124 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00006125 ErrorFound = NotAnAssignmentOp;
6126 ErrorLoc = AtomicBody->getExprLoc();
6127 ErrorRange = AtomicBody->getSourceRange();
6128 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6129 : AtomicBody->getExprLoc();
6130 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6131 : AtomicBody->getSourceRange();
6132 }
6133 } else {
6134 ErrorFound = NotAnExpression;
6135 NoteLoc = ErrorLoc = Body->getLocStart();
6136 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006137 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006138 if (ErrorFound != NoError) {
6139 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6140 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006141 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6142 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00006143 return StmtError();
6144 } else if (CurContext->isDependentContext())
6145 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00006146 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006147 enum {
6148 NotAnExpression,
6149 NotAnAssignmentOp,
6150 NotAScalarType,
6151 NotAnLValue,
6152 NoError
6153 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006154 SourceLocation ErrorLoc, NoteLoc;
6155 SourceRange ErrorRange, NoteRange;
6156 // If clause is write:
6157 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00006158 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6159 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006160 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6161 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00006162 X = AtomicBinOp->getLHS();
6163 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00006164 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6165 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6166 if (!X->isLValue()) {
6167 ErrorFound = NotAnLValue;
6168 ErrorLoc = AtomicBinOp->getExprLoc();
6169 ErrorRange = AtomicBinOp->getSourceRange();
6170 NoteLoc = X->getExprLoc();
6171 NoteRange = X->getSourceRange();
6172 }
6173 } else if (!X->isInstantiationDependent() ||
6174 !E->isInstantiationDependent()) {
6175 auto NotScalarExpr =
6176 (X->isInstantiationDependent() || X->getType()->isScalarType())
6177 ? E
6178 : X;
6179 ErrorFound = NotAScalarType;
6180 ErrorLoc = AtomicBinOp->getExprLoc();
6181 ErrorRange = AtomicBinOp->getSourceRange();
6182 NoteLoc = NotScalarExpr->getExprLoc();
6183 NoteRange = NotScalarExpr->getSourceRange();
6184 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006185 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00006186 ErrorFound = NotAnAssignmentOp;
6187 ErrorLoc = AtomicBody->getExprLoc();
6188 ErrorRange = AtomicBody->getSourceRange();
6189 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6190 : AtomicBody->getExprLoc();
6191 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6192 : AtomicBody->getSourceRange();
6193 }
6194 } else {
6195 ErrorFound = NotAnExpression;
6196 NoteLoc = ErrorLoc = Body->getLocStart();
6197 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006198 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006199 if (ErrorFound != NoError) {
6200 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6201 << ErrorRange;
6202 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6203 << NoteRange;
6204 return StmtError();
6205 } else if (CurContext->isDependentContext())
6206 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006207 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006208 // If clause is update:
6209 // x++;
6210 // x--;
6211 // ++x;
6212 // --x;
6213 // x binop= expr;
6214 // x = x binop expr;
6215 // x = expr binop x;
6216 OpenMPAtomicUpdateChecker Checker(*this);
6217 if (Checker.checkStatement(
6218 Body, (AtomicKind == OMPC_update)
6219 ? diag::err_omp_atomic_update_not_expression_statement
6220 : diag::err_omp_atomic_not_expression_statement,
6221 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006222 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006223 if (!CurContext->isDependentContext()) {
6224 E = Checker.getExpr();
6225 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006226 UE = Checker.getUpdateExpr();
6227 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006228 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006229 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006230 enum {
6231 NotAnAssignmentOp,
6232 NotACompoundStatement,
6233 NotTwoSubstatements,
6234 NotASpecificExpression,
6235 NoError
6236 } ErrorFound = NoError;
6237 SourceLocation ErrorLoc, NoteLoc;
6238 SourceRange ErrorRange, NoteRange;
6239 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6240 // If clause is a capture:
6241 // v = x++;
6242 // v = x--;
6243 // v = ++x;
6244 // v = --x;
6245 // v = x binop= expr;
6246 // v = x = x binop expr;
6247 // v = x = expr binop x;
6248 auto *AtomicBinOp =
6249 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6250 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6251 V = AtomicBinOp->getLHS();
6252 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6253 OpenMPAtomicUpdateChecker Checker(*this);
6254 if (Checker.checkStatement(
6255 Body, diag::err_omp_atomic_capture_not_expression_statement,
6256 diag::note_omp_atomic_update))
6257 return StmtError();
6258 E = Checker.getExpr();
6259 X = Checker.getX();
6260 UE = Checker.getUpdateExpr();
6261 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6262 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006263 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006264 ErrorLoc = AtomicBody->getExprLoc();
6265 ErrorRange = AtomicBody->getSourceRange();
6266 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6267 : AtomicBody->getExprLoc();
6268 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6269 : AtomicBody->getSourceRange();
6270 ErrorFound = NotAnAssignmentOp;
6271 }
6272 if (ErrorFound != NoError) {
6273 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6274 << ErrorRange;
6275 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6276 return StmtError();
6277 } else if (CurContext->isDependentContext()) {
6278 UE = V = E = X = nullptr;
6279 }
6280 } else {
6281 // If clause is a capture:
6282 // { v = x; x = expr; }
6283 // { v = x; x++; }
6284 // { v = x; x--; }
6285 // { v = x; ++x; }
6286 // { v = x; --x; }
6287 // { v = x; x binop= expr; }
6288 // { v = x; x = x binop expr; }
6289 // { v = x; x = expr binop x; }
6290 // { x++; v = x; }
6291 // { x--; v = x; }
6292 // { ++x; v = x; }
6293 // { --x; v = x; }
6294 // { x binop= expr; v = x; }
6295 // { x = x binop expr; v = x; }
6296 // { x = expr binop x; v = x; }
6297 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6298 // Check that this is { expr1; expr2; }
6299 if (CS->size() == 2) {
6300 auto *First = CS->body_front();
6301 auto *Second = CS->body_back();
6302 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6303 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6304 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6305 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6306 // Need to find what subexpression is 'v' and what is 'x'.
6307 OpenMPAtomicUpdateChecker Checker(*this);
6308 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6309 BinaryOperator *BinOp = nullptr;
6310 if (IsUpdateExprFound) {
6311 BinOp = dyn_cast<BinaryOperator>(First);
6312 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6313 }
6314 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6315 // { v = x; x++; }
6316 // { v = x; x--; }
6317 // { v = x; ++x; }
6318 // { v = x; --x; }
6319 // { v = x; x binop= expr; }
6320 // { v = x; x = x binop expr; }
6321 // { v = x; x = expr binop x; }
6322 // Check that the first expression has form v = x.
6323 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6324 llvm::FoldingSetNodeID XId, PossibleXId;
6325 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6326 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6327 IsUpdateExprFound = XId == PossibleXId;
6328 if (IsUpdateExprFound) {
6329 V = BinOp->getLHS();
6330 X = Checker.getX();
6331 E = Checker.getExpr();
6332 UE = Checker.getUpdateExpr();
6333 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006334 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006335 }
6336 }
6337 if (!IsUpdateExprFound) {
6338 IsUpdateExprFound = !Checker.checkStatement(First);
6339 BinOp = nullptr;
6340 if (IsUpdateExprFound) {
6341 BinOp = dyn_cast<BinaryOperator>(Second);
6342 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6343 }
6344 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6345 // { x++; v = x; }
6346 // { x--; v = x; }
6347 // { ++x; v = x; }
6348 // { --x; v = x; }
6349 // { x binop= expr; v = x; }
6350 // { x = x binop expr; v = x; }
6351 // { x = expr binop x; v = x; }
6352 // Check that the second expression has form v = x.
6353 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6354 llvm::FoldingSetNodeID XId, PossibleXId;
6355 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6356 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6357 IsUpdateExprFound = XId == PossibleXId;
6358 if (IsUpdateExprFound) {
6359 V = BinOp->getLHS();
6360 X = Checker.getX();
6361 E = Checker.getExpr();
6362 UE = Checker.getUpdateExpr();
6363 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006364 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006365 }
6366 }
6367 }
6368 if (!IsUpdateExprFound) {
6369 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006370 auto *FirstExpr = dyn_cast<Expr>(First);
6371 auto *SecondExpr = dyn_cast<Expr>(Second);
6372 if (!FirstExpr || !SecondExpr ||
6373 !(FirstExpr->isInstantiationDependent() ||
6374 SecondExpr->isInstantiationDependent())) {
6375 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6376 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006377 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006378 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6379 : First->getLocStart();
6380 NoteRange = ErrorRange = FirstBinOp
6381 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006382 : SourceRange(ErrorLoc, ErrorLoc);
6383 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006384 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6385 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6386 ErrorFound = NotAnAssignmentOp;
6387 NoteLoc = ErrorLoc = SecondBinOp
6388 ? SecondBinOp->getOperatorLoc()
6389 : Second->getLocStart();
6390 NoteRange = ErrorRange =
6391 SecondBinOp ? SecondBinOp->getSourceRange()
6392 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006393 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006394 auto *PossibleXRHSInFirst =
6395 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6396 auto *PossibleXLHSInSecond =
6397 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6398 llvm::FoldingSetNodeID X1Id, X2Id;
6399 PossibleXRHSInFirst->Profile(X1Id, Context,
6400 /*Canonical=*/true);
6401 PossibleXLHSInSecond->Profile(X2Id, Context,
6402 /*Canonical=*/true);
6403 IsUpdateExprFound = X1Id == X2Id;
6404 if (IsUpdateExprFound) {
6405 V = FirstBinOp->getLHS();
6406 X = SecondBinOp->getLHS();
6407 E = SecondBinOp->getRHS();
6408 UE = nullptr;
6409 IsXLHSInRHSPart = false;
6410 IsPostfixUpdate = true;
6411 } else {
6412 ErrorFound = NotASpecificExpression;
6413 ErrorLoc = FirstBinOp->getExprLoc();
6414 ErrorRange = FirstBinOp->getSourceRange();
6415 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6416 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6417 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006418 }
6419 }
6420 }
6421 }
6422 } else {
6423 NoteLoc = ErrorLoc = Body->getLocStart();
6424 NoteRange = ErrorRange =
6425 SourceRange(Body->getLocStart(), Body->getLocStart());
6426 ErrorFound = NotTwoSubstatements;
6427 }
6428 } else {
6429 NoteLoc = ErrorLoc = Body->getLocStart();
6430 NoteRange = ErrorRange =
6431 SourceRange(Body->getLocStart(), Body->getLocStart());
6432 ErrorFound = NotACompoundStatement;
6433 }
6434 if (ErrorFound != NoError) {
6435 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6436 << ErrorRange;
6437 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6438 return StmtError();
6439 } else if (CurContext->isDependentContext()) {
6440 UE = V = E = X = nullptr;
6441 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006442 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006443 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006444
Reid Kleckner8d485b82018-03-08 01:12:22 +00006445 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev0162e452014-07-22 10:10:35 +00006446
Alexey Bataev62cec442014-11-18 10:14:22 +00006447 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006448 X, V, E, UE, IsXLHSInRHSPart,
6449 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006450}
6451
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006452StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6453 Stmt *AStmt,
6454 SourceLocation StartLoc,
6455 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006456 if (!AStmt)
6457 return StmtError();
6458
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006459 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6460 // 1.2.2 OpenMP Language Terminology
6461 // Structured block - An executable statement with a single entry at the
6462 // top and a single exit at the bottom.
6463 // The point of exit cannot be a branch out of the structured block.
6464 // longjmp() and throw() must not violate the entry/exit criteria.
6465 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00006466 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
6467 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6468 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6469 // 1.2.2 OpenMP Language Terminology
6470 // Structured block - An executable statement with a single entry at the
6471 // top and a single exit at the bottom.
6472 // The point of exit cannot be a branch out of the structured block.
6473 // longjmp() and throw() must not violate the entry/exit criteria.
6474 CS->getCapturedDecl()->setNothrow();
6475 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006476
Alexey Bataev13314bf2014-10-09 04:18:56 +00006477 // OpenMP [2.16, Nesting of Regions]
6478 // If specified, a teams construct must be contained within a target
6479 // construct. That target construct must contain no statements or directives
6480 // outside of the teams construct.
6481 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00006482 Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006483 bool OMPTeamsFound = true;
6484 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6485 auto I = CS->body_begin();
6486 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00006487 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006488 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6489 OMPTeamsFound = false;
6490 break;
6491 }
6492 ++I;
6493 }
6494 assert(I != CS->body_end() && "Not found statement");
6495 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006496 } else {
6497 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6498 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006499 }
6500 if (!OMPTeamsFound) {
6501 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6502 Diag(DSAStack->getInnerTeamsRegionLoc(),
6503 diag::note_omp_nested_teams_construct_here);
6504 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6505 << isa<OMPExecutableDirective>(S);
6506 return StmtError();
6507 }
6508 }
6509
Reid Kleckner8d485b82018-03-08 01:12:22 +00006510 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006511
6512 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6513}
6514
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006515StmtResult
6516Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6517 Stmt *AStmt, SourceLocation StartLoc,
6518 SourceLocation EndLoc) {
6519 if (!AStmt)
6520 return StmtError();
6521
6522 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6523 // 1.2.2 OpenMP Language Terminology
6524 // Structured block - An executable statement with a single entry at the
6525 // top and a single exit at the bottom.
6526 // The point of exit cannot be a branch out of the structured block.
6527 // longjmp() and throw() must not violate the entry/exit criteria.
6528 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00006529 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
6530 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6531 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6532 // 1.2.2 OpenMP Language Terminology
6533 // Structured block - An executable statement with a single entry at the
6534 // top and a single exit at the bottom.
6535 // The point of exit cannot be a branch out of the structured block.
6536 // longjmp() and throw() must not violate the entry/exit criteria.
6537 CS->getCapturedDecl()->setNothrow();
6538 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006539
Reid Kleckner8d485b82018-03-08 01:12:22 +00006540 getCurFunction()->setHasBranchProtectedScope();
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006541
6542 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6543 AStmt);
6544}
6545
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006546StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6547 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6548 SourceLocation EndLoc,
6549 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6550 if (!AStmt)
6551 return StmtError();
6552
6553 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6554 // 1.2.2 OpenMP Language Terminology
6555 // Structured block - An executable statement with a single entry at the
6556 // top and a single exit at the bottom.
6557 // The point of exit cannot be a branch out of the structured block.
6558 // longjmp() and throw() must not violate the entry/exit criteria.
6559 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006560 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6561 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6562 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6563 // 1.2.2 OpenMP Language Terminology
6564 // Structured block - An executable statement with a single entry at the
6565 // top and a single exit at the bottom.
6566 // The point of exit cannot be a branch out of the structured block.
6567 // longjmp() and throw() must not violate the entry/exit criteria.
6568 CS->getCapturedDecl()->setNothrow();
6569 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006570
6571 OMPLoopDirective::HelperExprs B;
6572 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6573 // define the nested loops number.
6574 unsigned NestedLoopCount =
6575 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006576 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006577 VarsWithImplicitDSA, B);
6578 if (NestedLoopCount == 0)
6579 return StmtError();
6580
6581 assert((CurContext->isDependentContext() || B.builtAll()) &&
6582 "omp target parallel for loop exprs were not built");
6583
6584 if (!CurContext->isDependentContext()) {
6585 // Finalize the clauses that need pre-built expressions for CodeGen.
6586 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006587 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006588 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006589 B.NumIterations, *this, CurScope,
6590 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006591 return StmtError();
6592 }
6593 }
6594
Reid Kleckner8d485b82018-03-08 01:12:22 +00006595 getCurFunction()->setHasBranchProtectedScope();
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006596 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6597 NestedLoopCount, Clauses, AStmt,
6598 B, DSAStack->isCancelRegion());
6599}
6600
Alexey Bataev95b64a92017-05-30 16:00:04 +00006601/// Check for existence of a map clause in the list of clauses.
6602static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6603 const OpenMPClauseKind K) {
6604 return llvm::any_of(
6605 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6606}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006607
Alexey Bataev95b64a92017-05-30 16:00:04 +00006608template <typename... Params>
6609static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6610 const Params... ClauseTypes) {
6611 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006612}
6613
Michael Wong65f367f2015-07-21 13:44:28 +00006614StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6615 Stmt *AStmt,
6616 SourceLocation StartLoc,
6617 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006618 if (!AStmt)
6619 return StmtError();
6620
6621 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6622
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006623 // OpenMP [2.10.1, Restrictions, p. 97]
6624 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006625 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6626 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6627 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006628 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006629 return StmtError();
6630 }
6631
Reid Kleckner8d485b82018-03-08 01:12:22 +00006632 getCurFunction()->setHasBranchProtectedScope();
Michael Wong65f367f2015-07-21 13:44:28 +00006633
6634 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6635 AStmt);
6636}
6637
Samuel Antaodf67fc42016-01-19 19:15:56 +00006638StmtResult
6639Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6640 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006641 SourceLocation EndLoc, Stmt *AStmt) {
6642 if (!AStmt)
6643 return StmtError();
6644
6645 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6646 // 1.2.2 OpenMP Language Terminology
6647 // Structured block - An executable statement with a single entry at the
6648 // top and a single exit at the bottom.
6649 // The point of exit cannot be a branch out of the structured block.
6650 // longjmp() and throw() must not violate the entry/exit criteria.
6651 CS->getCapturedDecl()->setNothrow();
6652 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
6653 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6654 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6655 // 1.2.2 OpenMP Language Terminology
6656 // Structured block - An executable statement with a single entry at the
6657 // top and a single exit at the bottom.
6658 // The point of exit cannot be a branch out of the structured block.
6659 // longjmp() and throw() must not violate the entry/exit criteria.
6660 CS->getCapturedDecl()->setNothrow();
6661 }
6662
Samuel Antaodf67fc42016-01-19 19:15:56 +00006663 // OpenMP [2.10.2, Restrictions, p. 99]
6664 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006665 if (!hasClauses(Clauses, OMPC_map)) {
6666 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6667 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006668 return StmtError();
6669 }
6670
Alexey Bataev7828b252017-11-21 17:08:48 +00006671 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6672 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006673}
6674
Samuel Antao72590762016-01-19 20:04:50 +00006675StmtResult
6676Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6677 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006678 SourceLocation EndLoc, Stmt *AStmt) {
6679 if (!AStmt)
6680 return StmtError();
6681
6682 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6683 // 1.2.2 OpenMP Language Terminology
6684 // Structured block - An executable statement with a single entry at the
6685 // top and a single exit at the bottom.
6686 // The point of exit cannot be a branch out of the structured block.
6687 // longjmp() and throw() must not violate the entry/exit criteria.
6688 CS->getCapturedDecl()->setNothrow();
6689 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
6690 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6691 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6692 // 1.2.2 OpenMP Language Terminology
6693 // Structured block - An executable statement with a single entry at the
6694 // top and a single exit at the bottom.
6695 // The point of exit cannot be a branch out of the structured block.
6696 // longjmp() and throw() must not violate the entry/exit criteria.
6697 CS->getCapturedDecl()->setNothrow();
6698 }
6699
Samuel Antao72590762016-01-19 20:04:50 +00006700 // OpenMP [2.10.3, Restrictions, p. 102]
6701 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006702 if (!hasClauses(Clauses, OMPC_map)) {
6703 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6704 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006705 return StmtError();
6706 }
6707
Alexey Bataev7828b252017-11-21 17:08:48 +00006708 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6709 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00006710}
6711
Samuel Antao686c70c2016-05-26 17:30:50 +00006712StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6713 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006714 SourceLocation EndLoc,
6715 Stmt *AStmt) {
6716 if (!AStmt)
6717 return StmtError();
6718
6719 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6720 // 1.2.2 OpenMP Language Terminology
6721 // Structured block - An executable statement with a single entry at the
6722 // top and a single exit at the bottom.
6723 // The point of exit cannot be a branch out of the structured block.
6724 // longjmp() and throw() must not violate the entry/exit criteria.
6725 CS->getCapturedDecl()->setNothrow();
6726 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
6727 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6728 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6729 // 1.2.2 OpenMP Language Terminology
6730 // Structured block - An executable statement with a single entry at the
6731 // top and a single exit at the bottom.
6732 // The point of exit cannot be a branch out of the structured block.
6733 // longjmp() and throw() must not violate the entry/exit criteria.
6734 CS->getCapturedDecl()->setNothrow();
6735 }
6736
Alexey Bataev95b64a92017-05-30 16:00:04 +00006737 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006738 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6739 return StmtError();
6740 }
Alexey Bataev7828b252017-11-21 17:08:48 +00006741 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
6742 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00006743}
6744
Alexey Bataev13314bf2014-10-09 04:18:56 +00006745StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6746 Stmt *AStmt, SourceLocation StartLoc,
6747 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006748 if (!AStmt)
6749 return StmtError();
6750
Alexey Bataev13314bf2014-10-09 04:18:56 +00006751 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6752 // 1.2.2 OpenMP Language Terminology
6753 // Structured block - An executable statement with a single entry at the
6754 // top and a single exit at the bottom.
6755 // The point of exit cannot be a branch out of the structured block.
6756 // longjmp() and throw() must not violate the entry/exit criteria.
6757 CS->getCapturedDecl()->setNothrow();
6758
Reid Kleckner8d485b82018-03-08 01:12:22 +00006759 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev13314bf2014-10-09 04:18:56 +00006760
Alexey Bataevceabd412017-11-30 18:01:54 +00006761 DSAStack->setParentTeamsRegionLoc(StartLoc);
6762
Alexey Bataev13314bf2014-10-09 04:18:56 +00006763 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6764}
6765
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006766StmtResult
6767Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6768 SourceLocation EndLoc,
6769 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006770 if (DSAStack->isParentNowaitRegion()) {
6771 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6772 return StmtError();
6773 }
6774 if (DSAStack->isParentOrderedRegion()) {
6775 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6776 return StmtError();
6777 }
6778 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6779 CancelRegion);
6780}
6781
Alexey Bataev87933c72015-09-18 08:07:34 +00006782StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6783 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006784 SourceLocation EndLoc,
6785 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006786 if (DSAStack->isParentNowaitRegion()) {
6787 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6788 return StmtError();
6789 }
6790 if (DSAStack->isParentOrderedRegion()) {
6791 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6792 return StmtError();
6793 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006794 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006795 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6796 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006797}
6798
Alexey Bataev382967a2015-12-08 12:06:20 +00006799static bool checkGrainsizeNumTasksClauses(Sema &S,
6800 ArrayRef<OMPClause *> Clauses) {
6801 OMPClause *PrevClause = nullptr;
6802 bool ErrorFound = false;
6803 for (auto *C : Clauses) {
6804 if (C->getClauseKind() == OMPC_grainsize ||
6805 C->getClauseKind() == OMPC_num_tasks) {
6806 if (!PrevClause)
6807 PrevClause = C;
6808 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6809 S.Diag(C->getLocStart(),
6810 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6811 << getOpenMPClauseName(C->getClauseKind())
6812 << getOpenMPClauseName(PrevClause->getClauseKind());
6813 S.Diag(PrevClause->getLocStart(),
6814 diag::note_omp_previous_grainsize_num_tasks)
6815 << getOpenMPClauseName(PrevClause->getClauseKind());
6816 ErrorFound = true;
6817 }
6818 }
6819 }
6820 return ErrorFound;
6821}
6822
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006823static bool checkReductionClauseWithNogroup(Sema &S,
6824 ArrayRef<OMPClause *> Clauses) {
6825 OMPClause *ReductionClause = nullptr;
6826 OMPClause *NogroupClause = nullptr;
6827 for (auto *C : Clauses) {
6828 if (C->getClauseKind() == OMPC_reduction) {
6829 ReductionClause = C;
6830 if (NogroupClause)
6831 break;
6832 continue;
6833 }
6834 if (C->getClauseKind() == OMPC_nogroup) {
6835 NogroupClause = C;
6836 if (ReductionClause)
6837 break;
6838 continue;
6839 }
6840 }
6841 if (ReductionClause && NogroupClause) {
6842 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6843 << SourceRange(NogroupClause->getLocStart(),
6844 NogroupClause->getLocEnd());
6845 return true;
6846 }
6847 return false;
6848}
6849
Alexey Bataev49f6e782015-12-01 04:18:41 +00006850StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6851 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6852 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006853 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006854 if (!AStmt)
6855 return StmtError();
6856
6857 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6858 OMPLoopDirective::HelperExprs B;
6859 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6860 // define the nested loops number.
6861 unsigned NestedLoopCount =
6862 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006863 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006864 VarsWithImplicitDSA, B);
6865 if (NestedLoopCount == 0)
6866 return StmtError();
6867
6868 assert((CurContext->isDependentContext() || B.builtAll()) &&
6869 "omp for loop exprs were not built");
6870
Alexey Bataev382967a2015-12-08 12:06:20 +00006871 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6872 // The grainsize clause and num_tasks clause are mutually exclusive and may
6873 // not appear on the same taskloop directive.
6874 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6875 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006876 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6877 // If a reduction clause is present on the taskloop directive, the nogroup
6878 // clause must not be specified.
6879 if (checkReductionClauseWithNogroup(*this, Clauses))
6880 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006881
Reid Kleckner8d485b82018-03-08 01:12:22 +00006882 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev49f6e782015-12-01 04:18:41 +00006883 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6884 NestedLoopCount, Clauses, AStmt, B);
6885}
6886
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006887StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6888 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6889 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006890 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006891 if (!AStmt)
6892 return StmtError();
6893
6894 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6895 OMPLoopDirective::HelperExprs B;
6896 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6897 // define the nested loops number.
6898 unsigned NestedLoopCount =
6899 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6900 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6901 VarsWithImplicitDSA, B);
6902 if (NestedLoopCount == 0)
6903 return StmtError();
6904
6905 assert((CurContext->isDependentContext() || B.builtAll()) &&
6906 "omp for loop exprs were not built");
6907
Alexey Bataev5a3af132016-03-29 08:58:54 +00006908 if (!CurContext->isDependentContext()) {
6909 // Finalize the clauses that need pre-built expressions for CodeGen.
6910 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006911 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006912 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006913 B.NumIterations, *this, CurScope,
6914 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006915 return StmtError();
6916 }
6917 }
6918
Alexey Bataev382967a2015-12-08 12:06:20 +00006919 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6920 // The grainsize clause and num_tasks clause are mutually exclusive and may
6921 // not appear on the same taskloop directive.
6922 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6923 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006924 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6925 // If a reduction clause is present on the taskloop directive, the nogroup
6926 // clause must not be specified.
6927 if (checkReductionClauseWithNogroup(*this, Clauses))
6928 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00006929 if (checkSimdlenSafelenSpecified(*this, Clauses))
6930 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006931
Reid Kleckner8d485b82018-03-08 01:12:22 +00006932 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006933 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6934 NestedLoopCount, Clauses, AStmt, B);
6935}
6936
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006937StmtResult Sema::ActOnOpenMPDistributeDirective(
6938 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6939 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006940 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006941 if (!AStmt)
6942 return StmtError();
6943
6944 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6945 OMPLoopDirective::HelperExprs B;
6946 // In presence of clause 'collapse' with number of loops, it will
6947 // define the nested loops number.
6948 unsigned NestedLoopCount =
6949 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6950 nullptr /*ordered not a clause on distribute*/, AStmt,
6951 *this, *DSAStack, VarsWithImplicitDSA, B);
6952 if (NestedLoopCount == 0)
6953 return StmtError();
6954
6955 assert((CurContext->isDependentContext() || B.builtAll()) &&
6956 "omp for loop exprs were not built");
6957
Reid Kleckner8d485b82018-03-08 01:12:22 +00006958 getCurFunction()->setHasBranchProtectedScope();
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006959 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6960 NestedLoopCount, Clauses, AStmt, B);
6961}
6962
Carlo Bertolli9925f152016-06-27 14:55:37 +00006963StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6964 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6965 SourceLocation EndLoc,
6966 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6967 if (!AStmt)
6968 return StmtError();
6969
6970 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6971 // 1.2.2 OpenMP Language Terminology
6972 // Structured block - An executable statement with a single entry at the
6973 // top and a single exit at the bottom.
6974 // The point of exit cannot be a branch out of the structured block.
6975 // longjmp() and throw() must not violate the entry/exit criteria.
6976 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00006977 for (int ThisCaptureLevel =
6978 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
6979 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6980 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6981 // 1.2.2 OpenMP Language Terminology
6982 // Structured block - An executable statement with a single entry at the
6983 // top and a single exit at the bottom.
6984 // The point of exit cannot be a branch out of the structured block.
6985 // longjmp() and throw() must not violate the entry/exit criteria.
6986 CS->getCapturedDecl()->setNothrow();
6987 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00006988
6989 OMPLoopDirective::HelperExprs B;
6990 // In presence of clause 'collapse' with number of loops, it will
6991 // define the nested loops number.
6992 unsigned NestedLoopCount = CheckOpenMPLoop(
6993 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00006994 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00006995 VarsWithImplicitDSA, B);
6996 if (NestedLoopCount == 0)
6997 return StmtError();
6998
6999 assert((CurContext->isDependentContext() || B.builtAll()) &&
7000 "omp for loop exprs were not built");
7001
Reid Kleckner8d485b82018-03-08 01:12:22 +00007002 getCurFunction()->setHasBranchProtectedScope();
Carlo Bertolli9925f152016-06-27 14:55:37 +00007003 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007004 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7005 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00007006}
7007
Kelvin Li4a39add2016-07-05 05:00:15 +00007008StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
7009 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7010 SourceLocation EndLoc,
7011 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7012 if (!AStmt)
7013 return StmtError();
7014
7015 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7016 // 1.2.2 OpenMP Language Terminology
7017 // Structured block - An executable statement with a single entry at the
7018 // top and a single exit at the bottom.
7019 // The point of exit cannot be a branch out of the structured block.
7020 // longjmp() and throw() must not violate the entry/exit criteria.
7021 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00007022 for (int ThisCaptureLevel =
7023 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
7024 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7025 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7026 // 1.2.2 OpenMP Language Terminology
7027 // Structured block - An executable statement with a single entry at the
7028 // top and a single exit at the bottom.
7029 // The point of exit cannot be a branch out of the structured block.
7030 // longjmp() and throw() must not violate the entry/exit criteria.
7031 CS->getCapturedDecl()->setNothrow();
7032 }
Kelvin Li4a39add2016-07-05 05:00:15 +00007033
7034 OMPLoopDirective::HelperExprs B;
7035 // In presence of clause 'collapse' with number of loops, it will
7036 // define the nested loops number.
7037 unsigned NestedLoopCount = CheckOpenMPLoop(
7038 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00007039 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00007040 VarsWithImplicitDSA, B);
7041 if (NestedLoopCount == 0)
7042 return StmtError();
7043
7044 assert((CurContext->isDependentContext() || B.builtAll()) &&
7045 "omp for loop exprs were not built");
7046
Alexey Bataev438388c2017-11-22 18:34:02 +00007047 if (!CurContext->isDependentContext()) {
7048 // Finalize the clauses that need pre-built expressions for CodeGen.
7049 for (auto C : Clauses) {
7050 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7051 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7052 B.NumIterations, *this, CurScope,
7053 DSAStack))
7054 return StmtError();
7055 }
7056 }
7057
Kelvin Lic5609492016-07-15 04:39:07 +00007058 if (checkSimdlenSafelenSpecified(*this, Clauses))
7059 return StmtError();
7060
Reid Kleckner8d485b82018-03-08 01:12:22 +00007061 getCurFunction()->setHasBranchProtectedScope();
Kelvin Li4a39add2016-07-05 05:00:15 +00007062 return OMPDistributeParallelForSimdDirective::Create(
7063 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7064}
7065
Kelvin Li787f3fc2016-07-06 04:45:38 +00007066StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7067 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7068 SourceLocation EndLoc,
7069 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7070 if (!AStmt)
7071 return StmtError();
7072
7073 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7074 // 1.2.2 OpenMP Language Terminology
7075 // Structured block - An executable statement with a single entry at the
7076 // top and a single exit at the bottom.
7077 // The point of exit cannot be a branch out of the structured block.
7078 // longjmp() and throw() must not violate the entry/exit criteria.
7079 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00007080 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7081 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7082 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7083 // 1.2.2 OpenMP Language Terminology
7084 // Structured block - An executable statement with a single entry at the
7085 // top and a single exit at the bottom.
7086 // The point of exit cannot be a branch out of the structured block.
7087 // longjmp() and throw() must not violate the entry/exit criteria.
7088 CS->getCapturedDecl()->setNothrow();
7089 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007090
7091 OMPLoopDirective::HelperExprs B;
7092 // In presence of clause 'collapse' with number of loops, it will
7093 // define the nested loops number.
7094 unsigned NestedLoopCount =
7095 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007096 nullptr /*ordered not a clause on distribute*/, CS, *this,
7097 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007098 if (NestedLoopCount == 0)
7099 return StmtError();
7100
7101 assert((CurContext->isDependentContext() || B.builtAll()) &&
7102 "omp for loop exprs were not built");
7103
Alexey Bataev438388c2017-11-22 18:34:02 +00007104 if (!CurContext->isDependentContext()) {
7105 // Finalize the clauses that need pre-built expressions for CodeGen.
7106 for (auto C : Clauses) {
7107 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7108 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7109 B.NumIterations, *this, CurScope,
7110 DSAStack))
7111 return StmtError();
7112 }
7113 }
7114
Kelvin Lic5609492016-07-15 04:39:07 +00007115 if (checkSimdlenSafelenSpecified(*this, Clauses))
7116 return StmtError();
7117
Reid Kleckner8d485b82018-03-08 01:12:22 +00007118 getCurFunction()->setHasBranchProtectedScope();
Kelvin Li787f3fc2016-07-06 04:45:38 +00007119 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7120 NestedLoopCount, Clauses, AStmt, B);
7121}
7122
Kelvin Lia579b912016-07-14 02:54:56 +00007123StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7124 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7125 SourceLocation EndLoc,
7126 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7127 if (!AStmt)
7128 return StmtError();
7129
7130 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7131 // 1.2.2 OpenMP Language Terminology
7132 // Structured block - An executable statement with a single entry at the
7133 // top and a single exit at the bottom.
7134 // The point of exit cannot be a branch out of the structured block.
7135 // longjmp() and throw() must not violate the entry/exit criteria.
7136 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007137 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7138 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7139 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7140 // 1.2.2 OpenMP Language Terminology
7141 // Structured block - An executable statement with a single entry at the
7142 // top and a single exit at the bottom.
7143 // The point of exit cannot be a branch out of the structured block.
7144 // longjmp() and throw() must not violate the entry/exit criteria.
7145 CS->getCapturedDecl()->setNothrow();
7146 }
Kelvin Lia579b912016-07-14 02:54:56 +00007147
7148 OMPLoopDirective::HelperExprs B;
7149 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7150 // define the nested loops number.
7151 unsigned NestedLoopCount = CheckOpenMPLoop(
7152 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007153 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00007154 VarsWithImplicitDSA, B);
7155 if (NestedLoopCount == 0)
7156 return StmtError();
7157
7158 assert((CurContext->isDependentContext() || B.builtAll()) &&
7159 "omp target parallel for simd loop exprs were not built");
7160
7161 if (!CurContext->isDependentContext()) {
7162 // Finalize the clauses that need pre-built expressions for CodeGen.
7163 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007164 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00007165 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7166 B.NumIterations, *this, CurScope,
7167 DSAStack))
7168 return StmtError();
7169 }
7170 }
Kelvin Lic5609492016-07-15 04:39:07 +00007171 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00007172 return StmtError();
7173
Reid Kleckner8d485b82018-03-08 01:12:22 +00007174 getCurFunction()->setHasBranchProtectedScope();
Kelvin Lia579b912016-07-14 02:54:56 +00007175 return OMPTargetParallelForSimdDirective::Create(
7176 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7177}
7178
Kelvin Li986330c2016-07-20 22:57:10 +00007179StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7180 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7181 SourceLocation EndLoc,
7182 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7183 if (!AStmt)
7184 return StmtError();
7185
7186 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7187 // 1.2.2 OpenMP Language Terminology
7188 // Structured block - An executable statement with a single entry at the
7189 // top and a single exit at the bottom.
7190 // The point of exit cannot be a branch out of the structured block.
7191 // longjmp() and throw() must not violate the entry/exit criteria.
7192 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00007193 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7194 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7195 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7196 // 1.2.2 OpenMP Language Terminology
7197 // Structured block - An executable statement with a single entry at the
7198 // top and a single exit at the bottom.
7199 // The point of exit cannot be a branch out of the structured block.
7200 // longjmp() and throw() must not violate the entry/exit criteria.
7201 CS->getCapturedDecl()->setNothrow();
7202 }
7203
Kelvin Li986330c2016-07-20 22:57:10 +00007204 OMPLoopDirective::HelperExprs B;
7205 // In presence of clause 'collapse' with number of loops, it will define the
7206 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00007207 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00007208 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00007209 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00007210 VarsWithImplicitDSA, B);
7211 if (NestedLoopCount == 0)
7212 return StmtError();
7213
7214 assert((CurContext->isDependentContext() || B.builtAll()) &&
7215 "omp target simd loop exprs were not built");
7216
7217 if (!CurContext->isDependentContext()) {
7218 // Finalize the clauses that need pre-built expressions for CodeGen.
7219 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007220 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00007221 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7222 B.NumIterations, *this, CurScope,
7223 DSAStack))
7224 return StmtError();
7225 }
7226 }
7227
7228 if (checkSimdlenSafelenSpecified(*this, Clauses))
7229 return StmtError();
7230
Reid Kleckner8d485b82018-03-08 01:12:22 +00007231 getCurFunction()->setHasBranchProtectedScope();
Kelvin Li986330c2016-07-20 22:57:10 +00007232 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7233 NestedLoopCount, Clauses, AStmt, B);
7234}
7235
Kelvin Li02532872016-08-05 14:37:37 +00007236StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7237 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7238 SourceLocation EndLoc,
7239 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7240 if (!AStmt)
7241 return StmtError();
7242
7243 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7244 // 1.2.2 OpenMP Language Terminology
7245 // Structured block - An executable statement with a single entry at the
7246 // top and a single exit at the bottom.
7247 // The point of exit cannot be a branch out of the structured block.
7248 // longjmp() and throw() must not violate the entry/exit criteria.
7249 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007250 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7251 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7252 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7253 // 1.2.2 OpenMP Language Terminology
7254 // Structured block - An executable statement with a single entry at the
7255 // top and a single exit at the bottom.
7256 // The point of exit cannot be a branch out of the structured block.
7257 // longjmp() and throw() must not violate the entry/exit criteria.
7258 CS->getCapturedDecl()->setNothrow();
7259 }
Kelvin Li02532872016-08-05 14:37:37 +00007260
7261 OMPLoopDirective::HelperExprs B;
7262 // In presence of clause 'collapse' with number of loops, it will
7263 // define the nested loops number.
7264 unsigned NestedLoopCount =
7265 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007266 nullptr /*ordered not a clause on distribute*/, CS, *this,
7267 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00007268 if (NestedLoopCount == 0)
7269 return StmtError();
7270
7271 assert((CurContext->isDependentContext() || B.builtAll()) &&
7272 "omp teams distribute loop exprs were not built");
7273
Reid Kleckner8d485b82018-03-08 01:12:22 +00007274 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007275
7276 DSAStack->setParentTeamsRegionLoc(StartLoc);
7277
David Majnemer9d168222016-08-05 17:44:54 +00007278 return OMPTeamsDistributeDirective::Create(
7279 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00007280}
7281
Kelvin Li4e325f72016-10-25 12:50:55 +00007282StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7283 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7284 SourceLocation EndLoc,
7285 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7286 if (!AStmt)
7287 return StmtError();
7288
7289 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7290 // 1.2.2 OpenMP Language Terminology
7291 // Structured block - An executable statement with a single entry at the
7292 // top and a single exit at the bottom.
7293 // The point of exit cannot be a branch out of the structured block.
7294 // longjmp() and throw() must not violate the entry/exit criteria.
7295 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00007296 for (int ThisCaptureLevel =
7297 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7298 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7299 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7300 // 1.2.2 OpenMP Language Terminology
7301 // Structured block - An executable statement with a single entry at the
7302 // top and a single exit at the bottom.
7303 // The point of exit cannot be a branch out of the structured block.
7304 // longjmp() and throw() must not violate the entry/exit criteria.
7305 CS->getCapturedDecl()->setNothrow();
7306 }
7307
Kelvin Li4e325f72016-10-25 12:50:55 +00007308
7309 OMPLoopDirective::HelperExprs B;
7310 // In presence of clause 'collapse' with number of loops, it will
7311 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00007312 unsigned NestedLoopCount = CheckOpenMPLoop(
7313 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00007314 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00007315 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00007316
7317 if (NestedLoopCount == 0)
7318 return StmtError();
7319
7320 assert((CurContext->isDependentContext() || B.builtAll()) &&
7321 "omp teams distribute simd loop exprs were not built");
7322
7323 if (!CurContext->isDependentContext()) {
7324 // Finalize the clauses that need pre-built expressions for CodeGen.
7325 for (auto C : Clauses) {
7326 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7327 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7328 B.NumIterations, *this, CurScope,
7329 DSAStack))
7330 return StmtError();
7331 }
7332 }
7333
7334 if (checkSimdlenSafelenSpecified(*this, Clauses))
7335 return StmtError();
7336
Reid Kleckner8d485b82018-03-08 01:12:22 +00007337 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007338
7339 DSAStack->setParentTeamsRegionLoc(StartLoc);
7340
Kelvin Li4e325f72016-10-25 12:50:55 +00007341 return OMPTeamsDistributeSimdDirective::Create(
7342 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7343}
7344
Kelvin Li579e41c2016-11-30 23:51:03 +00007345StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7346 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7347 SourceLocation EndLoc,
7348 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7349 if (!AStmt)
7350 return StmtError();
7351
7352 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7353 // 1.2.2 OpenMP Language Terminology
7354 // Structured block - An executable statement with a single entry at the
7355 // top and a single exit at the bottom.
7356 // The point of exit cannot be a branch out of the structured block.
7357 // longjmp() and throw() must not violate the entry/exit criteria.
7358 CS->getCapturedDecl()->setNothrow();
7359
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007360 for (int ThisCaptureLevel =
7361 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7362 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7363 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7364 // 1.2.2 OpenMP Language Terminology
7365 // Structured block - An executable statement with a single entry at the
7366 // top and a single exit at the bottom.
7367 // The point of exit cannot be a branch out of the structured block.
7368 // longjmp() and throw() must not violate the entry/exit criteria.
7369 CS->getCapturedDecl()->setNothrow();
7370 }
7371
Kelvin Li579e41c2016-11-30 23:51:03 +00007372 OMPLoopDirective::HelperExprs B;
7373 // In presence of clause 'collapse' with number of loops, it will
7374 // define the nested loops number.
7375 auto NestedLoopCount = CheckOpenMPLoop(
7376 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007377 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00007378 VarsWithImplicitDSA, B);
7379
7380 if (NestedLoopCount == 0)
7381 return StmtError();
7382
7383 assert((CurContext->isDependentContext() || B.builtAll()) &&
7384 "omp for loop exprs were not built");
7385
7386 if (!CurContext->isDependentContext()) {
7387 // Finalize the clauses that need pre-built expressions for CodeGen.
7388 for (auto C : Clauses) {
7389 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7390 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7391 B.NumIterations, *this, CurScope,
7392 DSAStack))
7393 return StmtError();
7394 }
7395 }
7396
7397 if (checkSimdlenSafelenSpecified(*this, Clauses))
7398 return StmtError();
7399
Reid Kleckner8d485b82018-03-08 01:12:22 +00007400 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007401
7402 DSAStack->setParentTeamsRegionLoc(StartLoc);
7403
Kelvin Li579e41c2016-11-30 23:51:03 +00007404 return OMPTeamsDistributeParallelForSimdDirective::Create(
7405 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7406}
7407
Kelvin Li7ade93f2016-12-09 03:24:30 +00007408StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7409 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7410 SourceLocation EndLoc,
7411 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7412 if (!AStmt)
7413 return StmtError();
7414
7415 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7416 // 1.2.2 OpenMP Language Terminology
7417 // Structured block - An executable statement with a single entry at the
7418 // top and a single exit at the bottom.
7419 // The point of exit cannot be a branch out of the structured block.
7420 // longjmp() and throw() must not violate the entry/exit criteria.
7421 CS->getCapturedDecl()->setNothrow();
7422
Carlo Bertolli62fae152017-11-20 20:46:39 +00007423 for (int ThisCaptureLevel =
7424 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7425 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7426 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7427 // 1.2.2 OpenMP Language Terminology
7428 // Structured block - An executable statement with a single entry at the
7429 // top and a single exit at the bottom.
7430 // The point of exit cannot be a branch out of the structured block.
7431 // longjmp() and throw() must not violate the entry/exit criteria.
7432 CS->getCapturedDecl()->setNothrow();
7433 }
7434
Kelvin Li7ade93f2016-12-09 03:24:30 +00007435 OMPLoopDirective::HelperExprs B;
7436 // In presence of clause 'collapse' with number of loops, it will
7437 // define the nested loops number.
7438 unsigned NestedLoopCount = CheckOpenMPLoop(
7439 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00007440 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00007441 VarsWithImplicitDSA, B);
7442
7443 if (NestedLoopCount == 0)
7444 return StmtError();
7445
7446 assert((CurContext->isDependentContext() || B.builtAll()) &&
7447 "omp for loop exprs were not built");
7448
Reid Kleckner8d485b82018-03-08 01:12:22 +00007449 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007450
7451 DSAStack->setParentTeamsRegionLoc(StartLoc);
7452
Kelvin Li7ade93f2016-12-09 03:24:30 +00007453 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007454 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7455 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00007456}
7457
Kelvin Libf594a52016-12-17 05:48:59 +00007458StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7459 Stmt *AStmt,
7460 SourceLocation StartLoc,
7461 SourceLocation EndLoc) {
7462 if (!AStmt)
7463 return StmtError();
7464
7465 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7466 // 1.2.2 OpenMP Language Terminology
7467 // Structured block - An executable statement with a single entry at the
7468 // top and a single exit at the bottom.
7469 // The point of exit cannot be a branch out of the structured block.
7470 // longjmp() and throw() must not violate the entry/exit criteria.
7471 CS->getCapturedDecl()->setNothrow();
7472
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00007473 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7474 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7475 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7476 // 1.2.2 OpenMP Language Terminology
7477 // Structured block - An executable statement with a single entry at the
7478 // top and a single exit at the bottom.
7479 // The point of exit cannot be a branch out of the structured block.
7480 // longjmp() and throw() must not violate the entry/exit criteria.
7481 CS->getCapturedDecl()->setNothrow();
7482 }
Reid Kleckner8d485b82018-03-08 01:12:22 +00007483 getCurFunction()->setHasBranchProtectedScope();
Kelvin Libf594a52016-12-17 05:48:59 +00007484
7485 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7486 AStmt);
7487}
7488
Kelvin Li83c451e2016-12-25 04:52:54 +00007489StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7490 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7491 SourceLocation EndLoc,
7492 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7493 if (!AStmt)
7494 return StmtError();
7495
7496 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7497 // 1.2.2 OpenMP Language Terminology
7498 // Structured block - An executable statement with a single entry at the
7499 // top and a single exit at the bottom.
7500 // The point of exit cannot be a branch out of the structured block.
7501 // longjmp() and throw() must not violate the entry/exit criteria.
7502 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007503 for (int ThisCaptureLevel =
7504 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
7505 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7506 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7507 // 1.2.2 OpenMP Language Terminology
7508 // Structured block - An executable statement with a single entry at the
7509 // top and a single exit at the bottom.
7510 // The point of exit cannot be a branch out of the structured block.
7511 // longjmp() and throw() must not violate the entry/exit criteria.
7512 CS->getCapturedDecl()->setNothrow();
7513 }
Kelvin Li83c451e2016-12-25 04:52:54 +00007514
7515 OMPLoopDirective::HelperExprs B;
7516 // In presence of clause 'collapse' with number of loops, it will
7517 // define the nested loops number.
7518 auto NestedLoopCount = CheckOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007519 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
7520 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00007521 VarsWithImplicitDSA, B);
7522 if (NestedLoopCount == 0)
7523 return StmtError();
7524
7525 assert((CurContext->isDependentContext() || B.builtAll()) &&
7526 "omp target teams distribute loop exprs were not built");
7527
Reid Kleckner8d485b82018-03-08 01:12:22 +00007528 getCurFunction()->setHasBranchProtectedScope();
Kelvin Li83c451e2016-12-25 04:52:54 +00007529 return OMPTargetTeamsDistributeDirective::Create(
7530 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7531}
7532
Kelvin Li80e8f562016-12-29 22:16:30 +00007533StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7534 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7535 SourceLocation EndLoc,
7536 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7537 if (!AStmt)
7538 return StmtError();
7539
7540 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7541 // 1.2.2 OpenMP Language Terminology
7542 // Structured block - An executable statement with a single entry at the
7543 // top and a single exit at the bottom.
7544 // The point of exit cannot be a branch out of the structured block.
7545 // longjmp() and throw() must not violate the entry/exit criteria.
7546 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00007547 for (int ThisCaptureLevel =
7548 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
7549 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7550 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7551 // 1.2.2 OpenMP Language Terminology
7552 // Structured block - An executable statement with a single entry at the
7553 // top and a single exit at the bottom.
7554 // The point of exit cannot be a branch out of the structured block.
7555 // longjmp() and throw() must not violate the entry/exit criteria.
7556 CS->getCapturedDecl()->setNothrow();
7557 }
7558
Kelvin Li80e8f562016-12-29 22:16:30 +00007559 OMPLoopDirective::HelperExprs B;
7560 // In presence of clause 'collapse' with number of loops, it will
7561 // define the nested loops number.
7562 auto NestedLoopCount = CheckOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00007563 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7564 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00007565 VarsWithImplicitDSA, B);
7566 if (NestedLoopCount == 0)
7567 return StmtError();
7568
7569 assert((CurContext->isDependentContext() || B.builtAll()) &&
7570 "omp target teams distribute parallel for loop exprs were not built");
7571
Alexey Bataev647dd842018-01-15 20:59:40 +00007572 if (!CurContext->isDependentContext()) {
7573 // Finalize the clauses that need pre-built expressions for CodeGen.
7574 for (auto C : Clauses) {
7575 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7576 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7577 B.NumIterations, *this, CurScope,
7578 DSAStack))
7579 return StmtError();
7580 }
7581 }
7582
Reid Kleckner8d485b82018-03-08 01:12:22 +00007583 getCurFunction()->setHasBranchProtectedScope();
Kelvin Li80e8f562016-12-29 22:16:30 +00007584 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00007585 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7586 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00007587}
7588
Kelvin Li1851df52017-01-03 05:23:48 +00007589StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7590 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7591 SourceLocation EndLoc,
7592 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7593 if (!AStmt)
7594 return StmtError();
7595
7596 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7597 // 1.2.2 OpenMP Language Terminology
7598 // Structured block - An executable statement with a single entry at the
7599 // top and a single exit at the bottom.
7600 // The point of exit cannot be a branch out of the structured block.
7601 // longjmp() and throw() must not violate the entry/exit criteria.
7602 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00007603 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
7604 OMPD_target_teams_distribute_parallel_for_simd);
7605 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7606 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7607 // 1.2.2 OpenMP Language Terminology
7608 // Structured block - An executable statement with a single entry at the
7609 // top and a single exit at the bottom.
7610 // The point of exit cannot be a branch out of the structured block.
7611 // longjmp() and throw() must not violate the entry/exit criteria.
7612 CS->getCapturedDecl()->setNothrow();
7613 }
Kelvin Li1851df52017-01-03 05:23:48 +00007614
7615 OMPLoopDirective::HelperExprs B;
7616 // In presence of clause 'collapse' with number of loops, it will
7617 // define the nested loops number.
Alexey Bataev647dd842018-01-15 20:59:40 +00007618 auto NestedLoopCount =
7619 CheckOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
7620 getCollapseNumberExpr(Clauses),
7621 nullptr /*ordered not a clause on distribute*/, CS, *this,
7622 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00007623 if (NestedLoopCount == 0)
7624 return StmtError();
7625
7626 assert((CurContext->isDependentContext() || B.builtAll()) &&
7627 "omp target teams distribute parallel for simd loop exprs were not "
7628 "built");
7629
7630 if (!CurContext->isDependentContext()) {
7631 // Finalize the clauses that need pre-built expressions for CodeGen.
7632 for (auto C : Clauses) {
7633 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7634 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7635 B.NumIterations, *this, CurScope,
7636 DSAStack))
7637 return StmtError();
7638 }
7639 }
7640
Alexey Bataev438388c2017-11-22 18:34:02 +00007641 if (checkSimdlenSafelenSpecified(*this, Clauses))
7642 return StmtError();
7643
Reid Kleckner8d485b82018-03-08 01:12:22 +00007644 getCurFunction()->setHasBranchProtectedScope();
Kelvin Li1851df52017-01-03 05:23:48 +00007645 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7646 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7647}
7648
Kelvin Lida681182017-01-10 18:08:18 +00007649StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7650 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7651 SourceLocation EndLoc,
7652 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7653 if (!AStmt)
7654 return StmtError();
7655
7656 auto *CS = cast<CapturedStmt>(AStmt);
7657 // 1.2.2 OpenMP Language Terminology
7658 // Structured block - An executable statement with a single entry at the
7659 // top and a single exit at the bottom.
7660 // The point of exit cannot be a branch out of the structured block.
7661 // longjmp() and throw() must not violate the entry/exit criteria.
7662 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007663 for (int ThisCaptureLevel =
7664 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
7665 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7666 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7667 // 1.2.2 OpenMP Language Terminology
7668 // Structured block - An executable statement with a single entry at the
7669 // top and a single exit at the bottom.
7670 // The point of exit cannot be a branch out of the structured block.
7671 // longjmp() and throw() must not violate the entry/exit criteria.
7672 CS->getCapturedDecl()->setNothrow();
7673 }
Kelvin Lida681182017-01-10 18:08:18 +00007674
7675 OMPLoopDirective::HelperExprs B;
7676 // In presence of clause 'collapse' with number of loops, it will
7677 // define the nested loops number.
7678 auto NestedLoopCount = CheckOpenMPLoop(
7679 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007680 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00007681 VarsWithImplicitDSA, B);
7682 if (NestedLoopCount == 0)
7683 return StmtError();
7684
7685 assert((CurContext->isDependentContext() || B.builtAll()) &&
7686 "omp target teams distribute simd loop exprs were not built");
7687
Alexey Bataev438388c2017-11-22 18:34:02 +00007688 if (!CurContext->isDependentContext()) {
7689 // Finalize the clauses that need pre-built expressions for CodeGen.
7690 for (auto C : Clauses) {
7691 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7692 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7693 B.NumIterations, *this, CurScope,
7694 DSAStack))
7695 return StmtError();
7696 }
7697 }
7698
7699 if (checkSimdlenSafelenSpecified(*this, Clauses))
7700 return StmtError();
7701
Reid Kleckner8d485b82018-03-08 01:12:22 +00007702 getCurFunction()->setHasBranchProtectedScope();
Kelvin Lida681182017-01-10 18:08:18 +00007703 return OMPTargetTeamsDistributeSimdDirective::Create(
7704 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7705}
7706
Alexey Bataeved09d242014-05-28 05:53:51 +00007707OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007708 SourceLocation StartLoc,
7709 SourceLocation LParenLoc,
7710 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007711 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007712 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00007713 case OMPC_final:
7714 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7715 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007716 case OMPC_num_threads:
7717 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7718 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007719 case OMPC_safelen:
7720 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7721 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007722 case OMPC_simdlen:
7723 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7724 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007725 case OMPC_collapse:
7726 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7727 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007728 case OMPC_ordered:
7729 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7730 break;
Michael Wonge710d542015-08-07 16:16:36 +00007731 case OMPC_device:
7732 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7733 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007734 case OMPC_num_teams:
7735 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7736 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007737 case OMPC_thread_limit:
7738 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7739 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007740 case OMPC_priority:
7741 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7742 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007743 case OMPC_grainsize:
7744 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7745 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007746 case OMPC_num_tasks:
7747 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7748 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007749 case OMPC_hint:
7750 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7751 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007752 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007753 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007754 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007755 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007756 case OMPC_private:
7757 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007758 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007759 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007760 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007761 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007762 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007763 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007764 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007765 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007766 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007767 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007768 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007769 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007770 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007771 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007772 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007773 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007774 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007775 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007776 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007777 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007778 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007779 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007780 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007781 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007782 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007783 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007784 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007785 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007786 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007787 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007788 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007789 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007790 llvm_unreachable("Clause is not allowed.");
7791 }
7792 return Res;
7793}
7794
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007795// An OpenMP directive such as 'target parallel' has two captured regions:
7796// for the 'target' and 'parallel' respectively. This function returns
7797// the region in which to capture expressions associated with a clause.
7798// A return value of OMPD_unknown signifies that the expression should not
7799// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007800static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7801 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7802 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007803 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007804 switch (CKind) {
7805 case OMPC_if:
7806 switch (DKind) {
7807 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007808 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007809 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007810 // If this clause applies to the nested 'parallel' region, capture within
7811 // the 'target' region, otherwise do not capture.
7812 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7813 CaptureRegion = OMPD_target;
7814 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00007815 case OMPD_target_teams_distribute_parallel_for:
7816 case OMPD_target_teams_distribute_parallel_for_simd:
7817 // If this clause applies to the nested 'parallel' region, capture within
7818 // the 'teams' region, otherwise do not capture.
7819 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7820 CaptureRegion = OMPD_teams;
7821 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007822 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007823 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007824 CaptureRegion = OMPD_teams;
7825 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007826 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00007827 case OMPD_target_enter_data:
7828 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007829 CaptureRegion = OMPD_task;
7830 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007831 case OMPD_cancel:
7832 case OMPD_parallel:
7833 case OMPD_parallel_sections:
7834 case OMPD_parallel_for:
7835 case OMPD_parallel_for_simd:
7836 case OMPD_target:
7837 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007838 case OMPD_target_teams:
7839 case OMPD_target_teams_distribute:
7840 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007841 case OMPD_distribute_parallel_for:
7842 case OMPD_distribute_parallel_for_simd:
7843 case OMPD_task:
7844 case OMPD_taskloop:
7845 case OMPD_taskloop_simd:
7846 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007847 // Do not capture if-clause expressions.
7848 break;
7849 case OMPD_threadprivate:
7850 case OMPD_taskyield:
7851 case OMPD_barrier:
7852 case OMPD_taskwait:
7853 case OMPD_cancellation_point:
7854 case OMPD_flush:
7855 case OMPD_declare_reduction:
7856 case OMPD_declare_simd:
7857 case OMPD_declare_target:
7858 case OMPD_end_declare_target:
7859 case OMPD_teams:
7860 case OMPD_simd:
7861 case OMPD_for:
7862 case OMPD_for_simd:
7863 case OMPD_sections:
7864 case OMPD_section:
7865 case OMPD_single:
7866 case OMPD_master:
7867 case OMPD_critical:
7868 case OMPD_taskgroup:
7869 case OMPD_distribute:
7870 case OMPD_ordered:
7871 case OMPD_atomic:
7872 case OMPD_distribute_simd:
7873 case OMPD_teams_distribute:
7874 case OMPD_teams_distribute_simd:
7875 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7876 case OMPD_unknown:
7877 llvm_unreachable("Unknown OpenMP directive");
7878 }
7879 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007880 case OMPC_num_threads:
7881 switch (DKind) {
7882 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007883 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007884 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007885 CaptureRegion = OMPD_target;
7886 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007887 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007888 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00007889 case OMPD_target_teams_distribute_parallel_for:
7890 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007891 CaptureRegion = OMPD_teams;
7892 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007893 case OMPD_parallel:
7894 case OMPD_parallel_sections:
7895 case OMPD_parallel_for:
7896 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007897 case OMPD_distribute_parallel_for:
7898 case OMPD_distribute_parallel_for_simd:
7899 // Do not capture num_threads-clause expressions.
7900 break;
7901 case OMPD_target_data:
7902 case OMPD_target_enter_data:
7903 case OMPD_target_exit_data:
7904 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007905 case OMPD_target:
7906 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007907 case OMPD_target_teams:
7908 case OMPD_target_teams_distribute:
7909 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007910 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007911 case OMPD_task:
7912 case OMPD_taskloop:
7913 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007914 case OMPD_threadprivate:
7915 case OMPD_taskyield:
7916 case OMPD_barrier:
7917 case OMPD_taskwait:
7918 case OMPD_cancellation_point:
7919 case OMPD_flush:
7920 case OMPD_declare_reduction:
7921 case OMPD_declare_simd:
7922 case OMPD_declare_target:
7923 case OMPD_end_declare_target:
7924 case OMPD_teams:
7925 case OMPD_simd:
7926 case OMPD_for:
7927 case OMPD_for_simd:
7928 case OMPD_sections:
7929 case OMPD_section:
7930 case OMPD_single:
7931 case OMPD_master:
7932 case OMPD_critical:
7933 case OMPD_taskgroup:
7934 case OMPD_distribute:
7935 case OMPD_ordered:
7936 case OMPD_atomic:
7937 case OMPD_distribute_simd:
7938 case OMPD_teams_distribute:
7939 case OMPD_teams_distribute_simd:
7940 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7941 case OMPD_unknown:
7942 llvm_unreachable("Unknown OpenMP directive");
7943 }
7944 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007945 case OMPC_num_teams:
7946 switch (DKind) {
7947 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007948 case OMPD_target_teams_distribute:
7949 case OMPD_target_teams_distribute_simd:
7950 case OMPD_target_teams_distribute_parallel_for:
7951 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007952 CaptureRegion = OMPD_target;
7953 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007954 case OMPD_teams_distribute_parallel_for:
7955 case OMPD_teams_distribute_parallel_for_simd:
7956 case OMPD_teams:
7957 case OMPD_teams_distribute:
7958 case OMPD_teams_distribute_simd:
7959 // Do not capture num_teams-clause expressions.
7960 break;
7961 case OMPD_distribute_parallel_for:
7962 case OMPD_distribute_parallel_for_simd:
7963 case OMPD_task:
7964 case OMPD_taskloop:
7965 case OMPD_taskloop_simd:
7966 case OMPD_target_data:
7967 case OMPD_target_enter_data:
7968 case OMPD_target_exit_data:
7969 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007970 case OMPD_cancel:
7971 case OMPD_parallel:
7972 case OMPD_parallel_sections:
7973 case OMPD_parallel_for:
7974 case OMPD_parallel_for_simd:
7975 case OMPD_target:
7976 case OMPD_target_simd:
7977 case OMPD_target_parallel:
7978 case OMPD_target_parallel_for:
7979 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007980 case OMPD_threadprivate:
7981 case OMPD_taskyield:
7982 case OMPD_barrier:
7983 case OMPD_taskwait:
7984 case OMPD_cancellation_point:
7985 case OMPD_flush:
7986 case OMPD_declare_reduction:
7987 case OMPD_declare_simd:
7988 case OMPD_declare_target:
7989 case OMPD_end_declare_target:
7990 case OMPD_simd:
7991 case OMPD_for:
7992 case OMPD_for_simd:
7993 case OMPD_sections:
7994 case OMPD_section:
7995 case OMPD_single:
7996 case OMPD_master:
7997 case OMPD_critical:
7998 case OMPD_taskgroup:
7999 case OMPD_distribute:
8000 case OMPD_ordered:
8001 case OMPD_atomic:
8002 case OMPD_distribute_simd:
8003 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8004 case OMPD_unknown:
8005 llvm_unreachable("Unknown OpenMP directive");
8006 }
8007 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008008 case OMPC_thread_limit:
8009 switch (DKind) {
8010 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008011 case OMPD_target_teams_distribute:
8012 case OMPD_target_teams_distribute_simd:
8013 case OMPD_target_teams_distribute_parallel_for:
8014 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008015 CaptureRegion = OMPD_target;
8016 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008017 case OMPD_teams_distribute_parallel_for:
8018 case OMPD_teams_distribute_parallel_for_simd:
8019 case OMPD_teams:
8020 case OMPD_teams_distribute:
8021 case OMPD_teams_distribute_simd:
8022 // Do not capture thread_limit-clause expressions.
8023 break;
8024 case OMPD_distribute_parallel_for:
8025 case OMPD_distribute_parallel_for_simd:
8026 case OMPD_task:
8027 case OMPD_taskloop:
8028 case OMPD_taskloop_simd:
8029 case OMPD_target_data:
8030 case OMPD_target_enter_data:
8031 case OMPD_target_exit_data:
8032 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008033 case OMPD_cancel:
8034 case OMPD_parallel:
8035 case OMPD_parallel_sections:
8036 case OMPD_parallel_for:
8037 case OMPD_parallel_for_simd:
8038 case OMPD_target:
8039 case OMPD_target_simd:
8040 case OMPD_target_parallel:
8041 case OMPD_target_parallel_for:
8042 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00008043 case OMPD_threadprivate:
8044 case OMPD_taskyield:
8045 case OMPD_barrier:
8046 case OMPD_taskwait:
8047 case OMPD_cancellation_point:
8048 case OMPD_flush:
8049 case OMPD_declare_reduction:
8050 case OMPD_declare_simd:
8051 case OMPD_declare_target:
8052 case OMPD_end_declare_target:
8053 case OMPD_simd:
8054 case OMPD_for:
8055 case OMPD_for_simd:
8056 case OMPD_sections:
8057 case OMPD_section:
8058 case OMPD_single:
8059 case OMPD_master:
8060 case OMPD_critical:
8061 case OMPD_taskgroup:
8062 case OMPD_distribute:
8063 case OMPD_ordered:
8064 case OMPD_atomic:
8065 case OMPD_distribute_simd:
8066 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8067 case OMPD_unknown:
8068 llvm_unreachable("Unknown OpenMP directive");
8069 }
8070 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008071 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008072 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008073 case OMPD_parallel_for:
8074 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008075 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008076 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008077 case OMPD_teams_distribute_parallel_for:
8078 case OMPD_teams_distribute_parallel_for_simd:
8079 case OMPD_target_parallel_for:
8080 case OMPD_target_parallel_for_simd:
8081 case OMPD_target_teams_distribute_parallel_for:
8082 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008083 CaptureRegion = OMPD_parallel;
8084 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008085 case OMPD_for:
8086 case OMPD_for_simd:
8087 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008088 break;
8089 case OMPD_task:
8090 case OMPD_taskloop:
8091 case OMPD_taskloop_simd:
8092 case OMPD_target_data:
8093 case OMPD_target_enter_data:
8094 case OMPD_target_exit_data:
8095 case OMPD_target_update:
8096 case OMPD_teams:
8097 case OMPD_teams_distribute:
8098 case OMPD_teams_distribute_simd:
8099 case OMPD_target_teams_distribute:
8100 case OMPD_target_teams_distribute_simd:
8101 case OMPD_target:
8102 case OMPD_target_simd:
8103 case OMPD_target_parallel:
8104 case OMPD_cancel:
8105 case OMPD_parallel:
8106 case OMPD_parallel_sections:
8107 case OMPD_threadprivate:
8108 case OMPD_taskyield:
8109 case OMPD_barrier:
8110 case OMPD_taskwait:
8111 case OMPD_cancellation_point:
8112 case OMPD_flush:
8113 case OMPD_declare_reduction:
8114 case OMPD_declare_simd:
8115 case OMPD_declare_target:
8116 case OMPD_end_declare_target:
8117 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008118 case OMPD_sections:
8119 case OMPD_section:
8120 case OMPD_single:
8121 case OMPD_master:
8122 case OMPD_critical:
8123 case OMPD_taskgroup:
8124 case OMPD_distribute:
8125 case OMPD_ordered:
8126 case OMPD_atomic:
8127 case OMPD_distribute_simd:
8128 case OMPD_target_teams:
8129 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8130 case OMPD_unknown:
8131 llvm_unreachable("Unknown OpenMP directive");
8132 }
8133 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008134 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008135 switch (DKind) {
8136 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008137 case OMPD_teams_distribute_parallel_for_simd:
8138 case OMPD_teams_distribute:
8139 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008140 case OMPD_target_teams_distribute_parallel_for:
8141 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008142 case OMPD_target_teams_distribute:
8143 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008144 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008145 break;
8146 case OMPD_distribute_parallel_for:
8147 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008148 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008149 case OMPD_distribute_simd:
8150 // Do not capture thread_limit-clause expressions.
8151 break;
8152 case OMPD_parallel_for:
8153 case OMPD_parallel_for_simd:
8154 case OMPD_target_parallel_for_simd:
8155 case OMPD_target_parallel_for:
8156 case OMPD_task:
8157 case OMPD_taskloop:
8158 case OMPD_taskloop_simd:
8159 case OMPD_target_data:
8160 case OMPD_target_enter_data:
8161 case OMPD_target_exit_data:
8162 case OMPD_target_update:
8163 case OMPD_teams:
8164 case OMPD_target:
8165 case OMPD_target_simd:
8166 case OMPD_target_parallel:
8167 case OMPD_cancel:
8168 case OMPD_parallel:
8169 case OMPD_parallel_sections:
8170 case OMPD_threadprivate:
8171 case OMPD_taskyield:
8172 case OMPD_barrier:
8173 case OMPD_taskwait:
8174 case OMPD_cancellation_point:
8175 case OMPD_flush:
8176 case OMPD_declare_reduction:
8177 case OMPD_declare_simd:
8178 case OMPD_declare_target:
8179 case OMPD_end_declare_target:
8180 case OMPD_simd:
8181 case OMPD_for:
8182 case OMPD_for_simd:
8183 case OMPD_sections:
8184 case OMPD_section:
8185 case OMPD_single:
8186 case OMPD_master:
8187 case OMPD_critical:
8188 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008189 case OMPD_ordered:
8190 case OMPD_atomic:
8191 case OMPD_target_teams:
8192 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8193 case OMPD_unknown:
8194 llvm_unreachable("Unknown OpenMP directive");
8195 }
8196 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008197 case OMPC_device:
8198 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008199 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008200 case OMPD_target_enter_data:
8201 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00008202 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00008203 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00008204 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00008205 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00008206 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00008207 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00008208 case OMPD_target_parallel_for:
Alexey Bataevd60d1ba2018-01-16 17:55:15 +00008209 case OMPD_target_parallel_for_simd:
Alexey Bataev9f9fb0b2018-01-16 19:02:33 +00008210 case OMPD_target_teams_distribute_parallel_for:
Alexey Bataev9350fc32018-01-16 19:18:24 +00008211 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008212 CaptureRegion = OMPD_task;
8213 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008214 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008215 // Do not capture device-clause expressions.
8216 break;
8217 case OMPD_teams_distribute_parallel_for:
8218 case OMPD_teams_distribute_parallel_for_simd:
8219 case OMPD_teams:
8220 case OMPD_teams_distribute:
8221 case OMPD_teams_distribute_simd:
8222 case OMPD_distribute_parallel_for:
8223 case OMPD_distribute_parallel_for_simd:
8224 case OMPD_task:
8225 case OMPD_taskloop:
8226 case OMPD_taskloop_simd:
8227 case OMPD_cancel:
8228 case OMPD_parallel:
8229 case OMPD_parallel_sections:
8230 case OMPD_parallel_for:
8231 case OMPD_parallel_for_simd:
8232 case OMPD_threadprivate:
8233 case OMPD_taskyield:
8234 case OMPD_barrier:
8235 case OMPD_taskwait:
8236 case OMPD_cancellation_point:
8237 case OMPD_flush:
8238 case OMPD_declare_reduction:
8239 case OMPD_declare_simd:
8240 case OMPD_declare_target:
8241 case OMPD_end_declare_target:
8242 case OMPD_simd:
8243 case OMPD_for:
8244 case OMPD_for_simd:
8245 case OMPD_sections:
8246 case OMPD_section:
8247 case OMPD_single:
8248 case OMPD_master:
8249 case OMPD_critical:
8250 case OMPD_taskgroup:
8251 case OMPD_distribute:
8252 case OMPD_ordered:
8253 case OMPD_atomic:
8254 case OMPD_distribute_simd:
8255 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8256 case OMPD_unknown:
8257 llvm_unreachable("Unknown OpenMP directive");
8258 }
8259 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008260 case OMPC_firstprivate:
8261 case OMPC_lastprivate:
8262 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008263 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008264 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008265 case OMPC_linear:
8266 case OMPC_default:
8267 case OMPC_proc_bind:
8268 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008269 case OMPC_safelen:
8270 case OMPC_simdlen:
8271 case OMPC_collapse:
8272 case OMPC_private:
8273 case OMPC_shared:
8274 case OMPC_aligned:
8275 case OMPC_copyin:
8276 case OMPC_copyprivate:
8277 case OMPC_ordered:
8278 case OMPC_nowait:
8279 case OMPC_untied:
8280 case OMPC_mergeable:
8281 case OMPC_threadprivate:
8282 case OMPC_flush:
8283 case OMPC_read:
8284 case OMPC_write:
8285 case OMPC_update:
8286 case OMPC_capture:
8287 case OMPC_seq_cst:
8288 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008289 case OMPC_threads:
8290 case OMPC_simd:
8291 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008292 case OMPC_priority:
8293 case OMPC_grainsize:
8294 case OMPC_nogroup:
8295 case OMPC_num_tasks:
8296 case OMPC_hint:
8297 case OMPC_defaultmap:
8298 case OMPC_unknown:
8299 case OMPC_uniform:
8300 case OMPC_to:
8301 case OMPC_from:
8302 case OMPC_use_device_ptr:
8303 case OMPC_is_device_ptr:
8304 llvm_unreachable("Unexpected OpenMP clause.");
8305 }
8306 return CaptureRegion;
8307}
8308
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008309OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8310 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008311 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008312 SourceLocation NameModifierLoc,
8313 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008314 SourceLocation EndLoc) {
8315 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008316 Stmt *HelperValStmt = nullptr;
8317 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008318 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8319 !Condition->isInstantiationDependent() &&
8320 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008321 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008322 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008323 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008324
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008325 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008326
8327 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8328 CaptureRegion =
8329 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00008330 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008331 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008332 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8333 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8334 HelperValStmt = buildPreInits(Context, Captures);
8335 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008336 }
8337
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008338 return new (Context)
8339 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8340 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008341}
8342
Alexey Bataev3778b602014-07-17 07:32:53 +00008343OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8344 SourceLocation StartLoc,
8345 SourceLocation LParenLoc,
8346 SourceLocation EndLoc) {
8347 Expr *ValExpr = Condition;
8348 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8349 !Condition->isInstantiationDependent() &&
8350 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008351 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00008352 if (Val.isInvalid())
8353 return nullptr;
8354
Richard Smith03a4aa32016-06-23 19:02:52 +00008355 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00008356 }
8357
8358 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8359}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008360ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8361 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00008362 if (!Op)
8363 return ExprError();
8364
8365 class IntConvertDiagnoser : public ICEConvertDiagnoser {
8366 public:
8367 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00008368 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00008369 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8370 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008371 return S.Diag(Loc, diag::err_omp_not_integral) << T;
8372 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008373 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8374 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008375 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8376 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008377 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8378 QualType T,
8379 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008380 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8381 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008382 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8383 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008384 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008385 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008386 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008387 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8388 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008389 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8390 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008391 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8392 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008393 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008394 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008395 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008396 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8397 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008398 llvm_unreachable("conversion functions are permitted");
8399 }
8400 } ConvertDiagnoser;
8401 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8402}
8403
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008404static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00008405 OpenMPClauseKind CKind,
8406 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008407 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8408 !ValExpr->isInstantiationDependent()) {
8409 SourceLocation Loc = ValExpr->getExprLoc();
8410 ExprResult Value =
8411 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8412 if (Value.isInvalid())
8413 return false;
8414
8415 ValExpr = Value.get();
8416 // The expression must evaluate to a non-negative integer value.
8417 llvm::APSInt Result;
8418 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00008419 Result.isSigned() &&
8420 !((!StrictlyPositive && Result.isNonNegative()) ||
8421 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008422 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008423 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8424 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008425 return false;
8426 }
8427 }
8428 return true;
8429}
8430
Alexey Bataev568a8332014-03-06 06:15:19 +00008431OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8432 SourceLocation StartLoc,
8433 SourceLocation LParenLoc,
8434 SourceLocation EndLoc) {
8435 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008436 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008437
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008438 // OpenMP [2.5, Restrictions]
8439 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00008440 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8441 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008442 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008443
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008444 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00008445 OpenMPDirectiveKind CaptureRegion =
8446 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8447 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008448 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008449 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8450 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8451 HelperValStmt = buildPreInits(Context, Captures);
8452 }
8453
8454 return new (Context) OMPNumThreadsClause(
8455 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00008456}
8457
Alexey Bataev62c87d22014-03-21 04:51:18 +00008458ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008459 OpenMPClauseKind CKind,
8460 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008461 if (!E)
8462 return ExprError();
8463 if (E->isValueDependent() || E->isTypeDependent() ||
8464 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008465 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008466 llvm::APSInt Result;
8467 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8468 if (ICE.isInvalid())
8469 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008470 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8471 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008472 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008473 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8474 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00008475 return ExprError();
8476 }
Alexander Musman09184fe2014-09-30 05:29:28 +00008477 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8478 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8479 << E->getSourceRange();
8480 return ExprError();
8481 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008482 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8483 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00008484 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008485 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00008486 return ICE;
8487}
8488
8489OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8490 SourceLocation LParenLoc,
8491 SourceLocation EndLoc) {
8492 // OpenMP [2.8.1, simd construct, Description]
8493 // The parameter of the safelen clause must be a constant
8494 // positive integer expression.
8495 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8496 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008497 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008498 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008499 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00008500}
8501
Alexey Bataev66b15b52015-08-21 11:14:16 +00008502OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8503 SourceLocation LParenLoc,
8504 SourceLocation EndLoc) {
8505 // OpenMP [2.8.1, simd construct, Description]
8506 // The parameter of the simdlen clause must be a constant
8507 // positive integer expression.
8508 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8509 if (Simdlen.isInvalid())
8510 return nullptr;
8511 return new (Context)
8512 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8513}
8514
Alexander Musman64d33f12014-06-04 07:53:32 +00008515OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8516 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00008517 SourceLocation LParenLoc,
8518 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00008519 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008520 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00008521 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008522 // The parameter of the collapse clause must be a constant
8523 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00008524 ExprResult NumForLoopsResult =
8525 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8526 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00008527 return nullptr;
8528 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00008529 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00008530}
8531
Alexey Bataev10e775f2015-07-30 11:36:16 +00008532OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8533 SourceLocation EndLoc,
8534 SourceLocation LParenLoc,
8535 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00008536 // OpenMP [2.7.1, loop construct, Description]
8537 // OpenMP [2.8.1, simd construct, Description]
8538 // OpenMP [2.9.6, distribute construct, Description]
8539 // The parameter of the ordered clause must be a constant
8540 // positive integer expression if any.
8541 if (NumForLoops && LParenLoc.isValid()) {
8542 ExprResult NumForLoopsResult =
8543 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8544 if (NumForLoopsResult.isInvalid())
8545 return nullptr;
8546 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00008547 } else
8548 NumForLoops = nullptr;
8549 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00008550 return new (Context)
8551 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
8552}
8553
Alexey Bataeved09d242014-05-28 05:53:51 +00008554OMPClause *Sema::ActOnOpenMPSimpleClause(
8555 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8556 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008557 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008558 switch (Kind) {
8559 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008560 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00008561 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8562 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008563 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008564 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00008565 Res = ActOnOpenMPProcBindClause(
8566 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8567 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008568 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008569 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008570 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008571 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008572 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008573 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008574 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008575 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008576 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008577 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008578 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008579 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008580 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008581 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008582 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008583 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008584 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008585 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008586 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008587 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008588 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008589 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008590 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008591 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008592 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008593 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008594 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008595 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008596 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008597 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008598 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008599 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008600 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008601 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008602 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008603 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008604 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008605 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008606 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008607 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008608 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008609 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008610 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008611 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008612 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008613 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008614 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008615 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008616 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008617 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008618 llvm_unreachable("Clause is not allowed.");
8619 }
8620 return Res;
8621}
8622
Alexey Bataev6402bca2015-12-28 07:25:51 +00008623static std::string
8624getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8625 ArrayRef<unsigned> Exclude = llvm::None) {
8626 std::string Values;
8627 unsigned Bound = Last >= 2 ? Last - 2 : 0;
8628 unsigned Skipped = Exclude.size();
8629 auto S = Exclude.begin(), E = Exclude.end();
8630 for (unsigned i = First; i < Last; ++i) {
8631 if (std::find(S, E, i) != E) {
8632 --Skipped;
8633 continue;
8634 }
8635 Values += "'";
8636 Values += getOpenMPSimpleClauseTypeName(K, i);
8637 Values += "'";
8638 if (i == Bound - Skipped)
8639 Values += " or ";
8640 else if (i != Bound + 1 - Skipped)
8641 Values += ", ";
8642 }
8643 return Values;
8644}
8645
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008646OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8647 SourceLocation KindKwLoc,
8648 SourceLocation StartLoc,
8649 SourceLocation LParenLoc,
8650 SourceLocation EndLoc) {
8651 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00008652 static_assert(OMPC_DEFAULT_unknown > 0,
8653 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008654 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008655 << getListOfPossibleValues(OMPC_default, /*First=*/0,
8656 /*Last=*/OMPC_DEFAULT_unknown)
8657 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008658 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008659 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00008660 switch (Kind) {
8661 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008662 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008663 break;
8664 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008665 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008666 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008667 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008668 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00008669 break;
8670 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008671 return new (Context)
8672 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008673}
8674
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008675OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8676 SourceLocation KindKwLoc,
8677 SourceLocation StartLoc,
8678 SourceLocation LParenLoc,
8679 SourceLocation EndLoc) {
8680 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008681 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008682 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8683 /*Last=*/OMPC_PROC_BIND_unknown)
8684 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008685 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008686 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008687 return new (Context)
8688 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008689}
8690
Alexey Bataev56dafe82014-06-20 07:16:17 +00008691OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008692 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008693 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008694 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008695 SourceLocation EndLoc) {
8696 OMPClause *Res = nullptr;
8697 switch (Kind) {
8698 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008699 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8700 assert(Argument.size() == NumberOfElements &&
8701 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008702 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008703 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8704 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8705 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8706 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8707 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008708 break;
8709 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008710 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8711 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8712 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8713 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008714 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00008715 case OMPC_dist_schedule:
8716 Res = ActOnOpenMPDistScheduleClause(
8717 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8718 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8719 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008720 case OMPC_defaultmap:
8721 enum { Modifier, DefaultmapKind };
8722 Res = ActOnOpenMPDefaultmapClause(
8723 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8724 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00008725 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8726 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008727 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00008728 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008729 case OMPC_num_threads:
8730 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008731 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008732 case OMPC_collapse:
8733 case OMPC_default:
8734 case OMPC_proc_bind:
8735 case OMPC_private:
8736 case OMPC_firstprivate:
8737 case OMPC_lastprivate:
8738 case OMPC_shared:
8739 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008740 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008741 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008742 case OMPC_linear:
8743 case OMPC_aligned:
8744 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008745 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008746 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008747 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008748 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008749 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008750 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008751 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008752 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008753 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008754 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008755 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008756 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008757 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008758 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008759 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008760 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008761 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008762 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008763 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008764 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008765 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008766 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008767 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008768 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008769 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008770 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008771 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008772 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008773 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008774 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008775 llvm_unreachable("Clause is not allowed.");
8776 }
8777 return Res;
8778}
8779
Alexey Bataev6402bca2015-12-28 07:25:51 +00008780static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8781 OpenMPScheduleClauseModifier M2,
8782 SourceLocation M1Loc, SourceLocation M2Loc) {
8783 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8784 SmallVector<unsigned, 2> Excluded;
8785 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8786 Excluded.push_back(M2);
8787 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8788 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8789 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8790 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8791 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8792 << getListOfPossibleValues(OMPC_schedule,
8793 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8794 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8795 Excluded)
8796 << getOpenMPClauseName(OMPC_schedule);
8797 return true;
8798 }
8799 return false;
8800}
8801
Alexey Bataev56dafe82014-06-20 07:16:17 +00008802OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008803 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008804 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008805 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8806 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8807 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8808 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8809 return nullptr;
8810 // OpenMP, 2.7.1, Loop Construct, Restrictions
8811 // Either the monotonic modifier or the nonmonotonic modifier can be specified
8812 // but not both.
8813 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8814 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8815 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8816 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8817 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8818 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8819 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8820 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8821 return nullptr;
8822 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008823 if (Kind == OMPC_SCHEDULE_unknown) {
8824 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00008825 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8826 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8827 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8828 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8829 Exclude);
8830 } else {
8831 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8832 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008833 }
8834 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8835 << Values << getOpenMPClauseName(OMPC_schedule);
8836 return nullptr;
8837 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00008838 // OpenMP, 2.7.1, Loop Construct, Restrictions
8839 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8840 // schedule(guided).
8841 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8842 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8843 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8844 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8845 diag::err_omp_schedule_nonmonotonic_static);
8846 return nullptr;
8847 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008848 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00008849 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00008850 if (ChunkSize) {
8851 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8852 !ChunkSize->isInstantiationDependent() &&
8853 !ChunkSize->containsUnexpandedParameterPack()) {
8854 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8855 ExprResult Val =
8856 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8857 if (Val.isInvalid())
8858 return nullptr;
8859
8860 ValExpr = Val.get();
8861
8862 // OpenMP [2.7.1, Restrictions]
8863 // chunk_size must be a loop invariant integer expression with a positive
8864 // value.
8865 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00008866 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8867 if (Result.isSigned() && !Result.isStrictlyPositive()) {
8868 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008869 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00008870 return nullptr;
8871 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00008872 } else if (getOpenMPCaptureRegionForClause(
8873 DSAStack->getCurrentDirective(), OMPC_schedule) !=
8874 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00008875 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008876 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008877 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8878 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8879 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008880 }
8881 }
8882 }
8883
Alexey Bataev6402bca2015-12-28 07:25:51 +00008884 return new (Context)
8885 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00008886 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008887}
8888
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008889OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8890 SourceLocation StartLoc,
8891 SourceLocation EndLoc) {
8892 OMPClause *Res = nullptr;
8893 switch (Kind) {
8894 case OMPC_ordered:
8895 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8896 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00008897 case OMPC_nowait:
8898 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8899 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008900 case OMPC_untied:
8901 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8902 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008903 case OMPC_mergeable:
8904 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8905 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008906 case OMPC_read:
8907 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8908 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00008909 case OMPC_write:
8910 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8911 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008912 case OMPC_update:
8913 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8914 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00008915 case OMPC_capture:
8916 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8917 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008918 case OMPC_seq_cst:
8919 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8920 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008921 case OMPC_threads:
8922 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8923 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008924 case OMPC_simd:
8925 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8926 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008927 case OMPC_nogroup:
8928 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8929 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008930 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008931 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008932 case OMPC_num_threads:
8933 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008934 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008935 case OMPC_collapse:
8936 case OMPC_schedule:
8937 case OMPC_private:
8938 case OMPC_firstprivate:
8939 case OMPC_lastprivate:
8940 case OMPC_shared:
8941 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008942 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008943 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008944 case OMPC_linear:
8945 case OMPC_aligned:
8946 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008947 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008948 case OMPC_default:
8949 case OMPC_proc_bind:
8950 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008951 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008952 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008953 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008954 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008955 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008956 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008957 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008958 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00008959 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008960 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008961 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008962 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008963 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008964 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008965 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008966 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008967 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008968 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008969 llvm_unreachable("Clause is not allowed.");
8970 }
8971 return Res;
8972}
8973
Alexey Bataev236070f2014-06-20 11:19:47 +00008974OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8975 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008976 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00008977 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8978}
8979
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008980OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8981 SourceLocation EndLoc) {
8982 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8983}
8984
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008985OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8986 SourceLocation EndLoc) {
8987 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8988}
8989
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008990OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8991 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008992 return new (Context) OMPReadClause(StartLoc, EndLoc);
8993}
8994
Alexey Bataevdea47612014-07-23 07:46:59 +00008995OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
8996 SourceLocation EndLoc) {
8997 return new (Context) OMPWriteClause(StartLoc, EndLoc);
8998}
8999
Alexey Bataev67a4f222014-07-23 10:25:33 +00009000OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
9001 SourceLocation EndLoc) {
9002 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
9003}
9004
Alexey Bataev459dec02014-07-24 06:46:57 +00009005OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
9006 SourceLocation EndLoc) {
9007 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
9008}
9009
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009010OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
9011 SourceLocation EndLoc) {
9012 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
9013}
9014
Alexey Bataev346265e2015-09-25 10:37:12 +00009015OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
9016 SourceLocation EndLoc) {
9017 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
9018}
9019
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009020OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
9021 SourceLocation EndLoc) {
9022 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
9023}
9024
Alexey Bataevb825de12015-12-07 10:51:44 +00009025OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
9026 SourceLocation EndLoc) {
9027 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
9028}
9029
Alexey Bataevc5e02582014-06-16 07:08:35 +00009030OMPClause *Sema::ActOnOpenMPVarListClause(
9031 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
9032 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
9033 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009034 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00009035 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
9036 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
9037 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00009038 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009039 switch (Kind) {
9040 case OMPC_private:
9041 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9042 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009043 case OMPC_firstprivate:
9044 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9045 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009046 case OMPC_lastprivate:
9047 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9048 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009049 case OMPC_shared:
9050 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
9051 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009052 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00009053 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9054 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009055 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00009056 case OMPC_task_reduction:
9057 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9058 EndLoc, ReductionIdScopeSpec,
9059 ReductionId);
9060 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00009061 case OMPC_in_reduction:
9062 Res =
9063 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9064 EndLoc, ReductionIdScopeSpec, ReductionId);
9065 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00009066 case OMPC_linear:
9067 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009068 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00009069 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009070 case OMPC_aligned:
9071 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9072 ColonLoc, EndLoc);
9073 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009074 case OMPC_copyin:
9075 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9076 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009077 case OMPC_copyprivate:
9078 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9079 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00009080 case OMPC_flush:
9081 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9082 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009083 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00009084 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009085 StartLoc, LParenLoc, EndLoc);
9086 break;
9087 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00009088 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
9089 DepLinMapLoc, ColonLoc, VarList, StartLoc,
9090 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009091 break;
Samuel Antao661c0902016-05-26 17:39:58 +00009092 case OMPC_to:
9093 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
9094 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00009095 case OMPC_from:
9096 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
9097 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00009098 case OMPC_use_device_ptr:
9099 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9100 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00009101 case OMPC_is_device_ptr:
9102 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9103 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009104 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009105 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009106 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009107 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009108 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009109 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009110 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009111 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009112 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009113 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009114 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009115 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009116 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009117 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009118 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009119 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009120 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009121 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009122 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00009123 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009124 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009125 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009126 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009127 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009128 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009129 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009130 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009131 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009132 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009133 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009134 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009135 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009136 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009137 llvm_unreachable("Clause is not allowed.");
9138 }
9139 return Res;
9140}
9141
Alexey Bataev90c228f2016-02-08 09:29:13 +00009142ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00009143 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00009144 ExprResult Res = BuildDeclRefExpr(
9145 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9146 if (!Res.isUsable())
9147 return ExprError();
9148 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9149 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9150 if (!Res.isUsable())
9151 return ExprError();
9152 }
9153 if (VK != VK_LValue && Res.get()->isGLValue()) {
9154 Res = DefaultLvalueConversion(Res.get());
9155 if (!Res.isUsable())
9156 return ExprError();
9157 }
9158 return Res;
9159}
9160
Alexey Bataev60da77e2016-02-29 05:54:20 +00009161static std::pair<ValueDecl *, bool>
9162getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9163 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009164 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9165 RefExpr->containsUnexpandedParameterPack())
9166 return std::make_pair(nullptr, true);
9167
Alexey Bataevd985eda2016-02-10 11:29:16 +00009168 // OpenMP [3.1, C/C++]
9169 // A list item is a variable name.
9170 // OpenMP [2.9.3.3, Restrictions, p.1]
9171 // A variable that is part of another variable (as an array or
9172 // structure element) cannot appear in a private clause.
9173 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009174 enum {
9175 NoArrayExpr = -1,
9176 ArraySubscript = 0,
9177 OMPArraySection = 1
9178 } IsArrayExpr = NoArrayExpr;
9179 if (AllowArraySection) {
9180 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
9181 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
9182 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9183 Base = TempASE->getBase()->IgnoreParenImpCasts();
9184 RefExpr = Base;
9185 IsArrayExpr = ArraySubscript;
9186 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
9187 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
9188 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9189 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9190 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9191 Base = TempASE->getBase()->IgnoreParenImpCasts();
9192 RefExpr = Base;
9193 IsArrayExpr = OMPArraySection;
9194 }
9195 }
9196 ELoc = RefExpr->getExprLoc();
9197 ERange = RefExpr->getSourceRange();
9198 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009199 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9200 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9201 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9202 (S.getCurrentThisType().isNull() || !ME ||
9203 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9204 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009205 if (IsArrayExpr != NoArrayExpr)
9206 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9207 << ERange;
9208 else {
9209 S.Diag(ELoc,
9210 AllowArraySection
9211 ? diag::err_omp_expected_var_name_member_expr_or_array_item
9212 : diag::err_omp_expected_var_name_member_expr)
9213 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9214 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009215 return std::make_pair(nullptr, false);
9216 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009217 return std::make_pair(
9218 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009219}
9220
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009221OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9222 SourceLocation StartLoc,
9223 SourceLocation LParenLoc,
9224 SourceLocation EndLoc) {
9225 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00009226 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00009227 for (auto &RefExpr : VarList) {
9228 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009229 SourceLocation ELoc;
9230 SourceRange ERange;
9231 Expr *SimpleRefExpr = RefExpr;
9232 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009233 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009234 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009235 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009236 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009237 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009238 ValueDecl *D = Res.first;
9239 if (!D)
9240 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009241
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009242 QualType Type = D->getType();
9243 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009244
9245 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9246 // A variable that appears in a private clause must not have an incomplete
9247 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009248 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009249 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009250 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009251
Alexey Bataev758e55e2013-09-06 18:03:48 +00009252 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9253 // in a Construct]
9254 // Variables with the predetermined data-sharing attributes may not be
9255 // listed in data-sharing attributes clauses, except for the cases
9256 // listed below. For these exceptions only, listing a predetermined
9257 // variable in a data-sharing attribute clause is allowed and overrides
9258 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009259 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009260 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009261 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9262 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009263 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009264 continue;
9265 }
9266
Kelvin Libf594a52016-12-17 05:48:59 +00009267 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009268 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009269 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00009270 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009271 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9272 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00009273 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009274 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009275 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009276 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009277 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009278 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009279 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009280 continue;
9281 }
9282
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009283 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9284 // A list item cannot appear in both a map clause and a data-sharing
9285 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00009286 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Alexey Bataev647dd842018-01-15 20:59:40 +00009287 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00009288 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00009289 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00009290 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00009291 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00009292 CurrDir == OMPD_target_parallel_for_simd ||
9293 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00009294 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009295 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009296 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009297 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9298 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9299 ConflictKind = WhereFoundClauseKind;
9300 return true;
9301 })) {
9302 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009303 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00009304 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00009305 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009306 ReportOriginalDSA(*this, DSAStack, D, DVar);
9307 continue;
9308 }
9309 }
9310
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009311 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9312 // A variable of class type (or array thereof) that appears in a private
9313 // clause requires an accessible, unambiguous default constructor for the
9314 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00009315 // Generate helper private variable and initialize it with the default
9316 // value. The address of the original variable is replaced by the address of
9317 // the new private variable in CodeGen. This new variable is not added to
9318 // IdResolver, so the code in the OpenMP region uses original variable for
9319 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009320 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009321 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9322 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00009323 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009324 if (VDPrivate->isInvalidDecl())
9325 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009326 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009327 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009328
Alexey Bataev90c228f2016-02-08 09:29:13 +00009329 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009330 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009331 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00009332 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009333 Vars.push_back((VD || CurContext->isDependentContext())
9334 ? RefExpr->IgnoreParens()
9335 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009336 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009337 }
9338
Alexey Bataeved09d242014-05-28 05:53:51 +00009339 if (Vars.empty())
9340 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009341
Alexey Bataev03b340a2014-10-21 03:16:40 +00009342 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9343 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009344}
9345
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009346namespace {
9347class DiagsUninitializedSeveretyRAII {
9348private:
9349 DiagnosticsEngine &Diags;
9350 SourceLocation SavedLoc;
9351 bool IsIgnored;
9352
9353public:
9354 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9355 bool IsIgnored)
9356 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9357 if (!IsIgnored) {
9358 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9359 /*Map*/ diag::Severity::Ignored, Loc);
9360 }
9361 }
9362 ~DiagsUninitializedSeveretyRAII() {
9363 if (!IsIgnored)
9364 Diags.popMappings(SavedLoc);
9365 }
9366};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009367}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009368
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009369OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9370 SourceLocation StartLoc,
9371 SourceLocation LParenLoc,
9372 SourceLocation EndLoc) {
9373 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009374 SmallVector<Expr *, 8> PrivateCopies;
9375 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00009376 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009377 bool IsImplicitClause =
9378 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
9379 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
9380
Alexey Bataeved09d242014-05-28 05:53:51 +00009381 for (auto &RefExpr : VarList) {
9382 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009383 SourceLocation ELoc;
9384 SourceRange ERange;
9385 Expr *SimpleRefExpr = RefExpr;
9386 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009387 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009388 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009389 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009390 PrivateCopies.push_back(nullptr);
9391 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009392 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009393 ValueDecl *D = Res.first;
9394 if (!D)
9395 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009396
Alexey Bataev60da77e2016-02-29 05:54:20 +00009397 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009398 QualType Type = D->getType();
9399 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009400
9401 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9402 // A variable that appears in a private clause must not have an incomplete
9403 // type or a reference type.
9404 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00009405 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009406 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009407 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009408
9409 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9410 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00009411 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009412 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009413 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009414
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009415 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00009416 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009417 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009418 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009419 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009420 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009421 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009422 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9423 // A list item that specifies a given variable may not appear in more
9424 // than one clause on the same directive, except that a variable may be
9425 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009426 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9427 // A list item may appear in a firstprivate or lastprivate clause but not
9428 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009429 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +00009430 (isOpenMPDistributeDirective(CurrDir) ||
9431 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009432 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009433 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009434 << getOpenMPClauseName(DVar.CKind)
9435 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009436 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009437 continue;
9438 }
9439
9440 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9441 // in a Construct]
9442 // Variables with the predetermined data-sharing attributes may not be
9443 // listed in data-sharing attributes clauses, except for the cases
9444 // listed below. For these exceptions only, listing a predetermined
9445 // variable in a data-sharing attribute clause is allowed and overrides
9446 // the variable's predetermined data-sharing attributes.
9447 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9448 // in a Construct, C/C++, p.2]
9449 // Variables with const-qualified type having no mutable member may be
9450 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00009451 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009452 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9453 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009454 << getOpenMPClauseName(DVar.CKind)
9455 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009456 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009457 continue;
9458 }
9459
9460 // OpenMP [2.9.3.4, Restrictions, p.2]
9461 // A list item that is private within a parallel region must not appear
9462 // in a firstprivate clause on a worksharing construct if any of the
9463 // worksharing regions arising from the worksharing construct ever bind
9464 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009465 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9466 // A list item that is private within a teams region must not appear in a
9467 // firstprivate clause on a distribute construct if any of the distribute
9468 // regions arising from the distribute construct ever bind to any of the
9469 // teams regions arising from the teams construct.
9470 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9471 // A list item that appears in a reduction clause of a teams construct
9472 // must not appear in a firstprivate clause on a distribute construct if
9473 // any of the distribute regions arising from the distribute construct
9474 // ever bind to any of the teams regions arising from the teams construct.
9475 if ((isOpenMPWorksharingDirective(CurrDir) ||
9476 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009477 !isOpenMPParallelDirective(CurrDir) &&
9478 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009479 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009480 if (DVar.CKind != OMPC_shared &&
9481 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009482 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009483 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00009484 Diag(ELoc, diag::err_omp_required_access)
9485 << getOpenMPClauseName(OMPC_firstprivate)
9486 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009487 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009488 continue;
9489 }
9490 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009491 // OpenMP [2.9.3.4, Restrictions, p.3]
9492 // A list item that appears in a reduction clause of a parallel construct
9493 // must not appear in a firstprivate clause on a worksharing or task
9494 // construct if any of the worksharing or task regions arising from the
9495 // worksharing or task construct ever bind to any of the parallel regions
9496 // arising from the parallel construct.
9497 // OpenMP [2.9.3.4, Restrictions, p.4]
9498 // A list item that appears in a reduction clause in worksharing
9499 // construct must not appear in a firstprivate clause in a task construct
9500 // encountered during execution of any of the worksharing regions arising
9501 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00009502 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009503 DVar = DSAStack->hasInnermostDSA(
9504 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
9505 [](OpenMPDirectiveKind K) -> bool {
9506 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009507 isOpenMPWorksharingDirective(K) ||
9508 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009509 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009510 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009511 if (DVar.CKind == OMPC_reduction &&
9512 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009513 isOpenMPWorksharingDirective(DVar.DKind) ||
9514 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009515 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
9516 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009517 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009518 continue;
9519 }
9520 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009521
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009522 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9523 // A list item cannot appear in both a map clause and a data-sharing
9524 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +00009525 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +00009526 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009527 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009528 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009529 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9530 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9531 ConflictKind = WhereFoundClauseKind;
9532 return true;
9533 })) {
9534 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009535 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00009536 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009537 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9538 ReportOriginalDSA(*this, DSAStack, D, DVar);
9539 continue;
9540 }
9541 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009542 }
9543
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009544 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009545 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00009546 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009547 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9548 << getOpenMPClauseName(OMPC_firstprivate) << Type
9549 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9550 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009551 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009552 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009553 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009554 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00009555 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009556 continue;
9557 }
9558
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009559 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009560 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9561 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009562 // Generate helper private variable and initialize it with the value of the
9563 // original variable. The address of the original variable is replaced by
9564 // the address of the new private variable in the CodeGen. This new variable
9565 // is not added to IdResolver, so the code in the OpenMP region uses
9566 // original variable for proper diagnostics and variable capturing.
9567 Expr *VDInitRefExpr = nullptr;
9568 // For arrays generate initializer for single element and replace it by the
9569 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009570 if (Type->isArrayType()) {
9571 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009572 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009573 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009574 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009575 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009576 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009577 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00009578 InitializedEntity Entity =
9579 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009580 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9581
9582 InitializationSequence InitSeq(*this, Entity, Kind, Init);
9583 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9584 if (Result.isInvalid())
9585 VDPrivate->setInvalidDecl();
9586 else
9587 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009588 // Remove temp variable declaration.
9589 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009590 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009591 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9592 ".firstprivate.temp");
9593 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9594 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00009595 AddInitializerToDecl(VDPrivate,
9596 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009597 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009598 }
9599 if (VDPrivate->isInvalidDecl()) {
9600 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009601 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009602 diag::note_omp_task_predetermined_firstprivate_here);
9603 }
9604 continue;
9605 }
9606 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009607 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00009608 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
9609 RefExpr->getExprLoc());
9610 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009611 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009612 if (TopDVar.CKind == OMPC_lastprivate)
9613 Ref = TopDVar.PrivateCopy;
9614 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009615 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00009616 if (!IsOpenMPCapturedDecl(D))
9617 ExprCaptures.push_back(Ref->getDecl());
9618 }
Alexey Bataev417089f2016-02-17 13:19:37 +00009619 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009620 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009621 Vars.push_back((VD || CurContext->isDependentContext())
9622 ? RefExpr->IgnoreParens()
9623 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009624 PrivateCopies.push_back(VDPrivateRefExpr);
9625 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009626 }
9627
Alexey Bataeved09d242014-05-28 05:53:51 +00009628 if (Vars.empty())
9629 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009630
9631 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009632 Vars, PrivateCopies, Inits,
9633 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009634}
9635
Alexander Musman1bb328c2014-06-04 13:06:39 +00009636OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9637 SourceLocation StartLoc,
9638 SourceLocation LParenLoc,
9639 SourceLocation EndLoc) {
9640 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00009641 SmallVector<Expr *, 8> SrcExprs;
9642 SmallVector<Expr *, 8> DstExprs;
9643 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00009644 SmallVector<Decl *, 4> ExprCaptures;
9645 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009646 for (auto &RefExpr : VarList) {
9647 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009648 SourceLocation ELoc;
9649 SourceRange ERange;
9650 Expr *SimpleRefExpr = RefExpr;
9651 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009652 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00009653 // It will be analyzed later.
9654 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00009655 SrcExprs.push_back(nullptr);
9656 DstExprs.push_back(nullptr);
9657 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009658 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009659 ValueDecl *D = Res.first;
9660 if (!D)
9661 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009662
Alexey Bataev74caaf22016-02-20 04:09:36 +00009663 QualType Type = D->getType();
9664 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009665
9666 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9667 // A variable that appears in a lastprivate clause must not have an
9668 // incomplete type or a reference type.
9669 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00009670 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00009671 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009672 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009673
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009674 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009675 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9676 // in a Construct]
9677 // Variables with the predetermined data-sharing attributes may not be
9678 // listed in data-sharing attributes clauses, except for the cases
9679 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009680 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9681 // A list item may appear in a firstprivate or lastprivate clause but not
9682 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009683 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009684 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +00009685 (isOpenMPDistributeDirective(CurrDir) ||
9686 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00009687 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9688 Diag(ELoc, diag::err_omp_wrong_dsa)
9689 << getOpenMPClauseName(DVar.CKind)
9690 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009691 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009692 continue;
9693 }
9694
Alexey Bataevf29276e2014-06-18 04:14:57 +00009695 // OpenMP [2.14.3.5, Restrictions, p.2]
9696 // A list item that is private within a parallel region, or that appears in
9697 // the reduction clause of a parallel construct, must not appear in a
9698 // lastprivate clause on a worksharing construct if any of the corresponding
9699 // worksharing regions ever binds to any of the corresponding parallel
9700 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00009701 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00009702 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009703 !isOpenMPParallelDirective(CurrDir) &&
9704 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00009705 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009706 if (DVar.CKind != OMPC_shared) {
9707 Diag(ELoc, diag::err_omp_required_access)
9708 << getOpenMPClauseName(OMPC_lastprivate)
9709 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009710 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009711 continue;
9712 }
9713 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009714
Alexander Musman1bb328c2014-06-04 13:06:39 +00009715 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00009716 // A variable of class type (or array thereof) that appears in a
9717 // lastprivate clause requires an accessible, unambiguous default
9718 // constructor for the class type, unless the list item is also specified
9719 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00009720 // A variable of class type (or array thereof) that appears in a
9721 // lastprivate clause requires an accessible, unambiguous copy assignment
9722 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00009723 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009724 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009725 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009726 D->hasAttrs() ? &D->getAttrs() : nullptr);
9727 auto *PseudoSrcExpr =
9728 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009729 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009730 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009731 D->hasAttrs() ? &D->getAttrs() : nullptr);
9732 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009733 // For arrays generate assignment operation for single element and replace
9734 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009735 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00009736 PseudoDstExpr, PseudoSrcExpr);
9737 if (AssignmentOp.isInvalid())
9738 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00009739 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00009740 /*DiscardedValue=*/true);
9741 if (AssignmentOp.isInvalid())
9742 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009743
Alexey Bataev74caaf22016-02-20 04:09:36 +00009744 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009745 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009746 if (TopDVar.CKind == OMPC_firstprivate)
9747 Ref = TopDVar.PrivateCopy;
9748 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009749 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009750 if (!IsOpenMPCapturedDecl(D))
9751 ExprCaptures.push_back(Ref->getDecl());
9752 }
9753 if (TopDVar.CKind == OMPC_firstprivate ||
9754 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009755 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009756 ExprResult RefRes = DefaultLvalueConversion(Ref);
9757 if (!RefRes.isUsable())
9758 continue;
9759 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009760 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9761 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009762 if (!PostUpdateRes.isUsable())
9763 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009764 ExprPostUpdates.push_back(
9765 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009766 }
9767 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009768 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009769 Vars.push_back((VD || CurContext->isDependentContext())
9770 ? RefExpr->IgnoreParens()
9771 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00009772 SrcExprs.push_back(PseudoSrcExpr);
9773 DstExprs.push_back(PseudoDstExpr);
9774 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00009775 }
9776
9777 if (Vars.empty())
9778 return nullptr;
9779
9780 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00009781 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009782 buildPreInits(Context, ExprCaptures),
9783 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00009784}
9785
Alexey Bataev758e55e2013-09-06 18:03:48 +00009786OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9787 SourceLocation StartLoc,
9788 SourceLocation LParenLoc,
9789 SourceLocation EndLoc) {
9790 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00009791 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009792 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009793 SourceLocation ELoc;
9794 SourceRange ERange;
9795 Expr *SimpleRefExpr = RefExpr;
9796 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009797 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00009798 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009799 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009800 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009801 ValueDecl *D = Res.first;
9802 if (!D)
9803 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009804
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009805 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009806 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9807 // in a Construct]
9808 // Variables with the predetermined data-sharing attributes may not be
9809 // listed in data-sharing attributes clauses, except for the cases
9810 // listed below. For these exceptions only, listing a predetermined
9811 // variable in a data-sharing attribute clause is allowed and overrides
9812 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009813 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00009814 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9815 DVar.RefExpr) {
9816 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9817 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009818 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009819 continue;
9820 }
9821
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009822 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009823 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009824 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009825 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009826 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9827 ? RefExpr->IgnoreParens()
9828 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009829 }
9830
Alexey Bataeved09d242014-05-28 05:53:51 +00009831 if (Vars.empty())
9832 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009833
9834 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9835}
9836
Alexey Bataevc5e02582014-06-16 07:08:35 +00009837namespace {
9838class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9839 DSAStackTy *Stack;
9840
9841public:
9842 bool VisitDeclRefExpr(DeclRefExpr *E) {
9843 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009844 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009845 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9846 return false;
9847 if (DVar.CKind != OMPC_unknown)
9848 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009849 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9850 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009851 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009852 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009853 return true;
9854 return false;
9855 }
9856 return false;
9857 }
9858 bool VisitStmt(Stmt *S) {
9859 for (auto Child : S->children()) {
9860 if (Child && Visit(Child))
9861 return true;
9862 }
9863 return false;
9864 }
Alexey Bataev23b69422014-06-18 07:08:49 +00009865 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009866};
Alexey Bataev23b69422014-06-18 07:08:49 +00009867} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00009868
Alexey Bataev60da77e2016-02-29 05:54:20 +00009869namespace {
9870// Transform MemberExpression for specified FieldDecl of current class to
9871// DeclRefExpr to specified OMPCapturedExprDecl.
9872class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9873 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9874 ValueDecl *Field;
9875 DeclRefExpr *CapturedExpr;
9876
9877public:
9878 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9879 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9880
9881 ExprResult TransformMemberExpr(MemberExpr *E) {
9882 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9883 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00009884 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009885 return CapturedExpr;
9886 }
9887 return BaseTransform::TransformMemberExpr(E);
9888 }
9889 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9890};
9891} // namespace
9892
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009893template <typename T>
9894static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9895 const llvm::function_ref<T(ValueDecl *)> &Gen) {
9896 for (auto &Set : Lookups) {
9897 for (auto *D : Set) {
9898 if (auto Res = Gen(cast<ValueDecl>(D)))
9899 return Res;
9900 }
9901 }
9902 return T();
9903}
9904
9905static ExprResult
9906buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9907 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9908 const DeclarationNameInfo &ReductionId, QualType Ty,
9909 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9910 if (ReductionIdScopeSpec.isInvalid())
9911 return ExprError();
9912 SmallVector<UnresolvedSet<8>, 4> Lookups;
9913 if (S) {
9914 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9915 Lookup.suppressDiagnostics();
9916 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9917 auto *D = Lookup.getRepresentativeDecl();
9918 do {
9919 S = S->getParent();
9920 } while (S && !S->isDeclScope(D));
9921 if (S)
9922 S = S->getParent();
9923 Lookups.push_back(UnresolvedSet<8>());
9924 Lookups.back().append(Lookup.begin(), Lookup.end());
9925 Lookup.clear();
9926 }
9927 } else if (auto *ULE =
9928 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9929 Lookups.push_back(UnresolvedSet<8>());
9930 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00009931 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009932 if (D == PrevD)
9933 Lookups.push_back(UnresolvedSet<8>());
9934 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9935 Lookups.back().addDecl(DRD);
9936 PrevD = D;
9937 }
9938 }
Alexey Bataevfdc20352017-08-25 15:43:55 +00009939 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9940 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009941 Ty->containsUnexpandedParameterPack() ||
9942 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9943 return !D->isInvalidDecl() &&
9944 (D->getType()->isDependentType() ||
9945 D->getType()->isInstantiationDependentType() ||
9946 D->getType()->containsUnexpandedParameterPack());
9947 })) {
9948 UnresolvedSet<8> ResSet;
9949 for (auto &Set : Lookups) {
9950 ResSet.append(Set.begin(), Set.end());
9951 // The last item marks the end of all declarations at the specified scope.
9952 ResSet.addDecl(Set[Set.size() - 1]);
9953 }
9954 return UnresolvedLookupExpr::Create(
9955 SemaRef.Context, /*NamingClass=*/nullptr,
9956 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9957 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9958 }
9959 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9960 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9961 if (!D->isInvalidDecl() &&
9962 SemaRef.Context.hasSameType(D->getType(), Ty))
9963 return D;
9964 return nullptr;
9965 }))
9966 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9967 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9968 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9969 if (!D->isInvalidDecl() &&
9970 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9971 !Ty.isMoreQualifiedThan(D->getType()))
9972 return D;
9973 return nullptr;
9974 })) {
9975 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9976 /*DetectVirtual=*/false);
9977 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9978 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9979 VD->getType().getUnqualifiedType()))) {
9980 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9981 /*DiagID=*/0) !=
9982 Sema::AR_inaccessible) {
9983 SemaRef.BuildBasePathArray(Paths, BasePath);
9984 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9985 }
9986 }
9987 }
9988 }
9989 if (ReductionIdScopeSpec.isSet()) {
9990 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9991 return ExprError();
9992 }
9993 return ExprEmpty();
9994}
9995
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009996namespace {
9997/// Data for the reduction-based clauses.
9998struct ReductionData {
9999 /// List of original reduction items.
10000 SmallVector<Expr *, 8> Vars;
10001 /// List of private copies of the reduction items.
10002 SmallVector<Expr *, 8> Privates;
10003 /// LHS expressions for the reduction_op expressions.
10004 SmallVector<Expr *, 8> LHSs;
10005 /// RHS expressions for the reduction_op expressions.
10006 SmallVector<Expr *, 8> RHSs;
10007 /// Reduction operation expression.
10008 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +000010009 /// Taskgroup descriptors for the corresponding reduction items in
10010 /// in_reduction clauses.
10011 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010012 /// List of captures for clause.
10013 SmallVector<Decl *, 4> ExprCaptures;
10014 /// List of postupdate expressions.
10015 SmallVector<Expr *, 4> ExprPostUpdates;
10016 ReductionData() = delete;
10017 /// Reserves required memory for the reduction data.
10018 ReductionData(unsigned Size) {
10019 Vars.reserve(Size);
10020 Privates.reserve(Size);
10021 LHSs.reserve(Size);
10022 RHSs.reserve(Size);
10023 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +000010024 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010025 ExprCaptures.reserve(Size);
10026 ExprPostUpdates.reserve(Size);
10027 }
10028 /// Stores reduction item and reduction operation only (required for dependent
10029 /// reduction item).
10030 void push(Expr *Item, Expr *ReductionOp) {
10031 Vars.emplace_back(Item);
10032 Privates.emplace_back(nullptr);
10033 LHSs.emplace_back(nullptr);
10034 RHSs.emplace_back(nullptr);
10035 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010036 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010037 }
10038 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +000010039 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
10040 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010041 Vars.emplace_back(Item);
10042 Privates.emplace_back(Private);
10043 LHSs.emplace_back(LHS);
10044 RHSs.emplace_back(RHS);
10045 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +000010046 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010047 }
10048};
10049} // namespace
10050
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010051static bool CheckOMPArraySectionConstantForReduction(
10052 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
10053 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
10054 const Expr *Length = OASE->getLength();
10055 if (Length == nullptr) {
10056 // For array sections of the form [1:] or [:], we would need to analyze
10057 // the lower bound...
10058 if (OASE->getColonLoc().isValid())
10059 return false;
10060
10061 // This is an array subscript which has implicit length 1!
10062 SingleElement = true;
10063 ArraySizes.push_back(llvm::APSInt::get(1));
10064 } else {
10065 llvm::APSInt ConstantLengthValue;
10066 if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
10067 return false;
10068
10069 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
10070 ArraySizes.push_back(ConstantLengthValue);
10071 }
10072
10073 // Get the base of this array section and walk up from there.
10074 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10075
10076 // We require length = 1 for all array sections except the right-most to
10077 // guarantee that the memory region is contiguous and has no holes in it.
10078 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10079 Length = TempOASE->getLength();
10080 if (Length == nullptr) {
10081 // For array sections of the form [1:] or [:], we would need to analyze
10082 // the lower bound...
10083 if (OASE->getColonLoc().isValid())
10084 return false;
10085
10086 // This is an array subscript which has implicit length 1!
10087 ArraySizes.push_back(llvm::APSInt::get(1));
10088 } else {
10089 llvm::APSInt ConstantLengthValue;
10090 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
10091 ConstantLengthValue.getSExtValue() != 1)
10092 return false;
10093
10094 ArraySizes.push_back(ConstantLengthValue);
10095 }
10096 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10097 }
10098
10099 // If we have a single element, we don't need to add the implicit lengths.
10100 if (!SingleElement) {
10101 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10102 // Has implicit length 1!
10103 ArraySizes.push_back(llvm::APSInt::get(1));
10104 Base = TempASE->getBase()->IgnoreParenImpCasts();
10105 }
10106 }
10107
10108 // This array section can be privatized as a single value or as a constant
10109 // sized array.
10110 return true;
10111}
10112
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010113static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000010114 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10115 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10116 SourceLocation ColonLoc, SourceLocation EndLoc,
10117 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010118 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010119 auto DN = ReductionId.getName();
10120 auto OOK = DN.getCXXOverloadedOperator();
10121 BinaryOperatorKind BOK = BO_Comma;
10122
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010123 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010124 // OpenMP [2.14.3.6, reduction clause]
10125 // C
10126 // reduction-identifier is either an identifier or one of the following
10127 // operators: +, -, *, &, |, ^, && and ||
10128 // C++
10129 // reduction-identifier is either an id-expression or one of the following
10130 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000010131 switch (OOK) {
10132 case OO_Plus:
10133 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010134 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010135 break;
10136 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010137 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010138 break;
10139 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010140 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010141 break;
10142 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010143 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010144 break;
10145 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010146 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010147 break;
10148 case OO_AmpAmp:
10149 BOK = BO_LAnd;
10150 break;
10151 case OO_PipePipe:
10152 BOK = BO_LOr;
10153 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010154 case OO_New:
10155 case OO_Delete:
10156 case OO_Array_New:
10157 case OO_Array_Delete:
10158 case OO_Slash:
10159 case OO_Percent:
10160 case OO_Tilde:
10161 case OO_Exclaim:
10162 case OO_Equal:
10163 case OO_Less:
10164 case OO_Greater:
10165 case OO_LessEqual:
10166 case OO_GreaterEqual:
10167 case OO_PlusEqual:
10168 case OO_MinusEqual:
10169 case OO_StarEqual:
10170 case OO_SlashEqual:
10171 case OO_PercentEqual:
10172 case OO_CaretEqual:
10173 case OO_AmpEqual:
10174 case OO_PipeEqual:
10175 case OO_LessLess:
10176 case OO_GreaterGreater:
10177 case OO_LessLessEqual:
10178 case OO_GreaterGreaterEqual:
10179 case OO_EqualEqual:
10180 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000010181 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010182 case OO_PlusPlus:
10183 case OO_MinusMinus:
10184 case OO_Comma:
10185 case OO_ArrowStar:
10186 case OO_Arrow:
10187 case OO_Call:
10188 case OO_Subscript:
10189 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000010190 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010191 case NUM_OVERLOADED_OPERATORS:
10192 llvm_unreachable("Unexpected reduction identifier");
10193 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010194 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010195 if (II->isStr("max"))
10196 BOK = BO_GT;
10197 else if (II->isStr("min"))
10198 BOK = BO_LT;
10199 }
10200 break;
10201 }
10202 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010203 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000010204 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010205 else
10206 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000010207 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000010208
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010209 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
10210 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010211 for (auto RefExpr : VarList) {
10212 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000010213 // OpenMP [2.1, C/C++]
10214 // A list item is a variable or array section, subject to the restrictions
10215 // specified in Section 2.4 on page 42 and in each of the sections
10216 // describing clauses and directives for which a list appears.
10217 // OpenMP [2.14.3.3, Restrictions, p.1]
10218 // A variable that is part of another variable (as an array or
10219 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010220 if (!FirstIter && IR != ER)
10221 ++IR;
10222 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010223 SourceLocation ELoc;
10224 SourceRange ERange;
10225 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010226 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000010227 /*AllowArraySection=*/true);
10228 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010229 // Try to find 'declare reduction' corresponding construct before using
10230 // builtin/overloaded operators.
10231 QualType Type = Context.DependentTy;
10232 CXXCastPath BasePath;
10233 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010234 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010235 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010236 Expr *ReductionOp = nullptr;
10237 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010238 (DeclareReductionRef.isUnset() ||
10239 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010240 ReductionOp = DeclareReductionRef.get();
10241 // It will be analyzed later.
10242 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010243 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010244 ValueDecl *D = Res.first;
10245 if (!D)
10246 continue;
10247
Alexey Bataev88202be2017-07-27 13:20:36 +000010248 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000010249 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010250 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
10251 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
10252 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +000010253 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010254 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +000010255 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
10256 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
10257 Type = ATy->getElementType();
10258 else
10259 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000010260 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010261 } else
10262 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
10263 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000010264
Alexey Bataevc5e02582014-06-16 07:08:35 +000010265 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10266 // A variable that appears in a private clause must not have an incomplete
10267 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010268 if (S.RequireCompleteType(ELoc, Type,
10269 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010270 continue;
10271 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000010272 // A list item that appears in a reduction clause must not be
10273 // const-qualified.
10274 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010275 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010276 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010277 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10278 VarDecl::DeclarationOnly;
10279 S.Diag(D->getLocation(),
10280 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010281 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +000010282 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010283 continue;
10284 }
10285 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
10286 // If a list-item is a reference type then it must bind to the same object
10287 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +000010288 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +000010289 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +000010290 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010291 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +000010292 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010293 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
10294 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010295 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +000010296 continue;
10297 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010298 }
10299 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010300
Alexey Bataevc5e02582014-06-16 07:08:35 +000010301 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10302 // in a Construct]
10303 // Variables with the predetermined data-sharing attributes may not be
10304 // listed in data-sharing attributes clauses, except for the cases
10305 // listed below. For these exceptions only, listing a predetermined
10306 // variable in a data-sharing attribute clause is allowed and overrides
10307 // the variable's predetermined data-sharing attributes.
10308 // OpenMP [2.14.3.6, Restrictions, p.3]
10309 // Any number of reduction clauses can be specified on the directive,
10310 // but a list item can appear only once in the reduction clauses for that
10311 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +000010312 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010313 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010314 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010315 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010316 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010317 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010318 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010319 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010320 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010321 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010322 << getOpenMPClauseName(DVar.CKind)
10323 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010324 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010325 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010326 }
10327
10328 // OpenMP [2.14.3.6, Restrictions, p.1]
10329 // A list item that appears in a reduction clause of a worksharing
10330 // construct must be shared in the parallel regions to which any of the
10331 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010332 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010333 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010334 !isOpenMPParallelDirective(CurrDir) &&
10335 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010336 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010337 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010338 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010339 << getOpenMPClauseName(OMPC_reduction)
10340 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010341 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010342 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000010343 }
10344 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010345
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010346 // Try to find 'declare reduction' corresponding construct before using
10347 // builtin/overloaded operators.
10348 CXXCastPath BasePath;
10349 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010350 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010351 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10352 if (DeclareReductionRef.isInvalid())
10353 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010354 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010355 (DeclareReductionRef.isUnset() ||
10356 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010357 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010358 continue;
10359 }
10360 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
10361 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010362 S.Diag(ReductionId.getLocStart(),
10363 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010364 << Type << ReductionIdRange;
10365 continue;
10366 }
10367
10368 // OpenMP [2.14.3.6, reduction clause, Restrictions]
10369 // The type of a list item that appears in a reduction clause must be valid
10370 // for the reduction-identifier. For a max or min reduction in C, the type
10371 // of the list item must be an allowed arithmetic data type: char, int,
10372 // float, double, or _Bool, possibly modified with long, short, signed, or
10373 // unsigned. For a max or min reduction in C++, the type of the list item
10374 // must be an allowed arithmetic data type: char, wchar_t, int, float,
10375 // double, or bool, possibly modified with long, short, signed, or unsigned.
10376 if (DeclareReductionRef.isUnset()) {
10377 if ((BOK == BO_GT || BOK == BO_LT) &&
10378 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010379 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
10380 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010381 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010382 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010383 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10384 VarDecl::DeclarationOnly;
10385 S.Diag(D->getLocation(),
10386 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010387 << D;
10388 }
10389 continue;
10390 }
10391 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010392 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010393 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
10394 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010395 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010396 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10397 VarDecl::DeclarationOnly;
10398 S.Diag(D->getLocation(),
10399 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010400 << D;
10401 }
10402 continue;
10403 }
10404 }
10405
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010406 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010407 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +000010408 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010409 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010410 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010411 auto PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010412
10413 // Try if we can determine constant lengths for all array sections and avoid
10414 // the VLA.
10415 bool ConstantLengthOASE = false;
10416 if (OASE) {
10417 bool SingleElement;
10418 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
10419 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
10420 Context, OASE, SingleElement, ArraySizes);
10421
10422 // If we don't have a single element, we must emit a constant array type.
10423 if (ConstantLengthOASE && !SingleElement) {
10424 for (auto &Size : ArraySizes) {
10425 PrivateTy = Context.getConstantArrayType(
10426 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
10427 }
10428 }
10429 }
10430
10431 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000010432 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000010433 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000010434 if (!Context.getTargetInfo().isVLASupported() &&
10435 S.shouldDiagnoseTargetSupportFromOpenMP()) {
10436 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
10437 S.Diag(ELoc, diag::note_vla_unsupported);
10438 continue;
10439 }
David Majnemer9d168222016-08-05 17:44:54 +000010440 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010441 // Create pseudo array type for private copy. The size for this array will
10442 // be generated during codegen.
10443 // For array subscripts or single variables Private Ty is the same as Type
10444 // (type of the variable or single array element).
10445 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010446 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000010447 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010448 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000010449 } else if (!ASE && !OASE &&
10450 Context.getAsArrayType(D->getType().getNonReferenceType()))
10451 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010452 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010453 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010454 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010455 // Add initializer for private variable.
10456 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010457 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
10458 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010459 if (DeclareReductionRef.isUsable()) {
10460 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
10461 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
10462 if (DRD->getInitializer()) {
10463 Init = DRDRef;
10464 RHSVD->setInit(DRDRef);
10465 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010466 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010467 } else {
10468 switch (BOK) {
10469 case BO_Add:
10470 case BO_Xor:
10471 case BO_Or:
10472 case BO_LOr:
10473 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
10474 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010475 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010476 break;
10477 case BO_Mul:
10478 case BO_LAnd:
10479 if (Type->isScalarType() || Type->isAnyComplexType()) {
10480 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010481 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000010482 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010483 break;
10484 case BO_And: {
10485 // '&' reduction op - initializer is '~0'.
10486 QualType OrigType = Type;
10487 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
10488 Type = ComplexTy->getElementType();
10489 if (Type->isRealFloatingType()) {
10490 llvm::APFloat InitValue =
10491 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
10492 /*isIEEE=*/true);
10493 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10494 Type, ELoc);
10495 } else if (Type->isScalarType()) {
10496 auto Size = Context.getTypeSize(Type);
10497 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
10498 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
10499 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10500 }
10501 if (Init && OrigType->isAnyComplexType()) {
10502 // Init = 0xFFFF + 0xFFFFi;
10503 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010504 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010505 }
10506 Type = OrigType;
10507 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010508 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010509 case BO_LT:
10510 case BO_GT: {
10511 // 'min' reduction op - initializer is 'Largest representable number in
10512 // the reduction list item type'.
10513 // 'max' reduction op - initializer is 'Least representable number in
10514 // the reduction list item type'.
10515 if (Type->isIntegerType() || Type->isPointerType()) {
10516 bool IsSigned = Type->hasSignedIntegerRepresentation();
10517 auto Size = Context.getTypeSize(Type);
10518 QualType IntTy =
10519 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
10520 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010521 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
10522 : llvm::APInt::getMinValue(Size)
10523 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
10524 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010525 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10526 if (Type->isPointerType()) {
10527 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010528 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000010529 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010530 if (CastExpr.isInvalid())
10531 continue;
10532 Init = CastExpr.get();
10533 }
10534 } else if (Type->isRealFloatingType()) {
10535 llvm::APFloat InitValue = llvm::APFloat::getLargest(
10536 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
10537 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10538 Type, ELoc);
10539 }
10540 break;
10541 }
10542 case BO_PtrMemD:
10543 case BO_PtrMemI:
10544 case BO_MulAssign:
10545 case BO_Div:
10546 case BO_Rem:
10547 case BO_Sub:
10548 case BO_Shl:
10549 case BO_Shr:
10550 case BO_LE:
10551 case BO_GE:
10552 case BO_EQ:
10553 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000010554 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010555 case BO_AndAssign:
10556 case BO_XorAssign:
10557 case BO_OrAssign:
10558 case BO_Assign:
10559 case BO_AddAssign:
10560 case BO_SubAssign:
10561 case BO_DivAssign:
10562 case BO_RemAssign:
10563 case BO_ShlAssign:
10564 case BO_ShrAssign:
10565 case BO_Comma:
10566 llvm_unreachable("Unexpected reduction operation");
10567 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010568 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010569 if (Init && DeclareReductionRef.isUnset())
10570 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
10571 else if (!Init)
10572 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010573 if (RHSVD->isInvalidDecl())
10574 continue;
10575 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010576 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
10577 << Type << ReductionIdRange;
10578 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10579 VarDecl::DeclarationOnly;
10580 S.Diag(D->getLocation(),
10581 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010582 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010583 continue;
10584 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010585 // Store initializer for single element in private copy. Will be used during
10586 // codegen.
10587 PrivateVD->setInit(RHSVD->getInit());
10588 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010589 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010590 ExprResult ReductionOp;
10591 if (DeclareReductionRef.isUsable()) {
10592 QualType RedTy = DeclareReductionRef.get()->getType();
10593 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010594 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
10595 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010596 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010597 LHS = S.DefaultLvalueConversion(LHS.get());
10598 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010599 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10600 CK_UncheckedDerivedToBase, LHS.get(),
10601 &BasePath, LHS.get()->getValueKind());
10602 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10603 CK_UncheckedDerivedToBase, RHS.get(),
10604 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010605 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010606 FunctionProtoType::ExtProtoInfo EPI;
10607 QualType Params[] = {PtrRedTy, PtrRedTy};
10608 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
10609 auto *OVE = new (Context) OpaqueValueExpr(
10610 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010611 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010612 Expr *Args[] = {LHS.get(), RHS.get()};
10613 ReductionOp = new (Context)
10614 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
10615 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010616 ReductionOp = S.BuildBinOp(
10617 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010618 if (ReductionOp.isUsable()) {
10619 if (BOK != BO_LT && BOK != BO_GT) {
10620 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010621 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10622 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010623 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000010624 auto *ConditionalOp = new (Context)
10625 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
10626 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010627 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010628 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10629 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010630 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010631 if (ReductionOp.isUsable())
10632 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010633 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010634 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010635 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010636 }
10637
Alexey Bataevfa312f32017-07-21 18:48:21 +000010638 // OpenMP [2.15.4.6, Restrictions, p.2]
10639 // A list item that appears in an in_reduction clause of a task construct
10640 // must appear in a task_reduction clause of a construct associated with a
10641 // taskgroup region that includes the participating task in its taskgroup
10642 // set. The construct associated with the innermost region that meets this
10643 // condition must specify the same reduction-identifier as the in_reduction
10644 // clause.
10645 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000010646 SourceRange ParentSR;
10647 BinaryOperatorKind ParentBOK;
10648 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000010649 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000010650 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010651 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10652 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010653 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010654 Stack->getTopMostTaskgroupReductionData(
10655 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010656 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10657 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10658 if (!IsParentBOK && !IsParentReductionOp) {
10659 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10660 continue;
10661 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000010662 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10663 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10664 IsParentReductionOp) {
10665 bool EmitError = true;
10666 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10667 llvm::FoldingSetNodeID RedId, ParentRedId;
10668 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10669 DeclareReductionRef.get()->Profile(RedId, Context,
10670 /*Canonical=*/true);
10671 EmitError = RedId != ParentRedId;
10672 }
10673 if (EmitError) {
10674 S.Diag(ReductionId.getLocStart(),
10675 diag::err_omp_reduction_identifier_mismatch)
10676 << ReductionIdRange << RefExpr->getSourceRange();
10677 S.Diag(ParentSR.getBegin(),
10678 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000010679 << ParentSR
10680 << (IsParentBOK ? ParentBOKDSA.RefExpr
10681 : ParentReductionOpDSA.RefExpr)
10682 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000010683 continue;
10684 }
10685 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010686 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10687 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000010688 }
10689
Alexey Bataev60da77e2016-02-29 05:54:20 +000010690 DeclRefExpr *Ref = nullptr;
10691 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010692 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010693 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010694 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010695 VarsExpr =
10696 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10697 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000010698 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010699 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010700 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010701 if (!S.IsOpenMPCapturedDecl(D)) {
10702 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010703 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010704 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010705 if (!RefRes.isUsable())
10706 continue;
10707 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010708 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10709 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010710 if (!PostUpdateRes.isUsable())
10711 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010712 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10713 Stack->getCurrentDirective() == OMPD_taskgroup) {
10714 S.Diag(RefExpr->getExprLoc(),
10715 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000010716 << RefExpr->getSourceRange();
10717 continue;
10718 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010719 RD.ExprPostUpdates.emplace_back(
10720 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000010721 }
10722 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010723 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000010724 // All reduction items are still marked as reduction (to do not increase
10725 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010726 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010727 if (CurrDir == OMPD_taskgroup) {
10728 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010729 Stack->addTaskgroupReductionData(D, ReductionIdRange,
10730 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000010731 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010732 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010733 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010734 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10735 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010736 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010737 return RD.Vars.empty();
10738}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010739
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010740OMPClause *Sema::ActOnOpenMPReductionClause(
10741 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10742 SourceLocation ColonLoc, SourceLocation EndLoc,
10743 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10744 ArrayRef<Expr *> UnresolvedReductions) {
10745 ReductionData RD(VarList.size());
10746
Alexey Bataev169d96a2017-07-18 20:17:46 +000010747 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10748 StartLoc, LParenLoc, ColonLoc, EndLoc,
10749 ReductionIdScopeSpec, ReductionId,
10750 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010751 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000010752
Alexey Bataevc5e02582014-06-16 07:08:35 +000010753 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010754 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10755 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10756 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10757 buildPreInits(Context, RD.ExprCaptures),
10758 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000010759}
10760
Alexey Bataev169d96a2017-07-18 20:17:46 +000010761OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10762 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10763 SourceLocation ColonLoc, SourceLocation EndLoc,
10764 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10765 ArrayRef<Expr *> UnresolvedReductions) {
10766 ReductionData RD(VarList.size());
10767
10768 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
10769 VarList, StartLoc, LParenLoc, ColonLoc,
10770 EndLoc, ReductionIdScopeSpec, ReductionId,
10771 UnresolvedReductions, RD))
10772 return nullptr;
10773
10774 return OMPTaskReductionClause::Create(
10775 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10776 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10777 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10778 buildPreInits(Context, RD.ExprCaptures),
10779 buildPostUpdate(*this, RD.ExprPostUpdates));
10780}
10781
Alexey Bataevfa312f32017-07-21 18:48:21 +000010782OMPClause *Sema::ActOnOpenMPInReductionClause(
10783 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10784 SourceLocation ColonLoc, SourceLocation EndLoc,
10785 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10786 ArrayRef<Expr *> UnresolvedReductions) {
10787 ReductionData RD(VarList.size());
10788
10789 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10790 StartLoc, LParenLoc, ColonLoc, EndLoc,
10791 ReductionIdScopeSpec, ReductionId,
10792 UnresolvedReductions, RD))
10793 return nullptr;
10794
10795 return OMPInReductionClause::Create(
10796 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10797 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000010798 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000010799 buildPreInits(Context, RD.ExprCaptures),
10800 buildPostUpdate(*this, RD.ExprPostUpdates));
10801}
10802
Alexey Bataevecba70f2016-04-12 11:02:11 +000010803bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10804 SourceLocation LinLoc) {
10805 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10806 LinKind == OMPC_LINEAR_unknown) {
10807 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10808 return true;
10809 }
10810 return false;
10811}
10812
10813bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10814 OpenMPLinearClauseKind LinKind,
10815 QualType Type) {
10816 auto *VD = dyn_cast_or_null<VarDecl>(D);
10817 // A variable must not have an incomplete type or a reference type.
10818 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10819 return true;
10820 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10821 !Type->isReferenceType()) {
10822 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10823 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10824 return true;
10825 }
10826 Type = Type.getNonReferenceType();
10827
10828 // A list item must not be const-qualified.
10829 if (Type.isConstant(Context)) {
10830 Diag(ELoc, diag::err_omp_const_variable)
10831 << getOpenMPClauseName(OMPC_linear);
10832 if (D) {
10833 bool IsDecl =
10834 !VD ||
10835 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10836 Diag(D->getLocation(),
10837 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10838 << D;
10839 }
10840 return true;
10841 }
10842
10843 // A list item must be of integral or pointer type.
10844 Type = Type.getUnqualifiedType().getCanonicalType();
10845 const auto *Ty = Type.getTypePtrOrNull();
10846 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10847 !Ty->isPointerType())) {
10848 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10849 if (D) {
10850 bool IsDecl =
10851 !VD ||
10852 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10853 Diag(D->getLocation(),
10854 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10855 << D;
10856 }
10857 return true;
10858 }
10859 return false;
10860}
10861
Alexey Bataev182227b2015-08-20 10:54:39 +000010862OMPClause *Sema::ActOnOpenMPLinearClause(
10863 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10864 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10865 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010866 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010867 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000010868 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010869 SmallVector<Decl *, 4> ExprCaptures;
10870 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010871 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000010872 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +000010873 for (auto &RefExpr : VarList) {
10874 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010875 SourceLocation ELoc;
10876 SourceRange ERange;
10877 Expr *SimpleRefExpr = RefExpr;
10878 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10879 /*AllowArraySection=*/false);
10880 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010881 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010882 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010883 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000010884 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000010885 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010886 ValueDecl *D = Res.first;
10887 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000010888 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000010889
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010890 QualType Type = D->getType();
10891 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000010892
10893 // OpenMP [2.14.3.7, linear clause]
10894 // A list-item cannot appear in more than one linear clause.
10895 // A list-item that appears in a linear clause cannot appear in any
10896 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010897 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +000010898 if (DVar.RefExpr) {
10899 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10900 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010901 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000010902 continue;
10903 }
10904
Alexey Bataevecba70f2016-04-12 11:02:11 +000010905 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000010906 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010907 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000010908
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010909 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010910 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
10911 D->hasAttrs() ? &D->getAttrs() : nullptr);
10912 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010913 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010914 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010915 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010916 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010917 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000010918 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10919 if (!IsOpenMPCapturedDecl(D)) {
10920 ExprCaptures.push_back(Ref->getDecl());
10921 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10922 ExprResult RefRes = DefaultLvalueConversion(Ref);
10923 if (!RefRes.isUsable())
10924 continue;
10925 ExprResult PostUpdateRes =
10926 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10927 SimpleRefExpr, RefRes.get());
10928 if (!PostUpdateRes.isUsable())
10929 continue;
10930 ExprPostUpdates.push_back(
10931 IgnoredValueConversions(PostUpdateRes.get()).get());
10932 }
10933 }
10934 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010935 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010936 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010937 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010938 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010939 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010940 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010941 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10942
10943 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010944 Vars.push_back((VD || CurContext->isDependentContext())
10945 ? RefExpr->IgnoreParens()
10946 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010947 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000010948 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000010949 }
10950
10951 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010952 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010953
10954 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000010955 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010956 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
10957 !Step->isInstantiationDependent() &&
10958 !Step->containsUnexpandedParameterPack()) {
10959 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000010960 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000010961 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010962 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010963 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000010964
Alexander Musman3276a272015-03-21 10:12:56 +000010965 // Build var to save the step value.
10966 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010967 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000010968 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010969 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010970 ExprResult CalcStep =
10971 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010972 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +000010973
Alexander Musman8dba6642014-04-22 13:09:42 +000010974 // Warn about zero linear step (it would be probably better specified as
10975 // making corresponding variables 'const').
10976 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000010977 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
10978 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000010979 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
10980 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000010981 if (!IsConstant && CalcStep.isUsable()) {
10982 // Calculate the step beforehand instead of doing this on each iteration.
10983 // (This is not used if the number of iterations may be kfold-ed).
10984 CalcStepExpr = CalcStep.get();
10985 }
Alexander Musman8dba6642014-04-22 13:09:42 +000010986 }
10987
Alexey Bataev182227b2015-08-20 10:54:39 +000010988 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
10989 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010990 StepExpr, CalcStepExpr,
10991 buildPreInits(Context, ExprCaptures),
10992 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000010993}
10994
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010995static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
10996 Expr *NumIterations, Sema &SemaRef,
10997 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000010998 // Walk the vars and build update/final expressions for the CodeGen.
10999 SmallVector<Expr *, 8> Updates;
11000 SmallVector<Expr *, 8> Finals;
11001 Expr *Step = Clause.getStep();
11002 Expr *CalcStep = Clause.getCalcStep();
11003 // OpenMP [2.14.3.7, linear clause]
11004 // If linear-step is not specified it is assumed to be 1.
11005 if (Step == nullptr)
11006 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000011007 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +000011008 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +000011009 }
Alexander Musman3276a272015-03-21 10:12:56 +000011010 bool HasErrors = false;
11011 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011012 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011013 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +000011014 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011015 SourceLocation ELoc;
11016 SourceRange ERange;
11017 Expr *SimpleRefExpr = RefExpr;
11018 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
11019 /*AllowArraySection=*/false);
11020 ValueDecl *D = Res.first;
11021 if (Res.second || !D) {
11022 Updates.push_back(nullptr);
11023 Finals.push_back(nullptr);
11024 HasErrors = true;
11025 continue;
11026 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011027 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000011028 // OpenMP [2.15.11, distribute simd Construct]
11029 // A list item may not appear in a linear clause, unless it is the loop
11030 // iteration variable.
11031 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
11032 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
11033 SemaRef.Diag(ELoc,
11034 diag::err_omp_linear_distribute_var_non_loop_iteration);
11035 Updates.push_back(nullptr);
11036 Finals.push_back(nullptr);
11037 HasErrors = true;
11038 continue;
11039 }
Alexander Musman3276a272015-03-21 10:12:56 +000011040 Expr *InitExpr = *CurInit;
11041
11042 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000011043 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000011044 Expr *CapturedRef;
11045 if (LinKind == OMPC_LINEAR_uval)
11046 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
11047 else
11048 CapturedRef =
11049 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
11050 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
11051 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011052
11053 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011054 ExprResult Update;
11055 if (!Info.first) {
11056 Update =
11057 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
11058 InitExpr, IV, Step, /* Subtract */ false);
11059 } else
11060 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011061 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
11062 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011063
11064 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011065 ExprResult Final;
11066 if (!Info.first) {
11067 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
11068 InitExpr, NumIterations, Step,
11069 /* Subtract */ false);
11070 } else
11071 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011072 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
11073 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011074
Alexander Musman3276a272015-03-21 10:12:56 +000011075 if (!Update.isUsable() || !Final.isUsable()) {
11076 Updates.push_back(nullptr);
11077 Finals.push_back(nullptr);
11078 HasErrors = true;
11079 } else {
11080 Updates.push_back(Update.get());
11081 Finals.push_back(Final.get());
11082 }
Richard Trieucc3949d2016-02-18 22:34:54 +000011083 ++CurInit;
11084 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000011085 }
11086 Clause.setUpdates(Updates);
11087 Clause.setFinals(Finals);
11088 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000011089}
11090
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011091OMPClause *Sema::ActOnOpenMPAlignedClause(
11092 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11093 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
11094
11095 SmallVector<Expr *, 8> Vars;
11096 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000011097 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11098 SourceLocation ELoc;
11099 SourceRange ERange;
11100 Expr *SimpleRefExpr = RefExpr;
11101 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11102 /*AllowArraySection=*/false);
11103 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011104 // It will be analyzed later.
11105 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011106 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000011107 ValueDecl *D = Res.first;
11108 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011109 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011110
Alexey Bataev1efd1662016-03-29 10:59:56 +000011111 QualType QType = D->getType();
11112 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011113
11114 // OpenMP [2.8.1, simd construct, Restrictions]
11115 // The type of list items appearing in the aligned clause must be
11116 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011117 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011118 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000011119 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011120 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011121 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011122 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000011123 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011124 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000011125 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011126 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011127 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011128 continue;
11129 }
11130
11131 // OpenMP [2.8.1, simd construct, Restrictions]
11132 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000011133 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000011134 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011135 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11136 << getOpenMPClauseName(OMPC_aligned);
11137 continue;
11138 }
11139
Alexey Bataev1efd1662016-03-29 10:59:56 +000011140 DeclRefExpr *Ref = nullptr;
11141 if (!VD && IsOpenMPCapturedDecl(D))
11142 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11143 Vars.push_back(DefaultFunctionArrayConversion(
11144 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11145 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011146 }
11147
11148 // OpenMP [2.8.1, simd construct, Description]
11149 // The parameter of the aligned clause, alignment, must be a constant
11150 // positive integer expression.
11151 // If no optional parameter is specified, implementation-defined default
11152 // alignments for SIMD instructions on the target platforms are assumed.
11153 if (Alignment != nullptr) {
11154 ExprResult AlignResult =
11155 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
11156 if (AlignResult.isInvalid())
11157 return nullptr;
11158 Alignment = AlignResult.get();
11159 }
11160 if (Vars.empty())
11161 return nullptr;
11162
11163 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
11164 EndLoc, Vars, Alignment);
11165}
11166
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011167OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11168 SourceLocation StartLoc,
11169 SourceLocation LParenLoc,
11170 SourceLocation EndLoc) {
11171 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011172 SmallVector<Expr *, 8> SrcExprs;
11173 SmallVector<Expr *, 8> DstExprs;
11174 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000011175 for (auto &RefExpr : VarList) {
11176 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
11177 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011178 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011179 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011180 SrcExprs.push_back(nullptr);
11181 DstExprs.push_back(nullptr);
11182 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011183 continue;
11184 }
11185
Alexey Bataeved09d242014-05-28 05:53:51 +000011186 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011187 // OpenMP [2.1, C/C++]
11188 // A list item is a variable name.
11189 // OpenMP [2.14.4.1, Restrictions, p.1]
11190 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000011191 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011192 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011193 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
11194 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011195 continue;
11196 }
11197
11198 Decl *D = DE->getDecl();
11199 VarDecl *VD = cast<VarDecl>(D);
11200
11201 QualType Type = VD->getType();
11202 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
11203 // It will be analyzed later.
11204 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011205 SrcExprs.push_back(nullptr);
11206 DstExprs.push_back(nullptr);
11207 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011208 continue;
11209 }
11210
11211 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
11212 // A list item that appears in a copyin clause must be threadprivate.
11213 if (!DSAStack->isThreadPrivate(VD)) {
11214 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000011215 << getOpenMPClauseName(OMPC_copyin)
11216 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011217 continue;
11218 }
11219
11220 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11221 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000011222 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011223 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011224 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000011225 auto *SrcVD =
11226 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
11227 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000011228 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011229 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
11230 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000011231 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
11232 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011233 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011234 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011235 // For arrays generate assignment operation for single element and replace
11236 // it by the original array element in CodeGen.
11237 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
11238 PseudoDstExpr, PseudoSrcExpr);
11239 if (AssignmentOp.isInvalid())
11240 continue;
11241 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
11242 /*DiscardedValue=*/true);
11243 if (AssignmentOp.isInvalid())
11244 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011245
11246 DSAStack->addDSA(VD, DE, OMPC_copyin);
11247 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011248 SrcExprs.push_back(PseudoSrcExpr);
11249 DstExprs.push_back(PseudoDstExpr);
11250 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011251 }
11252
Alexey Bataeved09d242014-05-28 05:53:51 +000011253 if (Vars.empty())
11254 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011255
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011256 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11257 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011258}
11259
Alexey Bataevbae9a792014-06-27 10:37:06 +000011260OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11261 SourceLocation StartLoc,
11262 SourceLocation LParenLoc,
11263 SourceLocation EndLoc) {
11264 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000011265 SmallVector<Expr *, 8> SrcExprs;
11266 SmallVector<Expr *, 8> DstExprs;
11267 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011268 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011269 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11270 SourceLocation ELoc;
11271 SourceRange ERange;
11272 Expr *SimpleRefExpr = RefExpr;
11273 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11274 /*AllowArraySection=*/false);
11275 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011276 // It will be analyzed later.
11277 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011278 SrcExprs.push_back(nullptr);
11279 DstExprs.push_back(nullptr);
11280 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011281 }
Alexey Bataeve122da12016-03-17 10:50:17 +000011282 ValueDecl *D = Res.first;
11283 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000011284 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011285
Alexey Bataeve122da12016-03-17 10:50:17 +000011286 QualType Type = D->getType();
11287 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011288
11289 // OpenMP [2.14.4.2, Restrictions, p.2]
11290 // A list item that appears in a copyprivate clause may not appear in a
11291 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000011292 if (!VD || !DSAStack->isThreadPrivate(VD)) {
11293 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011294 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
11295 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011296 Diag(ELoc, diag::err_omp_wrong_dsa)
11297 << getOpenMPClauseName(DVar.CKind)
11298 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000011299 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011300 continue;
11301 }
11302
11303 // OpenMP [2.11.4.2, Restrictions, p.1]
11304 // All list items that appear in a copyprivate clause must be either
11305 // threadprivate or private in the enclosing context.
11306 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011307 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011308 if (DVar.CKind == OMPC_shared) {
11309 Diag(ELoc, diag::err_omp_required_access)
11310 << getOpenMPClauseName(OMPC_copyprivate)
11311 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000011312 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011313 continue;
11314 }
11315 }
11316 }
11317
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011318 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011319 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011320 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011321 << getOpenMPClauseName(OMPC_copyprivate) << Type
11322 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011323 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000011324 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011325 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000011326 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011327 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000011328 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011329 continue;
11330 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011331
Alexey Bataevbae9a792014-06-27 10:37:06 +000011332 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11333 // A variable of class type (or array thereof) that appears in a
11334 // copyin clause requires an accessible, unambiguous copy assignment
11335 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011336 Type = Context.getBaseElementType(Type.getNonReferenceType())
11337 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000011338 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011339 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
11340 D->hasAttrs() ? &D->getAttrs() : nullptr);
11341 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000011342 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011343 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
11344 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000011345 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000011346 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011347 PseudoDstExpr, PseudoSrcExpr);
11348 if (AssignmentOp.isInvalid())
11349 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000011350 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011351 /*DiscardedValue=*/true);
11352 if (AssignmentOp.isInvalid())
11353 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011354
11355 // No need to mark vars as copyprivate, they are already threadprivate or
11356 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000011357 assert(VD || IsOpenMPCapturedDecl(D));
11358 Vars.push_back(
11359 VD ? RefExpr->IgnoreParens()
11360 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000011361 SrcExprs.push_back(PseudoSrcExpr);
11362 DstExprs.push_back(PseudoDstExpr);
11363 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000011364 }
11365
11366 if (Vars.empty())
11367 return nullptr;
11368
Alexey Bataeva63048e2015-03-23 06:18:07 +000011369 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11370 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011371}
11372
Alexey Bataev6125da92014-07-21 11:26:11 +000011373OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11374 SourceLocation StartLoc,
11375 SourceLocation LParenLoc,
11376 SourceLocation EndLoc) {
11377 if (VarList.empty())
11378 return nullptr;
11379
11380 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
11381}
Alexey Bataevdea47612014-07-23 07:46:59 +000011382
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011383OMPClause *
11384Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
11385 SourceLocation DepLoc, SourceLocation ColonLoc,
11386 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11387 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011388 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011389 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011390 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011391 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000011392 return nullptr;
11393 }
11394 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011395 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
11396 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011397 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011398 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011399 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
11400 /*Last=*/OMPC_DEPEND_unknown, Except)
11401 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011402 return nullptr;
11403 }
11404 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000011405 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011406 llvm::APSInt DepCounter(/*BitWidth=*/32);
11407 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
11408 if (DepKind == OMPC_DEPEND_sink) {
11409 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
11410 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
11411 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011412 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011413 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011414 for (auto &RefExpr : VarList) {
11415 assert(RefExpr && "NULL expr in OpenMP shared clause.");
11416 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
11417 // It will be analyzed later.
11418 Vars.push_back(RefExpr);
11419 continue;
11420 }
11421
11422 SourceLocation ELoc = RefExpr->getExprLoc();
11423 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
11424 if (DepKind == OMPC_DEPEND_sink) {
11425 if (DSAStack->getParentOrderedRegionParam() &&
11426 DepCounter >= TotalDepCount) {
11427 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
11428 continue;
11429 }
11430 ++DepCounter;
11431 // OpenMP [2.13.9, Summary]
11432 // depend(dependence-type : vec), where dependence-type is:
11433 // 'sink' and where vec is the iteration vector, which has the form:
11434 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
11435 // where n is the value specified by the ordered clause in the loop
11436 // directive, xi denotes the loop iteration variable of the i-th nested
11437 // loop associated with the loop directive, and di is a constant
11438 // non-negative integer.
11439 if (CurContext->isDependentContext()) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011440 // It will be analyzed later.
11441 Vars.push_back(RefExpr);
11442 continue;
11443 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011444 SimpleExpr = SimpleExpr->IgnoreImplicit();
11445 OverloadedOperatorKind OOK = OO_None;
11446 SourceLocation OOLoc;
11447 Expr *LHS = SimpleExpr;
11448 Expr *RHS = nullptr;
11449 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
11450 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
11451 OOLoc = BO->getOperatorLoc();
11452 LHS = BO->getLHS()->IgnoreParenImpCasts();
11453 RHS = BO->getRHS()->IgnoreParenImpCasts();
11454 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
11455 OOK = OCE->getOperator();
11456 OOLoc = OCE->getOperatorLoc();
11457 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11458 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
11459 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
11460 OOK = MCE->getMethodDecl()
11461 ->getNameInfo()
11462 .getName()
11463 .getCXXOverloadedOperator();
11464 OOLoc = MCE->getCallee()->getExprLoc();
11465 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
11466 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011467 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011468 SourceLocation ELoc;
11469 SourceRange ERange;
11470 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
11471 /*AllowArraySection=*/false);
11472 if (Res.second) {
11473 // It will be analyzed later.
11474 Vars.push_back(RefExpr);
11475 }
11476 ValueDecl *D = Res.first;
11477 if (!D)
11478 continue;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011479
Alexey Bataev17daedf2018-02-15 22:42:57 +000011480 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
11481 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
11482 continue;
11483 }
11484 if (RHS) {
11485 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
11486 RHS, OMPC_depend, /*StrictlyPositive=*/false);
11487 if (RHSRes.isInvalid())
11488 continue;
11489 }
11490 if (!CurContext->isDependentContext() &&
11491 DSAStack->getParentOrderedRegionParam() &&
11492 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
11493 ValueDecl *VD =
11494 DSAStack->getParentLoopControlVariable(DepCounter.getZExtValue());
11495 if (VD) {
11496 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
11497 << 1 << VD;
11498 } else {
11499 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
11500 }
11501 continue;
11502 }
11503 OpsOffs.push_back({RHS, OOK});
11504 } else {
11505 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
11506 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
11507 (ASE &&
11508 !ASE->getBase()->getType().getNonReferenceType()->isPointerType() &&
11509 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
11510 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11511 << RefExpr->getSourceRange();
11512 continue;
11513 }
11514 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
11515 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
11516 ExprResult Res =
11517 CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RefExpr->IgnoreParenImpCasts());
11518 getDiagnostics().setSuppressAllDiagnostics(Suppress);
11519 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
11520 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11521 << RefExpr->getSourceRange();
11522 continue;
11523 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011524 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011525 Vars.push_back(RefExpr->IgnoreParenImpCasts());
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011526 }
Alexey Bataev17daedf2018-02-15 22:42:57 +000011527
11528 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
11529 TotalDepCount > VarList.size() &&
11530 DSAStack->getParentOrderedRegionParam() &&
11531 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
11532 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration)
11533 << 1 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
11534 }
11535 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
11536 Vars.empty())
11537 return nullptr;
11538
Alexey Bataev8b427062016-05-25 12:36:08 +000011539 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11540 DepKind, DepLoc, ColonLoc, Vars);
Alexey Bataev17daedf2018-02-15 22:42:57 +000011541 if ((DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source) &&
11542 DSAStack->isParentOrderedRegion())
Alexey Bataev8b427062016-05-25 12:36:08 +000011543 DSAStack->addDoacrossDependClause(C, OpsOffs);
11544 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011545}
Michael Wonge710d542015-08-07 16:16:36 +000011546
11547OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
11548 SourceLocation LParenLoc,
11549 SourceLocation EndLoc) {
11550 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000011551 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000011552
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011553 // OpenMP [2.9.1, Restrictions]
11554 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011555 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
11556 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011557 return nullptr;
11558
Alexey Bataev931e19b2017-10-02 16:32:39 +000011559 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011560 OpenMPDirectiveKind CaptureRegion =
11561 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
11562 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011563 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev931e19b2017-10-02 16:32:39 +000011564 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11565 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11566 HelperValStmt = buildPreInits(Context, Captures);
11567 }
11568
Alexey Bataev8451efa2018-01-15 19:06:12 +000011569 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
11570 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000011571}
Kelvin Li0bff7af2015-11-23 05:32:03 +000011572
Kelvin Li0bff7af2015-11-23 05:32:03 +000011573static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
Alexey Bataev95c23e72018-02-27 21:31:11 +000011574 DSAStackTy *Stack, QualType QTy,
11575 bool FullCheck = true) {
Kelvin Li0bff7af2015-11-23 05:32:03 +000011576 NamedDecl *ND;
11577 if (QTy->isIncompleteType(&ND)) {
11578 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
11579 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011580 }
Alexey Bataev95c23e72018-02-27 21:31:11 +000011581 if (FullCheck && !SemaRef.CurContext->isDependentContext() &&
11582 !QTy.isTrivialType(SemaRef.Context))
11583 SemaRef.Diag(SL, diag::warn_omp_non_trivial_type_mapped) << QTy << SR;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011584 return true;
11585}
11586
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011587/// \brief Return true if it can be proven that the provided array expression
11588/// (array section or array subscript) does NOT specify the whole size of the
11589/// array whose base type is \a BaseQTy.
11590static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
11591 const Expr *E,
11592 QualType BaseQTy) {
11593 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11594
11595 // If this is an array subscript, it refers to the whole size if the size of
11596 // the dimension is constant and equals 1. Also, an array section assumes the
11597 // format of an array subscript if no colon is used.
11598 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
11599 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11600 return ATy->getSize().getSExtValue() != 1;
11601 // Size can't be evaluated statically.
11602 return false;
11603 }
11604
11605 assert(OASE && "Expecting array section if not an array subscript.");
11606 auto *LowerBound = OASE->getLowerBound();
11607 auto *Length = OASE->getLength();
11608
11609 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000011610 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011611 if (LowerBound) {
11612 llvm::APSInt ConstLowerBound;
11613 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
11614 return false; // Can't get the integer value as a constant.
11615 if (ConstLowerBound.getSExtValue())
11616 return true;
11617 }
11618
11619 // If we don't have a length we covering the whole dimension.
11620 if (!Length)
11621 return false;
11622
11623 // If the base is a pointer, we don't have a way to get the size of the
11624 // pointee.
11625 if (BaseQTy->isPointerType())
11626 return false;
11627
11628 // We can only check if the length is the same as the size of the dimension
11629 // if we have a constant array.
11630 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
11631 if (!CATy)
11632 return false;
11633
11634 llvm::APSInt ConstLength;
11635 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11636 return false; // Can't get the integer value as a constant.
11637
11638 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
11639}
11640
11641// Return true if it can be proven that the provided array expression (array
11642// section or array subscript) does NOT specify a single element of the array
11643// whose base type is \a BaseQTy.
11644static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000011645 const Expr *E,
11646 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011647 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11648
11649 // An array subscript always refer to a single element. Also, an array section
11650 // assumes the format of an array subscript if no colon is used.
11651 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11652 return false;
11653
11654 assert(OASE && "Expecting array section if not an array subscript.");
11655 auto *Length = OASE->getLength();
11656
11657 // If we don't have a length we have to check if the array has unitary size
11658 // for this dimension. Also, we should always expect a length if the base type
11659 // is pointer.
11660 if (!Length) {
11661 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11662 return ATy->getSize().getSExtValue() != 1;
11663 // We cannot assume anything.
11664 return false;
11665 }
11666
11667 // Check if the length evaluates to 1.
11668 llvm::APSInt ConstLength;
11669 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11670 return false; // Can't get the integer value as a constant.
11671
11672 return ConstLength.getSExtValue() != 1;
11673}
11674
Samuel Antao661c0902016-05-26 17:39:58 +000011675// Return the expression of the base of the mappable expression or null if it
11676// cannot be determined and do all the necessary checks to see if the expression
11677// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000011678// components of the expression.
11679static Expr *CheckMapClauseExpressionBase(
11680 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000011681 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011682 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011683 SourceLocation ELoc = E->getExprLoc();
11684 SourceRange ERange = E->getSourceRange();
11685
11686 // The base of elements of list in a map clause have to be either:
11687 // - a reference to variable or field.
11688 // - a member expression.
11689 // - an array expression.
11690 //
11691 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11692 // reference to 'r'.
11693 //
11694 // If we have:
11695 //
11696 // struct SS {
11697 // Bla S;
11698 // foo() {
11699 // #pragma omp target map (S.Arr[:12]);
11700 // }
11701 // }
11702 //
11703 // We want to retrieve the member expression 'this->S';
11704
11705 Expr *RelevantExpr = nullptr;
11706
Samuel Antao5de996e2016-01-22 20:21:36 +000011707 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11708 // If a list item is an array section, it must specify contiguous storage.
11709 //
11710 // For this restriction it is sufficient that we make sure only references
11711 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011712 // exist except in the rightmost expression (unless they cover the whole
11713 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000011714 //
11715 // r.ArrS[3:5].Arr[6:7]
11716 //
11717 // r.ArrS[3:5].x
11718 //
11719 // but these would be valid:
11720 // r.ArrS[3].Arr[6:7]
11721 //
11722 // r.ArrS[3].x
11723
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011724 bool AllowUnitySizeArraySection = true;
11725 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000011726
Dmitry Polukhin644a9252016-03-11 07:58:34 +000011727 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011728 E = E->IgnoreParenImpCasts();
11729
11730 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11731 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000011732 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011733
11734 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011735
11736 // If we got a reference to a declaration, we should not expect any array
11737 // section before that.
11738 AllowUnitySizeArraySection = false;
11739 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011740
11741 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011742 CurComponents.emplace_back(CurE, CurE->getDecl());
11743 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011744 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11745
11746 if (isa<CXXThisExpr>(BaseE))
11747 // We found a base expression: this->Val.
11748 RelevantExpr = CurE;
11749 else
11750 E = BaseE;
11751
11752 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011753 if (!NoDiagnose) {
11754 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11755 << CurE->getSourceRange();
11756 return nullptr;
11757 }
11758 if (RelevantExpr)
11759 return nullptr;
11760 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011761 }
11762
11763 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11764
11765 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11766 // A bit-field cannot appear in a map clause.
11767 //
11768 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011769 if (!NoDiagnose) {
11770 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11771 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
11772 return nullptr;
11773 }
11774 if (RelevantExpr)
11775 return nullptr;
11776 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011777 }
11778
11779 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11780 // If the type of a list item is a reference to a type T then the type
11781 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011782 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011783
11784 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11785 // A list item cannot be a variable that is a member of a structure with
11786 // a union type.
11787 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011788 if (auto *RT = CurType->getAs<RecordType>()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011789 if (RT->isUnionType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011790 if (!NoDiagnose) {
11791 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11792 << CurE->getSourceRange();
11793 return nullptr;
11794 }
11795 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011796 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011797 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011798
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011799 // If we got a member expression, we should not expect any array section
11800 // before that:
11801 //
11802 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11803 // If a list item is an element of a structure, only the rightmost symbol
11804 // of the variable reference can be an array section.
11805 //
11806 AllowUnitySizeArraySection = false;
11807 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011808
11809 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011810 CurComponents.emplace_back(CurE, FD);
11811 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011812 E = CurE->getBase()->IgnoreParenImpCasts();
11813
11814 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011815 if (!NoDiagnose) {
11816 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11817 << 0 << CurE->getSourceRange();
11818 return nullptr;
11819 }
11820 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011821 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011822
11823 // If we got an array subscript that express the whole dimension we
11824 // can have any array expressions before. If it only expressing part of
11825 // the dimension, we can only have unitary-size array expressions.
11826 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11827 E->getType()))
11828 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011829
11830 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011831 CurComponents.emplace_back(CurE, nullptr);
11832 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011833 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000011834 E = CurE->getBase()->IgnoreParenImpCasts();
11835
Alexey Bataev27041fa2017-12-05 15:22:49 +000011836 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011837 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11838
Samuel Antao5de996e2016-01-22 20:21:36 +000011839 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11840 // If the type of a list item is a reference to a type T then the type
11841 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000011842 if (CurType->isReferenceType())
11843 CurType = CurType->getPointeeType();
11844
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011845 bool IsPointer = CurType->isAnyPointerType();
11846
11847 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011848 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11849 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000011850 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011851 }
11852
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011853 bool NotWhole =
11854 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11855 bool NotUnity =
11856 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11857
Samuel Antaodab51bb2016-07-18 23:22:11 +000011858 if (AllowWholeSizeArraySection) {
11859 // Any array section is currently allowed. Allowing a whole size array
11860 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011861 //
11862 // If this array section refers to the whole dimension we can still
11863 // accept other array sections before this one, except if the base is a
11864 // pointer. Otherwise, only unitary sections are accepted.
11865 if (NotWhole || IsPointer)
11866 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000011867 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011868 // A unity or whole array section is not allowed and that is not
11869 // compatible with the properties of the current array section.
11870 SemaRef.Diag(
11871 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11872 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000011873 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011874 }
Samuel Antao90927002016-04-26 14:54:23 +000011875
11876 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011877 CurComponents.emplace_back(CurE, nullptr);
11878 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011879 if (!NoDiagnose) {
11880 // If nothing else worked, this is not a valid map clause expression.
11881 SemaRef.Diag(
11882 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
11883 << ERange;
11884 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000011885 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011886 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011887 }
11888
11889 return RelevantExpr;
11890}
11891
11892// Return true if expression E associated with value VD has conflicts with other
11893// map information.
Samuel Antao90927002016-04-26 14:54:23 +000011894static bool CheckMapConflicts(
11895 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11896 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000011897 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11898 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011899 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000011900 SourceLocation ELoc = E->getExprLoc();
11901 SourceRange ERange = E->getSourceRange();
11902
11903 // In order to easily check the conflicts we need to match each component of
11904 // the expression under test with the components of the expressions that are
11905 // already in the stack.
11906
Samuel Antao5de996e2016-01-22 20:21:36 +000011907 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011908 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011909 "Map clause expression with unexpected base!");
11910
11911 // Variables to help detecting enclosing problems in data environment nests.
11912 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000011913 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011914
Samuel Antao90927002016-04-26 14:54:23 +000011915 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11916 VD, CurrentRegionOnly,
11917 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000011918 StackComponents,
11919 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000011920
Samuel Antao5de996e2016-01-22 20:21:36 +000011921 assert(!StackComponents.empty() &&
11922 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011923 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011924 "Map clause expression with unexpected base!");
11925
Samuel Antao90927002016-04-26 14:54:23 +000011926 // The whole expression in the stack.
11927 auto *RE = StackComponents.front().getAssociatedExpression();
11928
Samuel Antao5de996e2016-01-22 20:21:36 +000011929 // Expressions must start from the same base. Here we detect at which
11930 // point both expressions diverge from each other and see if we can
11931 // detect if the memory referred to both expressions is contiguous and
11932 // do not overlap.
11933 auto CI = CurComponents.rbegin();
11934 auto CE = CurComponents.rend();
11935 auto SI = StackComponents.rbegin();
11936 auto SE = StackComponents.rend();
11937 for (; CI != CE && SI != SE; ++CI, ++SI) {
11938
11939 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11940 // At most one list item can be an array item derived from a given
11941 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000011942 if (CurrentRegionOnly &&
11943 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
11944 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
11945 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
11946 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
11947 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000011948 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000011949 << CI->getAssociatedExpression()->getSourceRange();
11950 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
11951 diag::note_used_here)
11952 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000011953 return true;
11954 }
11955
11956 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000011957 if (CI->getAssociatedExpression()->getStmtClass() !=
11958 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000011959 break;
11960
11961 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000011962 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000011963 break;
11964 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000011965 // Check if the extra components of the expressions in the enclosing
11966 // data environment are redundant for the current base declaration.
11967 // If they are, the maps completely overlap, which is legal.
11968 for (; SI != SE; ++SI) {
11969 QualType Type;
11970 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000011971 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011972 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000011973 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
11974 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011975 auto *E = OASE->getBase()->IgnoreParenImpCasts();
11976 Type =
11977 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11978 }
11979 if (Type.isNull() || Type->isAnyPointerType() ||
11980 CheckArrayExpressionDoesNotReferToWholeSize(
11981 SemaRef, SI->getAssociatedExpression(), Type))
11982 break;
11983 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011984
11985 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11986 // List items of map clauses in the same construct must not share
11987 // original storage.
11988 //
11989 // If the expressions are exactly the same or one is a subset of the
11990 // other, it means they are sharing storage.
11991 if (CI == CE && SI == SE) {
11992 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000011993 if (CKind == OMPC_map)
11994 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11995 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011996 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011997 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11998 << ERange;
11999 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012000 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12001 << RE->getSourceRange();
12002 return true;
12003 } else {
12004 // If we find the same expression in the enclosing data environment,
12005 // that is legal.
12006 IsEnclosedByDataEnvironmentExpr = true;
12007 return false;
12008 }
12009 }
12010
Samuel Antao90927002016-04-26 14:54:23 +000012011 QualType DerivedType =
12012 std::prev(CI)->getAssociatedDeclaration()->getType();
12013 SourceLocation DerivedLoc =
12014 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000012015
12016 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12017 // If the type of a list item is a reference to a type T then the type
12018 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000012019 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012020
12021 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
12022 // A variable for which the type is pointer and an array section
12023 // derived from that variable must not appear as list items of map
12024 // clauses of the same construct.
12025 //
12026 // Also, cover one of the cases in:
12027 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12028 // If any part of the original storage of a list item has corresponding
12029 // storage in the device data environment, all of the original storage
12030 // must have corresponding storage in the device data environment.
12031 //
12032 if (DerivedType->isAnyPointerType()) {
12033 if (CI == CE || SI == SE) {
12034 SemaRef.Diag(
12035 DerivedLoc,
12036 diag::err_omp_pointer_mapped_along_with_derived_section)
12037 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012038 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12039 << RE->getSourceRange();
12040 return true;
12041 } else if (CI->getAssociatedExpression()->getStmtClass() !=
12042 SI->getAssociatedExpression()->getStmtClass() ||
12043 CI->getAssociatedDeclaration()->getCanonicalDecl() ==
12044 SI->getAssociatedDeclaration()->getCanonicalDecl()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012045 assert(CI != CE && SI != SE);
Alexey Bataev2819260b2018-02-27 17:42:00 +000012046 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_dereferenced)
Samuel Antao5de996e2016-01-22 20:21:36 +000012047 << DerivedLoc;
Alexey Bataev2819260b2018-02-27 17:42:00 +000012048 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12049 << RE->getSourceRange();
12050 return true;
Samuel Antao5de996e2016-01-22 20:21:36 +000012051 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012052 }
12053
12054 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
12055 // List items of map clauses in the same construct must not share
12056 // original storage.
12057 //
12058 // An expression is a subset of the other.
12059 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000012060 if (CKind == OMPC_map)
12061 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12062 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012063 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012064 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12065 << ERange;
12066 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012067 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12068 << RE->getSourceRange();
12069 return true;
12070 }
12071
12072 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000012073 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000012074 if (!CurrentRegionOnly && SI != SE)
12075 EnclosingExpr = RE;
12076
12077 // The current expression is a subset of the expression in the data
12078 // environment.
12079 IsEnclosedByDataEnvironmentExpr |=
12080 (!CurrentRegionOnly && CI != CE && SI == SE);
12081
12082 return false;
12083 });
12084
12085 if (CurrentRegionOnly)
12086 return FoundError;
12087
12088 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12089 // If any part of the original storage of a list item has corresponding
12090 // storage in the device data environment, all of the original storage must
12091 // have corresponding storage in the device data environment.
12092 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
12093 // If a list item is an element of a structure, and a different element of
12094 // the structure has a corresponding list item in the device data environment
12095 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000012096 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000012097 // data environment prior to the task encountering the construct.
12098 //
12099 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
12100 SemaRef.Diag(ELoc,
12101 diag::err_omp_original_storage_is_shared_and_does_not_contain)
12102 << ERange;
12103 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
12104 << EnclosingExpr->getSourceRange();
12105 return true;
12106 }
12107
12108 return FoundError;
12109}
12110
Samuel Antao661c0902016-05-26 17:39:58 +000012111namespace {
12112// Utility struct that gathers all the related lists associated with a mappable
12113// expression.
12114struct MappableVarListInfo final {
12115 // The list of expressions.
12116 ArrayRef<Expr *> VarList;
12117 // The list of processed expressions.
12118 SmallVector<Expr *, 16> ProcessedVarList;
12119 // The mappble components for each expression.
12120 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
12121 // The base declaration of the variable.
12122 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
12123
12124 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
12125 // We have a list of components and base declarations for each entry in the
12126 // variable list.
12127 VarComponents.reserve(VarList.size());
12128 VarBaseDeclarations.reserve(VarList.size());
12129 }
12130};
12131}
12132
12133// Check the validity of the provided variable list for the provided clause kind
12134// \a CKind. In the check process the valid expressions, and mappable expression
12135// components and variables are extracted and used to fill \a Vars,
12136// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
12137// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
12138static void
12139checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
12140 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
12141 SourceLocation StartLoc,
12142 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
12143 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000012144 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
12145 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000012146 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012147
Samuel Antao90927002016-04-26 14:54:23 +000012148 // Keep track of the mappable components and base declarations in this clause.
12149 // Each entry in the list is going to have a list of components associated. We
12150 // record each set of the components so that we can build the clause later on.
12151 // In the end we should have the same amount of declarations and component
12152 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000012153
Samuel Antao661c0902016-05-26 17:39:58 +000012154 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000012155 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012156 SourceLocation ELoc = RE->getExprLoc();
12157
Kelvin Li0bff7af2015-11-23 05:32:03 +000012158 auto *VE = RE->IgnoreParenLValueCasts();
12159
12160 if (VE->isValueDependent() || VE->isTypeDependent() ||
12161 VE->isInstantiationDependent() ||
12162 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012163 // We can only analyze this information once the missing information is
12164 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000012165 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012166 continue;
12167 }
12168
12169 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012170
Samuel Antao5de996e2016-01-22 20:21:36 +000012171 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000012172 SemaRef.Diag(ELoc,
12173 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000012174 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012175 continue;
12176 }
12177
Samuel Antao90927002016-04-26 14:54:23 +000012178 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
12179 ValueDecl *CurDeclaration = nullptr;
12180
12181 // Obtain the array or member expression bases if required. Also, fill the
12182 // components array with all the components identified in the process.
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012183 auto *BE = CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents,
12184 CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000012185 if (!BE)
12186 continue;
12187
Samuel Antao90927002016-04-26 14:54:23 +000012188 assert(!CurComponents.empty() &&
12189 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012190
Samuel Antao90927002016-04-26 14:54:23 +000012191 // For the following checks, we rely on the base declaration which is
12192 // expected to be associated with the last component. The declaration is
12193 // expected to be a variable or a field (if 'this' is being mapped).
12194 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
12195 assert(CurDeclaration && "Null decl on map clause.");
12196 assert(
12197 CurDeclaration->isCanonicalDecl() &&
12198 "Expecting components to have associated only canonical declarations.");
12199
12200 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
12201 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000012202
12203 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000012204 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000012205
12206 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000012207 // threadprivate variables cannot appear in a map clause.
12208 // OpenMP 4.5 [2.10.5, target update Construct]
12209 // threadprivate variables cannot appear in a from clause.
12210 if (VD && DSAS->isThreadPrivate(VD)) {
12211 auto DVar = DSAS->getTopDSA(VD, false);
12212 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
12213 << getOpenMPClauseName(CKind);
12214 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012215 continue;
12216 }
12217
Samuel Antao5de996e2016-01-22 20:21:36 +000012218 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12219 // A list item cannot appear in both a map clause and a data-sharing
12220 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000012221
Samuel Antao5de996e2016-01-22 20:21:36 +000012222 // Check conflicts with other map clause expressions. We check the conflicts
12223 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000012224 // environment, because the restrictions are different. We only have to
12225 // check conflicts across regions for the map clauses.
12226 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12227 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000012228 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012229 if (CKind == OMPC_map &&
12230 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12231 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000012232 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012233
Samuel Antao661c0902016-05-26 17:39:58 +000012234 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000012235 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12236 // If the type of a list item is a reference to a type T then the type will
12237 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000012238 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012239
Samuel Antao661c0902016-05-26 17:39:58 +000012240 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
12241 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000012242 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000012243 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000012244 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
12245 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000012246 continue;
12247
Samuel Antao661c0902016-05-26 17:39:58 +000012248 if (CKind == OMPC_map) {
12249 // target enter data
12250 // OpenMP [2.10.2, Restrictions, p. 99]
12251 // A map-type must be specified in all map clauses and must be either
12252 // to or alloc.
12253 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
12254 if (DKind == OMPD_target_enter_data &&
12255 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
12256 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12257 << (IsMapTypeImplicit ? 1 : 0)
12258 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12259 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012260 continue;
12261 }
Samuel Antao661c0902016-05-26 17:39:58 +000012262
12263 // target exit_data
12264 // OpenMP [2.10.3, Restrictions, p. 102]
12265 // A map-type must be specified in all map clauses and must be either
12266 // from, release, or delete.
12267 if (DKind == OMPD_target_exit_data &&
12268 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
12269 MapType == OMPC_MAP_delete)) {
12270 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12271 << (IsMapTypeImplicit ? 1 : 0)
12272 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12273 << getOpenMPDirectiveName(DKind);
12274 continue;
12275 }
12276
12277 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12278 // A list item cannot appear in both a map clause and a data-sharing
12279 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000012280 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000012281 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000012282 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000012283 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
12284 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000012285 auto DVar = DSAS->getTopDSA(VD, false);
12286 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000012287 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000012288 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000012289 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000012290 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
12291 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
12292 continue;
12293 }
12294 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012295 }
12296
Samuel Antao90927002016-04-26 14:54:23 +000012297 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000012298 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000012299
12300 // Store the components in the stack so that they can be used to check
12301 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000012302 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
12303 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000012304
12305 // Save the components and declaration to create the clause. For purposes of
12306 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000012307 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000012308 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12309 MVLI.VarComponents.back().append(CurComponents.begin(),
12310 CurComponents.end());
12311 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
12312 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012313 }
Samuel Antao661c0902016-05-26 17:39:58 +000012314}
12315
12316OMPClause *
12317Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
12318 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12319 SourceLocation MapLoc, SourceLocation ColonLoc,
12320 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12321 SourceLocation LParenLoc, SourceLocation EndLoc) {
12322 MappableVarListInfo MVLI(VarList);
12323 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
12324 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012325
Samuel Antao5de996e2016-01-22 20:21:36 +000012326 // We need to produce a map clause even if we don't have variables so that
12327 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000012328 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12329 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12330 MVLI.VarComponents, MapTypeModifier, MapType,
12331 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012332}
Kelvin Li099bb8c2015-11-24 20:50:12 +000012333
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012334QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
12335 TypeResult ParsedType) {
12336 assert(ParsedType.isUsable());
12337
12338 QualType ReductionType = GetTypeFromParser(ParsedType.get());
12339 if (ReductionType.isNull())
12340 return QualType();
12341
12342 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
12343 // A type name in a declare reduction directive cannot be a function type, an
12344 // array type, a reference type, or a type qualified with const, volatile or
12345 // restrict.
12346 if (ReductionType.hasQualifiers()) {
12347 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
12348 return QualType();
12349 }
12350
12351 if (ReductionType->isFunctionType()) {
12352 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
12353 return QualType();
12354 }
12355 if (ReductionType->isReferenceType()) {
12356 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
12357 return QualType();
12358 }
12359 if (ReductionType->isArrayType()) {
12360 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
12361 return QualType();
12362 }
12363 return ReductionType;
12364}
12365
12366Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
12367 Scope *S, DeclContext *DC, DeclarationName Name,
12368 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
12369 AccessSpecifier AS, Decl *PrevDeclInScope) {
12370 SmallVector<Decl *, 8> Decls;
12371 Decls.reserve(ReductionTypes.size());
12372
12373 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000012374 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012375 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
12376 // A reduction-identifier may not be re-declared in the current scope for the
12377 // same type or for a type that is compatible according to the base language
12378 // rules.
12379 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
12380 OMPDeclareReductionDecl *PrevDRD = nullptr;
12381 bool InCompoundScope = true;
12382 if (S != nullptr) {
12383 // Find previous declaration with the same name not referenced in other
12384 // declarations.
12385 FunctionScopeInfo *ParentFn = getEnclosingFunction();
12386 InCompoundScope =
12387 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
12388 LookupName(Lookup, S);
12389 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
12390 /*AllowInlineNamespace=*/false);
12391 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
12392 auto Filter = Lookup.makeFilter();
12393 while (Filter.hasNext()) {
12394 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
12395 if (InCompoundScope) {
12396 auto I = UsedAsPrevious.find(PrevDecl);
12397 if (I == UsedAsPrevious.end())
12398 UsedAsPrevious[PrevDecl] = false;
12399 if (auto *D = PrevDecl->getPrevDeclInScope())
12400 UsedAsPrevious[D] = true;
12401 }
12402 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
12403 PrevDecl->getLocation();
12404 }
12405 Filter.done();
12406 if (InCompoundScope) {
12407 for (auto &PrevData : UsedAsPrevious) {
12408 if (!PrevData.second) {
12409 PrevDRD = PrevData.first;
12410 break;
12411 }
12412 }
12413 }
12414 } else if (PrevDeclInScope != nullptr) {
12415 auto *PrevDRDInScope = PrevDRD =
12416 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
12417 do {
12418 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
12419 PrevDRDInScope->getLocation();
12420 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
12421 } while (PrevDRDInScope != nullptr);
12422 }
12423 for (auto &TyData : ReductionTypes) {
12424 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
12425 bool Invalid = false;
12426 if (I != PreviousRedeclTypes.end()) {
12427 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
12428 << TyData.first;
12429 Diag(I->second, diag::note_previous_definition);
12430 Invalid = true;
12431 }
12432 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
12433 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
12434 Name, TyData.first, PrevDRD);
12435 DC->addDecl(DRD);
12436 DRD->setAccess(AS);
12437 Decls.push_back(DRD);
12438 if (Invalid)
12439 DRD->setInvalidDecl();
12440 else
12441 PrevDRD = DRD;
12442 }
12443
12444 return DeclGroupPtrTy::make(
12445 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
12446}
12447
12448void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
12449 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12450
12451 // Enter new function scope.
12452 PushFunctionScope();
Reid Kleckner8d485b82018-03-08 01:12:22 +000012453 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012454 getCurFunction()->setHasOMPDeclareReductionCombiner();
12455
12456 if (S != nullptr)
12457 PushDeclContext(S, DRD);
12458 else
12459 CurContext = DRD;
12460
Faisal Valid143a0c2017-04-01 21:30:49 +000012461 PushExpressionEvaluationContext(
12462 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012463
12464 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012465 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
12466 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
12467 // uses semantics of argument handles by value, but it should be passed by
12468 // reference. C lang does not support references, so pass all parameters as
12469 // pointers.
12470 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012471 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012472 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012473 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
12474 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
12475 // uses semantics of argument handles by value, but it should be passed by
12476 // reference. C lang does not support references, so pass all parameters as
12477 // pointers.
12478 // Create 'T omp_out;' variable.
12479 auto *OmpOutParm =
12480 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
12481 if (S != nullptr) {
12482 PushOnScopeChains(OmpInParm, S);
12483 PushOnScopeChains(OmpOutParm, S);
12484 } else {
12485 DRD->addDecl(OmpInParm);
12486 DRD->addDecl(OmpOutParm);
12487 }
12488}
12489
12490void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
12491 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12492 DiscardCleanupsInEvaluationContext();
12493 PopExpressionEvaluationContext();
12494
12495 PopDeclContext();
12496 PopFunctionScopeInfo();
12497
12498 if (Combiner != nullptr)
12499 DRD->setCombiner(Combiner);
12500 else
12501 DRD->setInvalidDecl();
12502}
12503
Alexey Bataev070f43a2017-09-06 14:49:58 +000012504VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012505 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12506
12507 // Enter new function scope.
12508 PushFunctionScope();
Reid Kleckner8d485b82018-03-08 01:12:22 +000012509 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012510
12511 if (S != nullptr)
12512 PushDeclContext(S, DRD);
12513 else
12514 CurContext = DRD;
12515
Faisal Valid143a0c2017-04-01 21:30:49 +000012516 PushExpressionEvaluationContext(
12517 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012518
12519 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012520 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
12521 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
12522 // uses semantics of argument handles by value, but it should be passed by
12523 // reference. C lang does not support references, so pass all parameters as
12524 // pointers.
12525 // Create 'T omp_priv;' variable.
12526 auto *OmpPrivParm =
12527 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012528 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
12529 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
12530 // uses semantics of argument handles by value, but it should be passed by
12531 // reference. C lang does not support references, so pass all parameters as
12532 // pointers.
12533 // Create 'T omp_orig;' variable.
12534 auto *OmpOrigParm =
12535 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012536 if (S != nullptr) {
12537 PushOnScopeChains(OmpPrivParm, S);
12538 PushOnScopeChains(OmpOrigParm, S);
12539 } else {
12540 DRD->addDecl(OmpPrivParm);
12541 DRD->addDecl(OmpOrigParm);
12542 }
Alexey Bataev070f43a2017-09-06 14:49:58 +000012543 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012544}
12545
Alexey Bataev070f43a2017-09-06 14:49:58 +000012546void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
12547 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012548 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12549 DiscardCleanupsInEvaluationContext();
12550 PopExpressionEvaluationContext();
12551
12552 PopDeclContext();
12553 PopFunctionScopeInfo();
12554
Alexey Bataev070f43a2017-09-06 14:49:58 +000012555 if (Initializer != nullptr) {
12556 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
12557 } else if (OmpPrivParm->hasInit()) {
12558 DRD->setInitializer(OmpPrivParm->getInit(),
12559 OmpPrivParm->isDirectInit()
12560 ? OMPDeclareReductionDecl::DirectInit
12561 : OMPDeclareReductionDecl::CopyInit);
12562 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012563 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000012564 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012565}
12566
12567Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
12568 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
12569 for (auto *D : DeclReductions.get()) {
12570 if (IsValid) {
12571 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12572 if (S != nullptr)
12573 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
12574 } else
12575 D->setInvalidDecl();
12576 }
12577 return DeclReductions;
12578}
12579
David Majnemer9d168222016-08-05 17:44:54 +000012580OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000012581 SourceLocation StartLoc,
12582 SourceLocation LParenLoc,
12583 SourceLocation EndLoc) {
12584 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012585 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012586
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012587 // OpenMP [teams Constrcut, Restrictions]
12588 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012589 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
12590 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012591 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012592
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012593 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012594 OpenMPDirectiveKind CaptureRegion =
12595 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
12596 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012597 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012598 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12599 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12600 HelperValStmt = buildPreInits(Context, Captures);
12601 }
12602
12603 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
12604 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000012605}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012606
12607OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12608 SourceLocation StartLoc,
12609 SourceLocation LParenLoc,
12610 SourceLocation EndLoc) {
12611 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012612 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012613
12614 // OpenMP [teams Constrcut, Restrictions]
12615 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012616 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
12617 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012618 return nullptr;
12619
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012620 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012621 OpenMPDirectiveKind CaptureRegion =
12622 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
12623 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012624 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012625 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12626 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12627 HelperValStmt = buildPreInits(Context, Captures);
12628 }
12629
12630 return new (Context) OMPThreadLimitClause(
12631 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012632}
Alexey Bataeva0569352015-12-01 10:17:31 +000012633
12634OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
12635 SourceLocation StartLoc,
12636 SourceLocation LParenLoc,
12637 SourceLocation EndLoc) {
12638 Expr *ValExpr = Priority;
12639
12640 // OpenMP [2.9.1, task Constrcut]
12641 // The priority-value is a non-negative numerical scalar expression.
12642 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
12643 /*StrictlyPositive=*/false))
12644 return nullptr;
12645
12646 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12647}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012648
12649OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
12650 SourceLocation StartLoc,
12651 SourceLocation LParenLoc,
12652 SourceLocation EndLoc) {
12653 Expr *ValExpr = Grainsize;
12654
12655 // OpenMP [2.9.2, taskloop Constrcut]
12656 // The parameter of the grainsize clause must be a positive integer
12657 // expression.
12658 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
12659 /*StrictlyPositive=*/true))
12660 return nullptr;
12661
12662 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12663}
Alexey Bataev382967a2015-12-08 12:06:20 +000012664
12665OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12666 SourceLocation StartLoc,
12667 SourceLocation LParenLoc,
12668 SourceLocation EndLoc) {
12669 Expr *ValExpr = NumTasks;
12670
12671 // OpenMP [2.9.2, taskloop Constrcut]
12672 // The parameter of the num_tasks clause must be a positive integer
12673 // expression.
12674 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
12675 /*StrictlyPositive=*/true))
12676 return nullptr;
12677
12678 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12679}
12680
Alexey Bataev28c75412015-12-15 08:19:24 +000012681OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12682 SourceLocation LParenLoc,
12683 SourceLocation EndLoc) {
12684 // OpenMP [2.13.2, critical construct, Description]
12685 // ... where hint-expression is an integer constant expression that evaluates
12686 // to a valid lock hint.
12687 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12688 if (HintExpr.isInvalid())
12689 return nullptr;
12690 return new (Context)
12691 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12692}
12693
Carlo Bertollib4adf552016-01-15 18:50:31 +000012694OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12695 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12696 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12697 SourceLocation EndLoc) {
12698 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12699 std::string Values;
12700 Values += "'";
12701 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12702 Values += "'";
12703 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12704 << Values << getOpenMPClauseName(OMPC_dist_schedule);
12705 return nullptr;
12706 }
12707 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012708 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012709 if (ChunkSize) {
12710 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12711 !ChunkSize->isInstantiationDependent() &&
12712 !ChunkSize->containsUnexpandedParameterPack()) {
12713 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12714 ExprResult Val =
12715 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12716 if (Val.isInvalid())
12717 return nullptr;
12718
12719 ValExpr = Val.get();
12720
12721 // OpenMP [2.7.1, Restrictions]
12722 // chunk_size must be a loop invariant integer expression with a positive
12723 // value.
12724 llvm::APSInt Result;
12725 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12726 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12727 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12728 << "dist_schedule" << ChunkSize->getSourceRange();
12729 return nullptr;
12730 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012731 } else if (getOpenMPCaptureRegionForClause(
12732 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
12733 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012734 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012735 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000012736 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12737 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12738 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012739 }
12740 }
12741 }
12742
12743 return new (Context)
12744 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000012745 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012746}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012747
12748OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12749 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12750 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12751 SourceLocation KindLoc, SourceLocation EndLoc) {
12752 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000012753 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012754 std::string Value;
12755 SourceLocation Loc;
12756 Value += "'";
12757 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12758 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012759 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012760 Loc = MLoc;
12761 } else {
12762 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012763 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012764 Loc = KindLoc;
12765 }
12766 Value += "'";
12767 Diag(Loc, diag::err_omp_unexpected_clause_value)
12768 << Value << getOpenMPClauseName(OMPC_defaultmap);
12769 return nullptr;
12770 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000012771 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012772
12773 return new (Context)
12774 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12775}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012776
12777bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12778 DeclContext *CurLexicalContext = getCurLexicalContext();
12779 if (!CurLexicalContext->isFileContext() &&
12780 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000012781 !CurLexicalContext->isExternCXXContext() &&
12782 !isa<CXXRecordDecl>(CurLexicalContext) &&
12783 !isa<ClassTemplateDecl>(CurLexicalContext) &&
12784 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12785 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012786 Diag(Loc, diag::err_omp_region_not_file_context);
12787 return false;
12788 }
12789 if (IsInOpenMPDeclareTargetContext) {
12790 Diag(Loc, diag::err_omp_enclosed_declare_target);
12791 return false;
12792 }
12793
12794 IsInOpenMPDeclareTargetContext = true;
12795 return true;
12796}
12797
12798void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12799 assert(IsInOpenMPDeclareTargetContext &&
12800 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12801
12802 IsInOpenMPDeclareTargetContext = false;
12803}
12804
David Majnemer9d168222016-08-05 17:44:54 +000012805void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12806 CXXScopeSpec &ScopeSpec,
12807 const DeclarationNameInfo &Id,
12808 OMPDeclareTargetDeclAttr::MapTypeTy MT,
12809 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012810 LookupResult Lookup(*this, Id, LookupOrdinaryName);
12811 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12812
12813 if (Lookup.isAmbiguous())
12814 return;
12815 Lookup.suppressDiagnostics();
12816
12817 if (!Lookup.isSingleResult()) {
12818 if (TypoCorrection Corrected =
12819 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12820 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12821 CTK_ErrorRecovery)) {
12822 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12823 << Id.getName());
12824 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12825 return;
12826 }
12827
12828 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12829 return;
12830 }
12831
12832 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12833 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12834 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12835 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12836
12837 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12838 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12839 ND->addAttr(A);
12840 if (ASTMutationListener *ML = Context.getASTMutationListener())
12841 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000012842 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012843 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12844 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12845 << Id.getName();
12846 }
12847 } else
12848 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12849}
12850
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012851static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12852 Sema &SemaRef, Decl *D) {
12853 if (!D)
12854 return;
Alexey Bataev8e39c342018-02-16 21:23:23 +000012855 const Decl *LD = nullptr;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012856 if (isa<TagDecl>(D)) {
12857 LD = cast<TagDecl>(D)->getDefinition();
12858 } else if (isa<VarDecl>(D)) {
12859 LD = cast<VarDecl>(D)->getDefinition();
12860
12861 // If this is an implicit variable that is legal and we do not need to do
12862 // anything.
12863 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012864 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12865 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12866 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012867 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012868 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012869 return;
12870 }
Alexey Bataev8e39c342018-02-16 21:23:23 +000012871 } else if (auto *F = dyn_cast<FunctionDecl>(D)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012872 const FunctionDecl *FD = nullptr;
Alexey Bataev8e39c342018-02-16 21:23:23 +000012873 if (cast<FunctionDecl>(D)->hasBody(FD)) {
12874 LD = FD;
12875 // If the definition is associated with the current declaration in the
12876 // target region (it can be e.g. a lambda) that is legal and we do not
12877 // need to do anything else.
12878 if (LD == D) {
12879 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12880 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12881 D->addAttr(A);
12882 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
12883 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
12884 return;
12885 }
12886 } else if (F->isFunctionTemplateSpecialization() &&
12887 F->getTemplateSpecializationKind() ==
12888 TSK_ImplicitInstantiation) {
12889 // Check if the function is implicitly instantiated from the template
12890 // defined in the declare target region.
12891 const FunctionTemplateDecl *FTD = F->getPrimaryTemplate();
12892 if (FTD && FTD->hasAttr<OMPDeclareTargetDeclAttr>())
12893 return;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012894 }
12895 }
12896 if (!LD)
12897 LD = D;
12898 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12899 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12900 // Outlined declaration is not declared target.
12901 if (LD->isOutOfLine()) {
12902 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12903 SemaRef.Diag(SL, diag::note_used_here) << SR;
12904 } else {
Alexey Bataev8e39c342018-02-16 21:23:23 +000012905 const DeclContext *DC = LD->getDeclContext();
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012906 while (DC) {
12907 if (isa<FunctionDecl>(DC) &&
12908 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12909 break;
12910 DC = DC->getParent();
12911 }
12912 if (DC)
12913 return;
12914
12915 // Is not declared in target context.
12916 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12917 SemaRef.Diag(SL, diag::note_used_here) << SR;
12918 }
12919 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012920 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12921 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12922 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012923 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012924 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012925 }
12926}
12927
12928static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12929 Sema &SemaRef, DSAStackTy *Stack,
12930 ValueDecl *VD) {
12931 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12932 return true;
Alexey Bataev95c23e72018-02-27 21:31:11 +000012933 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType(),
12934 /*FullCheck=*/false))
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012935 return false;
12936 return true;
12937}
12938
Kelvin Li1ce87c72017-12-12 20:08:12 +000012939void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
12940 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012941 if (!D || D->isInvalidDecl())
12942 return;
12943 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
12944 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
12945 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
12946 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12947 if (DSAStack->isThreadPrivate(VD)) {
12948 Diag(SL, diag::err_omp_threadprivate_in_target);
12949 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
12950 return;
12951 }
12952 }
12953 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
12954 // Problem if any with var declared with incomplete type will be reported
12955 // as normal, so no need to check it here.
12956 if ((E || !VD->getType()->isIncompleteType()) &&
12957 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
12958 // Mark decl as declared target to prevent further diagnostic.
Alexey Bataev8e39c342018-02-16 21:23:23 +000012959 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD) ||
12960 isa<FunctionTemplateDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012961 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12962 Context, OMPDeclareTargetDeclAttr::MT_To);
12963 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012964 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012965 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012966 }
12967 return;
12968 }
12969 }
Kelvin Li1ce87c72017-12-12 20:08:12 +000012970 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12971 if (FD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12972 (FD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
12973 OMPDeclareTargetDeclAttr::MT_Link)) {
12974 assert(IdLoc.isValid() && "Source location is expected");
12975 Diag(IdLoc, diag::err_omp_function_in_link_clause);
12976 Diag(FD->getLocation(), diag::note_defined_here) << FD;
12977 return;
12978 }
12979 }
Alexey Bataev8e39c342018-02-16 21:23:23 +000012980 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D)) {
12981 if (FTD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12982 (FTD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
12983 OMPDeclareTargetDeclAttr::MT_Link)) {
12984 assert(IdLoc.isValid() && "Source location is expected");
12985 Diag(IdLoc, diag::err_omp_function_in_link_clause);
12986 Diag(FTD->getLocation(), diag::note_defined_here) << FTD;
12987 return;
12988 }
12989 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012990 if (!E) {
12991 // Checking declaration inside declare target region.
12992 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
Alexey Bataev8e39c342018-02-16 21:23:23 +000012993 (isa<VarDecl>(D) || isa<FunctionDecl>(D) ||
12994 isa<FunctionTemplateDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012995 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12996 Context, OMPDeclareTargetDeclAttr::MT_To);
12997 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012998 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012999 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000013000 }
13001 return;
13002 }
13003 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
13004}
Samuel Antao661c0902016-05-26 17:39:58 +000013005
13006OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
13007 SourceLocation StartLoc,
13008 SourceLocation LParenLoc,
13009 SourceLocation EndLoc) {
13010 MappableVarListInfo MVLI(VarList);
13011 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
13012 if (MVLI.ProcessedVarList.empty())
13013 return nullptr;
13014
13015 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13016 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13017 MVLI.VarComponents);
13018}
Samuel Antaoec172c62016-05-26 17:49:04 +000013019
13020OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
13021 SourceLocation StartLoc,
13022 SourceLocation LParenLoc,
13023 SourceLocation EndLoc) {
13024 MappableVarListInfo MVLI(VarList);
13025 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
13026 if (MVLI.ProcessedVarList.empty())
13027 return nullptr;
13028
13029 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
13030 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
13031 MVLI.VarComponents);
13032}
Carlo Bertolli2404b172016-07-13 15:37:16 +000013033
13034OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
13035 SourceLocation StartLoc,
13036 SourceLocation LParenLoc,
13037 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000013038 MappableVarListInfo MVLI(VarList);
13039 SmallVector<Expr *, 8> PrivateCopies;
13040 SmallVector<Expr *, 8> Inits;
13041
Carlo Bertolli2404b172016-07-13 15:37:16 +000013042 for (auto &RefExpr : VarList) {
13043 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
13044 SourceLocation ELoc;
13045 SourceRange ERange;
13046 Expr *SimpleRefExpr = RefExpr;
13047 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13048 if (Res.second) {
13049 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000013050 MVLI.ProcessedVarList.push_back(RefExpr);
13051 PrivateCopies.push_back(nullptr);
13052 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000013053 }
13054 ValueDecl *D = Res.first;
13055 if (!D)
13056 continue;
13057
13058 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000013059 Type = Type.getNonReferenceType().getUnqualifiedType();
13060
13061 auto *VD = dyn_cast<VarDecl>(D);
13062
13063 // Item should be a pointer or reference to pointer.
13064 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000013065 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
13066 << 0 << RefExpr->getSourceRange();
13067 continue;
13068 }
Samuel Antaocc10b852016-07-28 14:23:26 +000013069
13070 // Build the private variable and the expression that refers to it.
13071 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
13072 D->hasAttrs() ? &D->getAttrs() : nullptr);
13073 if (VDPrivate->isInvalidDecl())
13074 continue;
13075
13076 CurContext->addDecl(VDPrivate);
13077 auto VDPrivateRefExpr = buildDeclRefExpr(
13078 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
13079
13080 // Add temporary variable to initialize the private copy of the pointer.
13081 auto *VDInit =
13082 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
13083 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
13084 RefExpr->getExprLoc());
13085 AddInitializerToDecl(VDPrivate,
13086 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000013087 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000013088
13089 // If required, build a capture to implement the privatization initialized
13090 // with the current list item value.
13091 DeclRefExpr *Ref = nullptr;
13092 if (!VD)
13093 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
13094 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
13095 PrivateCopies.push_back(VDPrivateRefExpr);
13096 Inits.push_back(VDInitRefExpr);
13097
13098 // We need to add a data sharing attribute for this variable to make sure it
13099 // is correctly captured. A variable that shows up in a use_device_ptr has
13100 // similar properties of a first private variable.
13101 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
13102
13103 // Create a mappable component for the list item. List items in this clause
13104 // only need a component.
13105 MVLI.VarBaseDeclarations.push_back(D);
13106 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13107 MVLI.VarComponents.back().push_back(
13108 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000013109 }
13110
Samuel Antaocc10b852016-07-28 14:23:26 +000013111 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000013112 return nullptr;
13113
Samuel Antaocc10b852016-07-28 14:23:26 +000013114 return OMPUseDevicePtrClause::Create(
13115 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13116 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000013117}
Carlo Bertolli70594e92016-07-13 17:16:49 +000013118
13119OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
13120 SourceLocation StartLoc,
13121 SourceLocation LParenLoc,
13122 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000013123 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013124 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000013125 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000013126 SourceLocation ELoc;
13127 SourceRange ERange;
13128 Expr *SimpleRefExpr = RefExpr;
13129 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13130 if (Res.second) {
13131 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000013132 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013133 }
13134 ValueDecl *D = Res.first;
13135 if (!D)
13136 continue;
13137
13138 QualType Type = D->getType();
13139 // item should be a pointer or array or reference to pointer or array
13140 if (!Type.getNonReferenceType()->isPointerType() &&
13141 !Type.getNonReferenceType()->isArrayType()) {
13142 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
13143 << 0 << RefExpr->getSourceRange();
13144 continue;
13145 }
Samuel Antao6890b092016-07-28 14:25:09 +000013146
13147 // Check if the declaration in the clause does not show up in any data
13148 // sharing attribute.
13149 auto DVar = DSAStack->getTopDSA(D, false);
13150 if (isOpenMPPrivate(DVar.CKind)) {
13151 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13152 << getOpenMPClauseName(DVar.CKind)
13153 << getOpenMPClauseName(OMPC_is_device_ptr)
13154 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13155 ReportOriginalDSA(*this, DSAStack, D, DVar);
13156 continue;
13157 }
13158
13159 Expr *ConflictExpr;
13160 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000013161 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000013162 [&ConflictExpr](
13163 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
13164 OpenMPClauseKind) -> bool {
13165 ConflictExpr = R.front().getAssociatedExpression();
13166 return true;
13167 })) {
13168 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
13169 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
13170 << ConflictExpr->getSourceRange();
13171 continue;
13172 }
13173
13174 // Store the components in the stack so that they can be used to check
13175 // against other clauses later on.
13176 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
13177 DSAStack->addMappableExpressionComponents(
13178 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
13179
13180 // Record the expression we've just processed.
13181 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
13182
13183 // Create a mappable component for the list item. List items in this clause
13184 // only need a component. We use a null declaration to signal fields in
13185 // 'this'.
13186 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
13187 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
13188 "Unexpected device pointer expression!");
13189 MVLI.VarBaseDeclarations.push_back(
13190 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
13191 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13192 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013193 }
13194
Samuel Antao6890b092016-07-28 14:25:09 +000013195 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000013196 return nullptr;
13197
Samuel Antao6890b092016-07-28 14:25:09 +000013198 return OMPIsDevicePtrClause::Create(
13199 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13200 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013201}