blob: d0298540bae3850d9199053e83a9992bb9008d4c [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 Bataev4b465392017-04-26 15:06:24 +0000939 if (!isStackEmpty() && Stack.back().first.size() > 1) {
940 reverse_iterator I = Iter, E = Stack.back().first.rend();
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000941 Scope *TopScope = nullptr;
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000942 while (I != E && !isParallelOrTaskRegion(I->Directive))
Alexey Bataevec3da872014-01-31 05:15:34 +0000943 ++I;
Alexey Bataeved09d242014-05-28 05:53:51 +0000944 if (I == E)
945 return false;
Alexander Musmancb7f9c42014-05-15 13:04:49 +0000946 TopScope = I->CurScope ? I->CurScope->getParent() : nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +0000947 Scope *CurScope = getCurScope();
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000948 while (CurScope != TopScope && !CurScope->isDeclScope(D))
Alexey Bataev758e55e2013-09-06 18:03:48 +0000949 CurScope = CurScope->getParent();
Alexey Bataevec3da872014-01-31 05:15:34 +0000950 return CurScope != TopScope;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000951 }
Alexey Bataevec3da872014-01-31 05:15:34 +0000952 return false;
Alexey Bataev758e55e2013-09-06 18:03:48 +0000953}
954
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000955DSAStackTy::DSAVarData DSAStackTy::getTopDSA(ValueDecl *D, bool FromParent) {
956 D = getCanonicalDecl(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000957 DSAVarData DVar;
958
959 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
960 // in a Construct, C/C++, predetermined, p.1]
961 // Variables appearing in threadprivate directives are threadprivate.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000962 auto *VD = dyn_cast<VarDecl>(D);
963 if ((VD && VD->getTLSKind() != VarDecl::TLS_None &&
964 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
Samuel Antaof8b50122015-07-13 22:54:53 +0000965 SemaRef.getLangOpts().OpenMPUseTLS &&
966 SemaRef.getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000967 (VD && VD->getStorageClass() == SC_Register &&
968 VD->hasAttr<AsmLabelAttr>() && !VD->isLocalVarDecl())) {
969 addDSA(D, buildDeclRefExpr(SemaRef, VD, D->getType().getNonReferenceType(),
Alexey Bataev39f915b82015-05-08 10:41:21 +0000970 D->getLocation()),
Alexey Bataevf2453a02015-05-06 07:25:08 +0000971 OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000972 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +0000973 auto TI = Threadprivates.find(D);
974 if (TI != Threadprivates.end()) {
975 DVar.RefExpr = TI->getSecond().RefExpr.getPointer();
Alexey Bataev758e55e2013-09-06 18:03:48 +0000976 DVar.CKind = OMPC_threadprivate;
977 return DVar;
Alexey Bataev817d7f32017-11-14 21:01:01 +0000978 } else if (VD && VD->hasAttr<OMPThreadPrivateDeclAttr>()) {
979 DVar.RefExpr = buildDeclRefExpr(
980 SemaRef, VD, D->getType().getNonReferenceType(),
981 VD->getAttr<OMPThreadPrivateDeclAttr>()->getLocation());
982 DVar.CKind = OMPC_threadprivate;
983 addDSA(D, DVar.RefExpr, OMPC_threadprivate);
Alexey Bataev758e55e2013-09-06 18:03:48 +0000984 }
985
Alexey Bataev4b465392017-04-26 15:06:24 +0000986 if (isStackEmpty())
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000987 // Not in OpenMP execution region and top scope was already checked.
988 return DVar;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +0000989
Alexey Bataev758e55e2013-09-06 18:03:48 +0000990 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
Alexey Bataevdffa93a2015-12-10 08:20:58 +0000991 // in a Construct, C/C++, predetermined, p.4]
992 // Static data members are shared.
993 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
994 // in a Construct, C/C++, predetermined, p.7]
995 // Variables with static storage duration that are declared in a scope
996 // inside the construct are shared.
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000997 auto &&MatchesAlways = [](OpenMPDirectiveKind) -> bool { return true; };
Alexey Bataev48c0bfb2016-01-20 09:07:54 +0000998 if (VD && VD->isStaticDataMember()) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +0000999 DSAVarData DVarTemp = hasDSA(D, isOpenMPPrivate, MatchesAlways, FromParent);
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001000 if (DVarTemp.CKind != OMPC_unknown && DVarTemp.RefExpr)
Alexey Bataevec3da872014-01-31 05:15:34 +00001001 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001002
Alexey Bataevdffa93a2015-12-10 08:20:58 +00001003 DVar.CKind = OMPC_shared;
1004 return DVar;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001005 }
1006
1007 QualType Type = D->getType().getNonReferenceType().getCanonicalType();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00001008 bool IsConstant = Type.isConstant(SemaRef.getASTContext());
1009 Type = SemaRef.getASTContext().getBaseElementType(Type);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001010 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
1011 // in a Construct, C/C++, predetermined, p.6]
1012 // Variables with const qualified type having no mutable member are
1013 // shared.
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001014 CXXRecordDecl *RD =
Alexey Bataev7ff55242014-06-19 09:13:45 +00001015 SemaRef.getLangOpts().CPlusPlus ? Type->getAsCXXRecordDecl() : nullptr;
Alexey Bataevc9bd03d2015-12-17 06:55:08 +00001016 if (auto *CTSD = dyn_cast_or_null<ClassTemplateSpecializationDecl>(RD))
1017 if (auto *CTD = CTSD->getSpecializedTemplate())
1018 RD = CTD->getTemplatedDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001019 if (IsConstant &&
Alexey Bataev4bcad7f2016-02-10 10:50:12 +00001020 !(SemaRef.getLangOpts().CPlusPlus && RD && RD->hasDefinition() &&
1021 RD->hasMutableFields())) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00001022 // Variables with const-qualified type having no mutable member may be
1023 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001024 DSAVarData DVarTemp = hasDSA(
1025 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_firstprivate; },
1026 MatchesAlways, FromParent);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001027 if (DVarTemp.CKind == OMPC_firstprivate && DVarTemp.RefExpr)
1028 return DVar;
1029
Alexey Bataev758e55e2013-09-06 18:03:48 +00001030 DVar.CKind = OMPC_shared;
1031 return DVar;
1032 }
1033
Alexey Bataev758e55e2013-09-06 18:03:48 +00001034 // Explicitly specified attributes and local variables with predetermined
1035 // attributes.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001036 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001037 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001038 if (FromParent && I != EndI)
1039 std::advance(I, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001040 if (I->SharingMap.count(D)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001041 DVar.RefExpr = I->SharingMap[D].RefExpr.getPointer();
Alexey Bataev90c228f2016-02-08 09:29:13 +00001042 DVar.PrivateCopy = I->SharingMap[D].PrivateCopy;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001043 DVar.CKind = I->SharingMap[D].Attributes;
1044 DVar.ImplicitDSALoc = I->DefaultAttrLoc;
Alexey Bataev4d4624c2017-07-20 16:47:47 +00001045 DVar.DKind = I->Directive;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001046 }
1047
1048 return DVar;
1049}
1050
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001051DSAStackTy::DSAVarData DSAStackTy::getImplicitDSA(ValueDecl *D,
1052 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001053 if (isStackEmpty()) {
1054 StackTy::reverse_iterator I;
1055 return getDSA(I, D);
1056 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001057 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001058 auto StartI = Stack.back().first.rbegin();
1059 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001060 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001061 std::advance(StartI, 1);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001062 return getDSA(StartI, D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001063}
1064
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001065DSAStackTy::DSAVarData
1066DSAStackTy::hasDSA(ValueDecl *D,
1067 const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1068 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1069 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001070 if (isStackEmpty())
1071 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001072 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001073 auto I = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001074 auto EndI = Stack.back().first.rend();
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001075 if (FromParent && I != EndI)
Alexey Bataev0e6fc1c2017-04-27 14:46:26 +00001076 std::advance(I, 1);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001077 for (; I != EndI; std::advance(I, 1)) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001078 if (!DPred(I->Directive) && !isParallelOrTaskRegion(I->Directive))
Alexey Bataeved09d242014-05-28 05:53:51 +00001079 continue;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001080 auto NewI = I;
1081 DSAVarData DVar = getDSA(NewI, D);
1082 if (I == NewI && CPred(DVar.CKind))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001083 return DVar;
Alexey Bataev60859c02017-04-27 15:10:33 +00001084 }
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001085 return {};
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001086}
1087
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001088DSAStackTy::DSAVarData DSAStackTy::hasInnermostDSA(
1089 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
1090 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1091 bool FromParent) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001092 if (isStackEmpty())
1093 return {};
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001094 D = getCanonicalDecl(D);
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001095 auto StartI = Stack.back().first.rbegin();
Alexey Bataev4b465392017-04-26 15:06:24 +00001096 auto EndI = Stack.back().first.rend();
Alexey Bataeve3978122016-07-19 05:06:39 +00001097 if (FromParent && StartI != EndI)
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001098 std::advance(StartI, 1);
Alexey Bataeve3978122016-07-19 05:06:39 +00001099 if (StartI == EndI || !DPred(StartI->Directive))
Alexey Bataev4b465392017-04-26 15:06:24 +00001100 return {};
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001101 auto NewI = StartI;
1102 DSAVarData DVar = getDSA(NewI, D);
1103 return (NewI == StartI && CPred(DVar.CKind)) ? DVar : DSAVarData();
Alexey Bataevc5e02582014-06-16 07:08:35 +00001104}
1105
Alexey Bataevaac108a2015-06-23 04:51:00 +00001106bool DSAStackTy::hasExplicitDSA(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001107 ValueDecl *D, const llvm::function_ref<bool(OpenMPClauseKind)> &CPred,
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001108 unsigned Level, bool NotLastprivate) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001109 if (isStackEmpty())
1110 return false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001111 D = getCanonicalDecl(D);
Alexey Bataev4b465392017-04-26 15:06:24 +00001112 auto StartI = Stack.back().first.begin();
1113 auto EndI = Stack.back().first.end();
NAKAMURA Takumi0332eda2015-06-23 10:01:20 +00001114 if (std::distance(StartI, EndI) <= (int)Level)
Alexey Bataevaac108a2015-06-23 04:51:00 +00001115 return false;
1116 std::advance(StartI, Level);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001117 return (StartI->SharingMap.count(D) > 0) &&
1118 StartI->SharingMap[D].RefExpr.getPointer() &&
1119 CPred(StartI->SharingMap[D].Attributes) &&
1120 (!NotLastprivate || !StartI->SharingMap[D].RefExpr.getInt());
Alexey Bataevaac108a2015-06-23 04:51:00 +00001121}
1122
Samuel Antao4be30e92015-10-02 17:14:03 +00001123bool DSAStackTy::hasExplicitDirective(
1124 const llvm::function_ref<bool(OpenMPDirectiveKind)> &DPred,
1125 unsigned Level) {
Alexey Bataev4b465392017-04-26 15:06:24 +00001126 if (isStackEmpty())
1127 return false;
1128 auto StartI = Stack.back().first.begin();
1129 auto EndI = Stack.back().first.end();
Samuel Antao4be30e92015-10-02 17:14:03 +00001130 if (std::distance(StartI, EndI) <= (int)Level)
1131 return false;
1132 std::advance(StartI, Level);
1133 return DPred(StartI->Directive);
1134}
1135
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001136bool DSAStackTy::hasDirective(
1137 const llvm::function_ref<bool(OpenMPDirectiveKind,
1138 const DeclarationNameInfo &, SourceLocation)>
1139 &DPred,
1140 bool FromParent) {
Samuel Antaof0d79752016-05-27 15:21:27 +00001141 // We look only in the enclosing region.
Alexey Bataev4b465392017-04-26 15:06:24 +00001142 if (isStackEmpty())
Samuel Antaof0d79752016-05-27 15:21:27 +00001143 return false;
Alexey Bataev4b465392017-04-26 15:06:24 +00001144 auto StartI = std::next(Stack.back().first.rbegin());
1145 auto EndI = Stack.back().first.rend();
Alexey Bataevccaddfb2017-04-26 14:24:21 +00001146 if (FromParent && StartI != EndI)
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001147 StartI = std::next(StartI);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00001148 for (auto I = StartI, EE = EndI; I != EE; ++I) {
1149 if (DPred(I->Directive, I->DirectiveName, I->ConstructLoc))
1150 return true;
1151 }
1152 return false;
1153}
1154
Alexey Bataev758e55e2013-09-06 18:03:48 +00001155void Sema::InitDataSharingAttributesStack() {
1156 VarDataSharingAttributesStack = new DSAStackTy(*this);
1157}
1158
1159#define DSAStack static_cast<DSAStackTy *>(VarDataSharingAttributesStack)
1160
Alexey Bataev4b465392017-04-26 15:06:24 +00001161void Sema::pushOpenMPFunctionRegion() {
1162 DSAStack->pushFunction();
1163}
1164
1165void Sema::popOpenMPFunctionRegion(const FunctionScopeInfo *OldFSI) {
1166 DSAStack->popFunction(OldFSI);
1167}
1168
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001169bool Sema::IsOpenMPCapturedByRef(ValueDecl *D, unsigned Level) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001170 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1171
1172 auto &Ctx = getASTContext();
1173 bool IsByRef = true;
1174
1175 // Find the directive that is associated with the provided scope.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001176 D = cast<ValueDecl>(D->getCanonicalDecl());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001177 auto Ty = D->getType();
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001178
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001179 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective, Level)) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001180 // This table summarizes how a given variable should be passed to the device
1181 // given its type and the clauses where it appears. This table is based on
1182 // the description in OpenMP 4.5 [2.10.4, target Construct] and
1183 // OpenMP 4.5 [2.15.5, Data-mapping Attribute Rules and Clauses].
1184 //
1185 // =========================================================================
1186 // | type | defaultmap | pvt | first | is_device_ptr | map | res. |
1187 // | |(tofrom:scalar)| | pvt | | | |
1188 // =========================================================================
1189 // | scl | | | | - | | bycopy|
1190 // | scl | | - | x | - | - | bycopy|
1191 // | scl | | x | - | - | - | null |
1192 // | scl | x | | | - | | byref |
1193 // | scl | x | - | x | - | - | bycopy|
1194 // | scl | x | x | - | - | - | null |
1195 // | scl | | - | - | - | x | byref |
1196 // | scl | x | - | - | - | x | byref |
1197 //
1198 // | agg | n.a. | | | - | | byref |
1199 // | agg | n.a. | - | x | - | - | byref |
1200 // | agg | n.a. | x | - | - | - | null |
1201 // | agg | n.a. | - | - | - | x | byref |
1202 // | agg | n.a. | - | - | - | x[] | byref |
1203 //
1204 // | ptr | n.a. | | | - | | bycopy|
1205 // | ptr | n.a. | - | x | - | - | bycopy|
1206 // | ptr | n.a. | x | - | - | - | null |
1207 // | ptr | n.a. | - | - | - | x | byref |
1208 // | ptr | n.a. | - | - | - | x[] | bycopy|
1209 // | ptr | n.a. | - | - | x | | bycopy|
1210 // | ptr | n.a. | - | - | x | x | bycopy|
1211 // | ptr | n.a. | - | - | x | x[] | bycopy|
1212 // =========================================================================
1213 // Legend:
1214 // scl - scalar
1215 // ptr - pointer
1216 // agg - aggregate
1217 // x - applies
1218 // - - invalid in this combination
1219 // [] - mapped with an array section
1220 // byref - should be mapped by reference
1221 // byval - should be mapped by value
1222 // null - initialize a local variable to null on the device
1223 //
1224 // Observations:
1225 // - All scalar declarations that show up in a map clause have to be passed
1226 // by reference, because they may have been mapped in the enclosing data
1227 // environment.
1228 // - If the scalar value does not fit the size of uintptr, it has to be
1229 // passed by reference, regardless the result in the table above.
1230 // - For pointers mapped by value that have either an implicit map or an
1231 // array section, the runtime library may pass the NULL value to the
1232 // device instead of the value passed to it by the compiler.
1233
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001234 if (Ty->isReferenceType())
1235 Ty = Ty->castAs<ReferenceType>()->getPointeeType();
Samuel Antao86ace552016-04-27 22:40:57 +00001236
1237 // Locate map clauses and see if the variable being captured is referred to
1238 // in any of those clauses. Here we only care about variables, not fields,
1239 // because fields are part of aggregates.
1240 bool IsVariableUsedInMapClause = false;
1241 bool IsVariableAssociatedWithSection = false;
1242
Jonas Hahnfeldf7c4d7b2017-07-01 10:40:50 +00001243 DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1244 D, Level, [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +00001245 MapExprComponents,
1246 OpenMPClauseKind WhereFoundClauseKind) {
1247 // Only the map clause information influences how a variable is
1248 // captured. E.g. is_device_ptr does not require changing the default
Samuel Antao4c8035b2016-12-12 18:00:20 +00001249 // behavior.
Samuel Antao6890b092016-07-28 14:25:09 +00001250 if (WhereFoundClauseKind != OMPC_map)
1251 return false;
Samuel Antao86ace552016-04-27 22:40:57 +00001252
1253 auto EI = MapExprComponents.rbegin();
1254 auto EE = MapExprComponents.rend();
1255
1256 assert(EI != EE && "Invalid map expression!");
1257
1258 if (isa<DeclRefExpr>(EI->getAssociatedExpression()))
1259 IsVariableUsedInMapClause |= EI->getAssociatedDeclaration() == D;
1260
1261 ++EI;
1262 if (EI == EE)
1263 return false;
1264
1265 if (isa<ArraySubscriptExpr>(EI->getAssociatedExpression()) ||
1266 isa<OMPArraySectionExpr>(EI->getAssociatedExpression()) ||
1267 isa<MemberExpr>(EI->getAssociatedExpression())) {
1268 IsVariableAssociatedWithSection = true;
1269 // There is nothing more we need to know about this variable.
1270 return true;
1271 }
1272
1273 // Keep looking for more map info.
1274 return false;
1275 });
1276
1277 if (IsVariableUsedInMapClause) {
1278 // If variable is identified in a map clause it is always captured by
1279 // reference except if it is a pointer that is dereferenced somehow.
1280 IsByRef = !(Ty->isPointerType() && IsVariableAssociatedWithSection);
1281 } else {
Alexey Bataev3f96fe62017-12-13 17:31:39 +00001282 // By default, all the data that has a scalar type is mapped by copy
1283 // (except for reduction variables).
1284 IsByRef =
1285 !Ty->isScalarType() ||
1286 DSAStack->getDefaultDMAAtLevel(Level) == DMA_tofrom_scalar ||
1287 DSAStack->hasExplicitDSA(
1288 D, [](OpenMPClauseKind K) { return K == OMPC_reduction; }, Level);
Samuel Antao86ace552016-04-27 22:40:57 +00001289 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001290 }
1291
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001292 if (IsByRef && Ty.getNonReferenceType()->isScalarType()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00001293 IsByRef =
1294 !DSAStack->hasExplicitDSA(
1295 D,
1296 [](OpenMPClauseKind K) -> bool { return K == OMPC_firstprivate; },
1297 Level, /*NotLastprivate=*/true) &&
1298 // If the variable is artificial and must be captured by value - try to
1299 // capture by value.
Alexey Bataevd2202ca2017-12-27 17:58:32 +00001300 !(isa<OMPCapturedExprDecl>(D) && !D->hasAttr<OMPCaptureNoInitAttr>() &&
1301 !cast<OMPCapturedExprDecl>(D)->getInit()->isGLValue());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001302 }
1303
Samuel Antao86ace552016-04-27 22:40:57 +00001304 // When passing data by copy, we need to make sure it fits the uintptr size
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001305 // and alignment, because the runtime library only deals with uintptr types.
1306 // If it does not fit the uintptr size, we need to pass the data by reference
1307 // instead.
1308 if (!IsByRef &&
1309 (Ctx.getTypeSizeInChars(Ty) >
1310 Ctx.getTypeSizeInChars(Ctx.getUIntPtrType()) ||
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001311 Ctx.getDeclAlign(D) > Ctx.getTypeAlignInChars(Ctx.getUIntPtrType()))) {
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001312 IsByRef = true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001313 }
Samuel Antao4af1b7b2015-12-02 17:44:43 +00001314
1315 return IsByRef;
1316}
1317
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001318unsigned Sema::getOpenMPNestingLevel() const {
1319 assert(getLangOpts().OpenMP);
1320 return DSAStack->getNestingLevel();
1321}
1322
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001323bool Sema::isInOpenMPTargetExecutionDirective() const {
1324 return (isOpenMPTargetExecutionDirective(DSAStack->getCurrentDirective()) &&
1325 !DSAStack->isClauseParsingMode()) ||
1326 DSAStack->hasDirective(
1327 [](OpenMPDirectiveKind K, const DeclarationNameInfo &,
1328 SourceLocation) -> bool {
1329 return isOpenMPTargetExecutionDirective(K);
1330 },
1331 false);
1332}
1333
Alexey Bataev90c228f2016-02-08 09:29:13 +00001334VarDecl *Sema::IsOpenMPCapturedDecl(ValueDecl *D) {
Alexey Bataevf841bd92014-12-16 07:00:22 +00001335 assert(LangOpts.OpenMP && "OpenMP is not allowed");
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001336 D = getCanonicalDecl(D);
Samuel Antao4be30e92015-10-02 17:14:03 +00001337
1338 // If we are attempting to capture a global variable in a directive with
1339 // 'target' we return true so that this global is also mapped to the device.
1340 //
1341 // FIXME: If the declaration is enclosed in a 'declare target' directive,
1342 // then it should not be captured. Therefore, an extra check has to be
1343 // inserted here once support for 'declare target' is added.
1344 //
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001345 auto *VD = dyn_cast<VarDecl>(D);
Jonas Hahnfeld87d44262017-11-18 21:00:46 +00001346 if (VD && !VD->hasLocalStorage() && isInOpenMPTargetExecutionDirective())
1347 return VD;
Samuel Antao4be30e92015-10-02 17:14:03 +00001348
Alexey Bataev48977c32015-08-04 08:10:48 +00001349 if (DSAStack->getCurrentDirective() != OMPD_unknown &&
1350 (!DSAStack->isClauseParsingMode() ||
1351 DSAStack->getParentDirective() != OMPD_unknown)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001352 auto &&Info = DSAStack->isLoopControlVariable(D);
1353 if (Info.first ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001354 (VD && VD->hasLocalStorage() &&
Samuel Antao9c75cfe2015-07-27 16:38:06 +00001355 isParallelOrTaskRegion(DSAStack->getCurrentDirective())) ||
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001356 (VD && DSAStack->isForceVarCapturing()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00001357 return VD ? VD : Info.second;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001358 auto DVarPrivate = DSAStack->getTopDSA(D, DSAStack->isClauseParsingMode());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001359 if (DVarPrivate.CKind != OMPC_unknown && isOpenMPPrivate(DVarPrivate.CKind))
Alexey Bataev90c228f2016-02-08 09:29:13 +00001360 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001361 DVarPrivate = DSAStack->hasDSA(
1362 D, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
1363 DSAStack->isClauseParsingMode());
Alexey Bataev90c228f2016-02-08 09:29:13 +00001364 if (DVarPrivate.CKind != OMPC_unknown)
1365 return VD ? VD : cast<VarDecl>(DVarPrivate.PrivateCopy->getDecl());
Alexey Bataevf841bd92014-12-16 07:00:22 +00001366 }
Alexey Bataev90c228f2016-02-08 09:29:13 +00001367 return nullptr;
Alexey Bataevf841bd92014-12-16 07:00:22 +00001368}
1369
Alexey Bataevdfa430f2017-12-08 15:03:50 +00001370void Sema::adjustOpenMPTargetScopeIndex(unsigned &FunctionScopesIndex,
1371 unsigned Level) const {
1372 SmallVector<OpenMPDirectiveKind, 4> Regions;
1373 getOpenMPCaptureRegions(Regions, DSAStack->getDirective(Level));
1374 FunctionScopesIndex -= Regions.size();
1375}
1376
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001377bool Sema::isOpenMPPrivateDecl(ValueDecl *D, unsigned Level) {
Alexey Bataevaac108a2015-06-23 04:51:00 +00001378 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1379 return DSAStack->hasExplicitDSA(
Alexey Bataev88202be2017-07-27 13:20:36 +00001380 D, [](OpenMPClauseKind K) -> bool { return K == OMPC_private; },
1381 Level) ||
Alexey Bataev3f82cfc2017-12-13 15:28:44 +00001382 (DSAStack->isClauseParsingMode() &&
1383 DSAStack->getClauseParsingMode() == OMPC_private) ||
Alexey Bataev88202be2017-07-27 13:20:36 +00001384 // Consider taskgroup reduction descriptor variable a private to avoid
1385 // possible capture in the region.
1386 (DSAStack->hasExplicitDirective(
1387 [](OpenMPDirectiveKind K) { return K == OMPD_taskgroup; },
1388 Level) &&
1389 DSAStack->isTaskgroupReductionRef(D, Level));
Alexey Bataevaac108a2015-06-23 04:51:00 +00001390}
1391
Alexey Bataev3b8d5582017-08-08 18:04:06 +00001392void Sema::setOpenMPCaptureKind(FieldDecl *FD, ValueDecl *D, unsigned Level) {
1393 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1394 D = getCanonicalDecl(D);
1395 OpenMPClauseKind OMPC = OMPC_unknown;
1396 for (unsigned I = DSAStack->getNestingLevel() + 1; I > Level; --I) {
1397 const unsigned NewLevel = I - 1;
1398 if (DSAStack->hasExplicitDSA(D,
1399 [&OMPC](const OpenMPClauseKind K) {
1400 if (isOpenMPPrivate(K)) {
1401 OMPC = K;
1402 return true;
1403 }
1404 return false;
1405 },
1406 NewLevel))
1407 break;
1408 if (DSAStack->checkMappableExprComponentListsForDeclAtLevel(
1409 D, NewLevel,
1410 [](OMPClauseMappableExprCommon::MappableExprComponentListRef,
1411 OpenMPClauseKind) { return true; })) {
1412 OMPC = OMPC_map;
1413 break;
1414 }
1415 if (DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1416 NewLevel)) {
1417 OMPC = OMPC_firstprivate;
1418 break;
1419 }
1420 }
1421 if (OMPC != OMPC_unknown)
1422 FD->addAttr(OMPCaptureKindAttr::CreateImplicit(Context, OMPC));
1423}
1424
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001425bool Sema::isOpenMPTargetCapturedDecl(ValueDecl *D, unsigned Level) {
Samuel Antao4be30e92015-10-02 17:14:03 +00001426 assert(LangOpts.OpenMP && "OpenMP is not allowed");
1427 // Return true if the current level is no longer enclosed in a target region.
1428
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001429 auto *VD = dyn_cast<VarDecl>(D);
1430 return VD && !VD->hasLocalStorage() &&
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00001431 DSAStack->hasExplicitDirective(isOpenMPTargetExecutionDirective,
1432 Level);
Samuel Antao4be30e92015-10-02 17:14:03 +00001433}
1434
Alexey Bataeved09d242014-05-28 05:53:51 +00001435void Sema::DestroyDataSharingAttributesStack() { delete DSAStack; }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001436
1437void Sema::StartOpenMPDSABlock(OpenMPDirectiveKind DKind,
1438 const DeclarationNameInfo &DirName,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001439 Scope *CurScope, SourceLocation Loc) {
1440 DSAStack->push(DKind, DirName, CurScope, Loc);
Faisal Valid143a0c2017-04-01 21:30:49 +00001441 PushExpressionEvaluationContext(
1442 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001443}
1444
Alexey Bataevaac108a2015-06-23 04:51:00 +00001445void Sema::StartOpenMPClause(OpenMPClauseKind K) {
1446 DSAStack->setClauseParsingMode(K);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001447}
1448
Alexey Bataevaac108a2015-06-23 04:51:00 +00001449void Sema::EndOpenMPClause() {
1450 DSAStack->setClauseParsingMode(/*K=*/OMPC_unknown);
Alexey Bataev39f915b82015-05-08 10:41:21 +00001451}
1452
Alexey Bataev758e55e2013-09-06 18:03:48 +00001453void Sema::EndOpenMPDSABlock(Stmt *CurDirective) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00001454 // OpenMP [2.14.3.5, Restrictions, C/C++, p.1]
1455 // A variable of class type (or array thereof) that appears in a lastprivate
1456 // clause requires an accessible, unambiguous default constructor for the
1457 // class type, unless the list item is also specified in a firstprivate
1458 // clause.
David Majnemer9d168222016-08-05 17:44:54 +00001459 if (auto *D = dyn_cast_or_null<OMPExecutableDirective>(CurDirective)) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001460 for (auto *C : D->clauses()) {
1461 if (auto *Clause = dyn_cast<OMPLastprivateClause>(C)) {
1462 SmallVector<Expr *, 8> PrivateCopies;
1463 for (auto *DE : Clause->varlists()) {
1464 if (DE->isValueDependent() || DE->isTypeDependent()) {
1465 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001466 continue;
Alexey Bataev38e89532015-04-16 04:54:05 +00001467 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00001468 auto *DRE = cast<DeclRefExpr>(DE->IgnoreParens());
Alexey Bataev005248a2016-02-25 05:25:57 +00001469 VarDecl *VD = cast<VarDecl>(DRE->getDecl());
1470 QualType Type = VD->getType().getNonReferenceType();
1471 auto DVar = DSAStack->getTopDSA(VD, false);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001472 if (DVar.CKind == OMPC_lastprivate) {
Alexey Bataev38e89532015-04-16 04:54:05 +00001473 // Generate helper private variable and initialize it with the
1474 // default value. The address of the original variable is replaced
1475 // by the address of the new private variable in CodeGen. This new
1476 // variable is not added to IdResolver, so the code in the OpenMP
1477 // region uses original variable for proper diagnostics.
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00001478 auto *VDPrivate = buildVarDecl(
1479 *this, DE->getExprLoc(), Type.getUnqualifiedType(),
Alexey Bataev005248a2016-02-25 05:25:57 +00001480 VD->getName(), VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00001481 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev38e89532015-04-16 04:54:05 +00001482 if (VDPrivate->isInvalidDecl())
1483 continue;
Alexey Bataev39f915b82015-05-08 10:41:21 +00001484 PrivateCopies.push_back(buildDeclRefExpr(
1485 *this, VDPrivate, DE->getType(), DE->getExprLoc()));
Alexey Bataev38e89532015-04-16 04:54:05 +00001486 } else {
1487 // The variable is also a firstprivate, so initialization sequence
1488 // for private copy is generated already.
1489 PrivateCopies.push_back(nullptr);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001490 }
1491 }
Alexey Bataev38e89532015-04-16 04:54:05 +00001492 // Set initializers to private copies if no errors were found.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001493 if (PrivateCopies.size() == Clause->varlist_size())
Alexey Bataev38e89532015-04-16 04:54:05 +00001494 Clause->setPrivateCopies(PrivateCopies);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001495 }
1496 }
1497 }
1498
Alexey Bataev758e55e2013-09-06 18:03:48 +00001499 DSAStack->pop();
1500 DiscardCleanupsInEvaluationContext();
1501 PopExpressionEvaluationContext();
1502}
1503
Alexey Bataev5dff95c2016-04-22 03:56:56 +00001504static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
1505 Expr *NumIterations, Sema &SemaRef,
1506 Scope *S, DSAStackTy *Stack);
Alexander Musman3276a272015-03-21 10:12:56 +00001507
Alexey Bataeva769e072013-03-22 06:34:35 +00001508namespace {
1509
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001510class VarDeclFilterCCC : public CorrectionCandidateCallback {
1511private:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001512 Sema &SemaRef;
Alexey Bataeved09d242014-05-28 05:53:51 +00001513
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001514public:
Alexey Bataev7ff55242014-06-19 09:13:45 +00001515 explicit VarDeclFilterCCC(Sema &S) : SemaRef(S) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00001516 bool ValidateCandidate(const TypoCorrection &Candidate) override {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001517 NamedDecl *ND = Candidate.getCorrectionDecl();
David Majnemer9d168222016-08-05 17:44:54 +00001518 if (auto *VD = dyn_cast_or_null<VarDecl>(ND)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001519 return VD->hasGlobalStorage() &&
Alexey Bataev7ff55242014-06-19 09:13:45 +00001520 SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1521 SemaRef.getCurScope());
Alexey Bataeva769e072013-03-22 06:34:35 +00001522 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001523 return false;
Alexey Bataeva769e072013-03-22 06:34:35 +00001524 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001525};
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001526
1527class VarOrFuncDeclFilterCCC : public CorrectionCandidateCallback {
1528private:
1529 Sema &SemaRef;
1530
1531public:
1532 explicit VarOrFuncDeclFilterCCC(Sema &S) : SemaRef(S) {}
1533 bool ValidateCandidate(const TypoCorrection &Candidate) override {
1534 NamedDecl *ND = Candidate.getCorrectionDecl();
Kelvin Li59e3d192017-11-30 18:52:06 +00001535 if (ND && (isa<VarDecl>(ND) || isa<FunctionDecl>(ND))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +00001536 return SemaRef.isDeclInScope(ND, SemaRef.getCurLexicalContext(),
1537 SemaRef.getCurScope());
1538 }
1539 return false;
1540 }
1541};
1542
Alexey Bataeved09d242014-05-28 05:53:51 +00001543} // namespace
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001544
1545ExprResult Sema::ActOnOpenMPIdExpression(Scope *CurScope,
1546 CXXScopeSpec &ScopeSpec,
1547 const DeclarationNameInfo &Id) {
1548 LookupResult Lookup(*this, Id, LookupOrdinaryName);
1549 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
1550
1551 if (Lookup.isAmbiguous())
1552 return ExprError();
1553
1554 VarDecl *VD;
1555 if (!Lookup.isSingleResult()) {
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001556 if (TypoCorrection Corrected = CorrectTypo(
1557 Id, LookupOrdinaryName, CurScope, nullptr,
1558 llvm::make_unique<VarDeclFilterCCC>(*this), CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +00001559 diagnoseTypo(Corrected,
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001560 PDiag(Lookup.empty()
1561 ? diag::err_undeclared_var_use_suggest
1562 : diag::err_omp_expected_var_arg_suggest)
1563 << Id.getName());
Richard Smithf9b15102013-08-17 00:46:16 +00001564 VD = Corrected.getCorrectionDeclAs<VarDecl>();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001565 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001566 Diag(Id.getLoc(), Lookup.empty() ? diag::err_undeclared_var_use
1567 : diag::err_omp_expected_var_arg)
1568 << Id.getName();
1569 return ExprError();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001570 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001571 } else {
1572 if (!(VD = Lookup.getAsSingle<VarDecl>())) {
Alexey Bataeved09d242014-05-28 05:53:51 +00001573 Diag(Id.getLoc(), diag::err_omp_expected_var_arg) << Id.getName();
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001574 Diag(Lookup.getFoundDecl()->getLocation(), diag::note_declared_at);
1575 return ExprError();
1576 }
1577 }
1578 Lookup.suppressDiagnostics();
1579
1580 // OpenMP [2.9.2, Syntax, C/C++]
1581 // Variables must be file-scope, namespace-scope, or static block-scope.
1582 if (!VD->hasGlobalStorage()) {
1583 Diag(Id.getLoc(), diag::err_omp_global_var_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001584 << getOpenMPDirectiveName(OMPD_threadprivate) << !VD->isStaticLocal();
1585 bool IsDecl =
1586 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001587 Diag(VD->getLocation(),
Alexey Bataeved09d242014-05-28 05:53:51 +00001588 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1589 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001590 return ExprError();
1591 }
1592
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001593 VarDecl *CanonicalVD = VD->getCanonicalDecl();
1594 NamedDecl *ND = cast<NamedDecl>(CanonicalVD);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001595 // OpenMP [2.9.2, Restrictions, C/C++, p.2]
1596 // A threadprivate directive for file-scope variables must appear outside
1597 // any definition or declaration.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001598 if (CanonicalVD->getDeclContext()->isTranslationUnit() &&
1599 !getCurLexicalContext()->isTranslationUnit()) {
1600 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001601 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1602 bool IsDecl =
1603 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1604 Diag(VD->getLocation(),
1605 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1606 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001607 return ExprError();
1608 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001609 // OpenMP [2.9.2, Restrictions, C/C++, p.3]
1610 // A threadprivate directive for static class member variables must appear
1611 // in the class definition, in the same scope in which the member
1612 // variables are declared.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001613 if (CanonicalVD->isStaticDataMember() &&
1614 !CanonicalVD->getDeclContext()->Equals(getCurLexicalContext())) {
1615 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001616 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1617 bool IsDecl =
1618 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1619 Diag(VD->getLocation(),
1620 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1621 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001622 return ExprError();
1623 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001624 // OpenMP [2.9.2, Restrictions, C/C++, p.4]
1625 // A threadprivate directive for namespace-scope variables must appear
1626 // outside any definition or declaration other than the namespace
1627 // definition itself.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001628 if (CanonicalVD->getDeclContext()->isNamespace() &&
1629 (!getCurLexicalContext()->isFileContext() ||
1630 !getCurLexicalContext()->Encloses(CanonicalVD->getDeclContext()))) {
1631 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001632 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1633 bool IsDecl =
1634 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1635 Diag(VD->getLocation(),
1636 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1637 << VD;
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001638 return ExprError();
1639 }
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001640 // OpenMP [2.9.2, Restrictions, C/C++, p.6]
1641 // A threadprivate directive for static block-scope variables must appear
1642 // in the scope of the variable and not in a nested scope.
Alexey Bataev7d2960b2013-09-26 03:24:06 +00001643 if (CanonicalVD->isStaticLocal() && CurScope &&
1644 !isDeclInScope(ND, getCurLexicalContext(), CurScope)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001645 Diag(Id.getLoc(), diag::err_omp_var_scope)
Alexey Bataeved09d242014-05-28 05:53:51 +00001646 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
1647 bool IsDecl =
1648 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1649 Diag(VD->getLocation(),
1650 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1651 << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001652 return ExprError();
1653 }
1654
1655 // OpenMP [2.9.2, Restrictions, C/C++, p.2-6]
1656 // A threadprivate directive must lexically precede all references to any
1657 // of the variables in its list.
Alexey Bataev6ddfe1a2015-04-16 13:49:42 +00001658 if (VD->isUsed() && !DSAStack->isThreadPrivate(VD)) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001659 Diag(Id.getLoc(), diag::err_omp_var_used)
Alexey Bataeved09d242014-05-28 05:53:51 +00001660 << getOpenMPDirectiveName(OMPD_threadprivate) << VD;
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001661 return ExprError();
1662 }
1663
1664 QualType ExprType = VD->getType().getNonReferenceType();
Alexey Bataev376b4a42016-02-09 09:41:09 +00001665 return DeclRefExpr::Create(Context, NestedNameSpecifierLoc(),
1666 SourceLocation(), VD,
1667 /*RefersToEnclosingVariableOrCapture=*/false,
1668 Id.getLoc(), ExprType, VK_LValue);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001669}
1670
Alexey Bataeved09d242014-05-28 05:53:51 +00001671Sema::DeclGroupPtrTy
1672Sema::ActOnOpenMPThreadprivateDirective(SourceLocation Loc,
1673 ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001674 if (OMPThreadPrivateDecl *D = CheckOMPThreadPrivateDecl(Loc, VarList)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001675 CurContext->addDecl(D);
1676 return DeclGroupPtrTy::make(DeclGroupRef(D));
1677 }
David Blaikie0403cb12016-01-15 23:43:25 +00001678 return nullptr;
Alexey Bataeva769e072013-03-22 06:34:35 +00001679}
1680
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001681namespace {
1682class LocalVarRefChecker : public ConstStmtVisitor<LocalVarRefChecker, bool> {
1683 Sema &SemaRef;
1684
1685public:
1686 bool VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer9d168222016-08-05 17:44:54 +00001687 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001688 if (VD->hasLocalStorage()) {
1689 SemaRef.Diag(E->getLocStart(),
1690 diag::err_omp_local_var_in_threadprivate_init)
1691 << E->getSourceRange();
1692 SemaRef.Diag(VD->getLocation(), diag::note_defined_here)
1693 << VD << VD->getSourceRange();
1694 return true;
1695 }
1696 }
1697 return false;
1698 }
1699 bool VisitStmt(const Stmt *S) {
1700 for (auto Child : S->children()) {
1701 if (Child && Visit(Child))
1702 return true;
1703 }
1704 return false;
1705 }
Alexey Bataev23b69422014-06-18 07:08:49 +00001706 explicit LocalVarRefChecker(Sema &SemaRef) : SemaRef(SemaRef) {}
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001707};
1708} // namespace
1709
Alexey Bataeved09d242014-05-28 05:53:51 +00001710OMPThreadPrivateDecl *
1711Sema::CheckOMPThreadPrivateDecl(SourceLocation Loc, ArrayRef<Expr *> VarList) {
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001712 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00001713 for (auto &RefExpr : VarList) {
1714 DeclRefExpr *DE = cast<DeclRefExpr>(RefExpr);
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001715 VarDecl *VD = cast<VarDecl>(DE->getDecl());
1716 SourceLocation ILoc = DE->getExprLoc();
Alexey Bataeva769e072013-03-22 06:34:35 +00001717
Alexey Bataev376b4a42016-02-09 09:41:09 +00001718 // Mark variable as used.
1719 VD->setReferenced();
1720 VD->markUsed(Context);
1721
Alexey Bataevf56f98c2015-04-16 05:39:01 +00001722 QualType QType = VD->getType();
1723 if (QType->isDependentType() || QType->isInstantiationDependentType()) {
1724 // It will be analyzed later.
1725 Vars.push_back(DE);
1726 continue;
1727 }
1728
Alexey Bataeva769e072013-03-22 06:34:35 +00001729 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1730 // A threadprivate variable must not have an incomplete type.
1731 if (RequireCompleteType(ILoc, VD->getType(),
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001732 diag::err_omp_threadprivate_incomplete_type)) {
Alexey Bataeva769e072013-03-22 06:34:35 +00001733 continue;
1734 }
1735
1736 // OpenMP [2.9.2, Restrictions, C/C++, p.10]
1737 // A threadprivate variable must not have a reference type.
1738 if (VD->getType()->isReferenceType()) {
1739 Diag(ILoc, diag::err_omp_ref_type_arg)
Alexey Bataeved09d242014-05-28 05:53:51 +00001740 << getOpenMPDirectiveName(OMPD_threadprivate) << VD->getType();
1741 bool IsDecl =
1742 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1743 Diag(VD->getLocation(),
1744 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1745 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001746 continue;
1747 }
1748
Samuel Antaof8b50122015-07-13 22:54:53 +00001749 // Check if this is a TLS variable. If TLS is not being supported, produce
1750 // the corresponding diagnostic.
1751 if ((VD->getTLSKind() != VarDecl::TLS_None &&
1752 !(VD->hasAttr<OMPThreadPrivateDeclAttr>() &&
1753 getLangOpts().OpenMPUseTLS &&
1754 getASTContext().getTargetInfo().isTLSSupported())) ||
Alexey Bataev1a8b3f12015-05-06 06:34:55 +00001755 (VD->getStorageClass() == SC_Register && VD->hasAttr<AsmLabelAttr>() &&
1756 !VD->isLocalVarDecl())) {
Alexey Bataev26a39242015-01-13 03:35:30 +00001757 Diag(ILoc, diag::err_omp_var_thread_local)
1758 << VD << ((VD->getTLSKind() != VarDecl::TLS_None) ? 0 : 1);
Alexey Bataeved09d242014-05-28 05:53:51 +00001759 bool IsDecl =
1760 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
1761 Diag(VD->getLocation(),
1762 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
1763 << VD;
Alexey Bataeva769e072013-03-22 06:34:35 +00001764 continue;
1765 }
1766
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001767 // Check if initial value of threadprivate variable reference variable with
1768 // local storage (it is not supported by runtime).
1769 if (auto Init = VD->getAnyInitializer()) {
1770 LocalVarRefChecker Checker(*this);
Alexey Bataevf29276e2014-06-18 04:14:57 +00001771 if (Checker.Visit(Init))
1772 continue;
Alexey Bataev18b92ee2014-05-28 07:40:25 +00001773 }
1774
Alexey Bataeved09d242014-05-28 05:53:51 +00001775 Vars.push_back(RefExpr);
Alexey Bataevd178ad42014-03-07 08:03:37 +00001776 DSAStack->addDSA(VD, DE, OMPC_threadprivate);
Alexey Bataev97720002014-11-11 04:05:39 +00001777 VD->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
1778 Context, SourceRange(Loc, Loc)));
1779 if (auto *ML = Context.getASTMutationListener())
1780 ML->DeclarationMarkedOpenMPThreadPrivate(VD);
Alexey Bataeva769e072013-03-22 06:34:35 +00001781 }
Alexander Musmancb7f9c42014-05-15 13:04:49 +00001782 OMPThreadPrivateDecl *D = nullptr;
Alexey Bataevec3da872014-01-31 05:15:34 +00001783 if (!Vars.empty()) {
1784 D = OMPThreadPrivateDecl::Create(Context, getCurLexicalContext(), Loc,
1785 Vars);
1786 D->setAccess(AS_public);
1787 }
1788 return D;
Alexey Bataeva769e072013-03-22 06:34:35 +00001789}
Alexey Bataev6f6f3b42013-05-13 04:18:18 +00001790
Alexey Bataev7ff55242014-06-19 09:13:45 +00001791static void ReportOriginalDSA(Sema &SemaRef, DSAStackTy *Stack,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001792 const ValueDecl *D, DSAStackTy::DSAVarData DVar,
Alexey Bataev7ff55242014-06-19 09:13:45 +00001793 bool IsLoopIterVar = false) {
1794 if (DVar.RefExpr) {
1795 SemaRef.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_explicit_dsa)
1796 << getOpenMPClauseName(DVar.CKind);
1797 return;
1798 }
1799 enum {
1800 PDSA_StaticMemberShared,
1801 PDSA_StaticLocalVarShared,
1802 PDSA_LoopIterVarPrivate,
1803 PDSA_LoopIterVarLinear,
1804 PDSA_LoopIterVarLastprivate,
1805 PDSA_ConstVarShared,
1806 PDSA_GlobalVarShared,
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001807 PDSA_TaskVarFirstprivate,
Alexey Bataevbae9a792014-06-27 10:37:06 +00001808 PDSA_LocalVarPrivate,
1809 PDSA_Implicit
1810 } Reason = PDSA_Implicit;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001811 bool ReportHint = false;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001812 auto ReportLoc = D->getLocation();
1813 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev7ff55242014-06-19 09:13:45 +00001814 if (IsLoopIterVar) {
1815 if (DVar.CKind == OMPC_private)
1816 Reason = PDSA_LoopIterVarPrivate;
1817 else if (DVar.CKind == OMPC_lastprivate)
1818 Reason = PDSA_LoopIterVarLastprivate;
1819 else
1820 Reason = PDSA_LoopIterVarLinear;
Alexey Bataev35aaee62016-04-13 13:36:48 +00001821 } else if (isOpenMPTaskingDirective(DVar.DKind) &&
1822 DVar.CKind == OMPC_firstprivate) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001823 Reason = PDSA_TaskVarFirstprivate;
1824 ReportLoc = DVar.ImplicitDSALoc;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001825 } else if (VD && VD->isStaticLocal())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001826 Reason = PDSA_StaticLocalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001827 else if (VD && VD->isStaticDataMember())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001828 Reason = PDSA_StaticMemberShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001829 else if (VD && VD->isFileVarDecl())
Alexey Bataev7ff55242014-06-19 09:13:45 +00001830 Reason = PDSA_GlobalVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001831 else if (D->getType().isConstant(SemaRef.getASTContext()))
Alexey Bataev7ff55242014-06-19 09:13:45 +00001832 Reason = PDSA_ConstVarShared;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001833 else if (VD && VD->isLocalVarDecl() && DVar.CKind == OMPC_private) {
Alexey Bataev7ff55242014-06-19 09:13:45 +00001834 ReportHint = true;
1835 Reason = PDSA_LocalVarPrivate;
1836 }
Alexey Bataevbae9a792014-06-27 10:37:06 +00001837 if (Reason != PDSA_Implicit) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001838 SemaRef.Diag(ReportLoc, diag::note_omp_predetermined_dsa)
Alexey Bataevbae9a792014-06-27 10:37:06 +00001839 << Reason << ReportHint
1840 << getOpenMPDirectiveName(Stack->getCurrentDirective());
1841 } else if (DVar.ImplicitDSALoc.isValid()) {
1842 SemaRef.Diag(DVar.ImplicitDSALoc, diag::note_omp_implicit_dsa)
1843 << getOpenMPClauseName(DVar.CKind);
1844 }
Alexey Bataev7ff55242014-06-19 09:13:45 +00001845}
1846
Alexey Bataev758e55e2013-09-06 18:03:48 +00001847namespace {
1848class DSAAttrChecker : public StmtVisitor<DSAAttrChecker, void> {
1849 DSAStackTy *Stack;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001850 Sema &SemaRef;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001851 bool ErrorFound;
1852 CapturedStmt *CS;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00001853 llvm::SmallVector<Expr *, 8> ImplicitFirstprivate;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001854 llvm::SmallVector<Expr *, 8> ImplicitMap;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001855 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001856 llvm::DenseSet<ValueDecl *> ImplicitDeclarations;
Alexey Bataeved09d242014-05-28 05:53:51 +00001857
Alexey Bataev758e55e2013-09-06 18:03:48 +00001858public:
1859 void VisitDeclRefExpr(DeclRefExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001860 if (E->isTypeDependent() || E->isValueDependent() ||
1861 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1862 return;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001863 if (auto *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001864 VD = VD->getCanonicalDecl();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001865 // Skip internally declared variables.
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001866 if (VD->hasLocalStorage() && !CS->capturesVariable(VD))
Alexey Bataeved09d242014-05-28 05:53:51 +00001867 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001868
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001869 auto DVar = Stack->getTopDSA(VD, false);
1870 // Check if the variable has explicit DSA set and stop analysis if it so.
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00001871 if (DVar.RefExpr || !ImplicitDeclarations.insert(VD).second)
David Majnemer9d168222016-08-05 17:44:54 +00001872 return;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001873
Alexey Bataevafe50572017-10-06 17:00:28 +00001874 // Skip internally declared static variables.
1875 if (VD->hasGlobalStorage() && !CS->capturesVariable(VD))
1876 return;
1877
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001878 auto ELoc = E->getExprLoc();
1879 auto DKind = Stack->getCurrentDirective();
Alexey Bataev758e55e2013-09-06 18:03:48 +00001880 // The default(none) clause requires that each variable that is referenced
1881 // in the construct, and does not have a predetermined data-sharing
1882 // attribute, must have its data-sharing attribute explicitly determined
1883 // by being listed in a data-sharing attribute clause.
1884 if (DVar.CKind == OMPC_unknown && Stack->getDefaultDSA() == DSA_none &&
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001885 isParallelOrTaskRegion(DKind) &&
Alexey Bataev4acb8592014-07-07 13:01:15 +00001886 VarsWithInheritedDSA.count(VD) == 0) {
1887 VarsWithInheritedDSA[VD] = E;
Alexey Bataev758e55e2013-09-06 18:03:48 +00001888 return;
1889 }
1890
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001891 if (isOpenMPTargetExecutionDirective(DKind) &&
1892 !Stack->isLoopControlVariable(VD).first) {
1893 if (!Stack->checkMappableExprComponentListsForDecl(
1894 VD, /*CurrentRegionOnly=*/true,
1895 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1896 StackComponents,
1897 OpenMPClauseKind) {
1898 // Variable is used if it has been marked as an array, array
1899 // section or the variable iself.
1900 return StackComponents.size() == 1 ||
1901 std::all_of(
1902 std::next(StackComponents.rbegin()),
1903 StackComponents.rend(),
1904 [](const OMPClauseMappableExprCommon::
1905 MappableComponent &MC) {
1906 return MC.getAssociatedDeclaration() ==
1907 nullptr &&
1908 (isa<OMPArraySectionExpr>(
1909 MC.getAssociatedExpression()) ||
1910 isa<ArraySubscriptExpr>(
1911 MC.getAssociatedExpression()));
1912 });
1913 })) {
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001914 bool IsFirstprivate = false;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001915 // By default lambdas are captured as firstprivates.
1916 if (const auto *RD =
1917 VD->getType().getNonReferenceType()->getAsCXXRecordDecl())
Alexey Bataev2fd0cb22017-10-05 17:51:39 +00001918 IsFirstprivate = RD->isLambda();
1919 IsFirstprivate =
1920 IsFirstprivate ||
1921 (VD->getType().getNonReferenceType()->isScalarType() &&
1922 Stack->getDefaultDMA() != DMA_tofrom_scalar);
1923 if (IsFirstprivate)
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001924 ImplicitFirstprivate.emplace_back(E);
1925 else
1926 ImplicitMap.emplace_back(E);
1927 return;
1928 }
1929 }
1930
Alexey Bataev758e55e2013-09-06 18:03:48 +00001931 // OpenMP [2.9.3.6, Restrictions, p.2]
1932 // A list item that appears in a reduction clause of the innermost
1933 // enclosing worksharing or parallel construct may not be accessed in an
1934 // explicit task.
Alexey Bataev7ace49d2016-05-17 08:55:33 +00001935 DVar = Stack->hasInnermostDSA(
1936 VD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
1937 [](OpenMPDirectiveKind K) -> bool {
1938 return isOpenMPParallelDirective(K) ||
1939 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
1940 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00001941 /*FromParent=*/true);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001942 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
Alexey Bataevc5e02582014-06-16 07:08:35 +00001943 ErrorFound = true;
Alexey Bataev7ff55242014-06-19 09:13:45 +00001944 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
1945 ReportOriginalDSA(SemaRef, Stack, VD, DVar);
Alexey Bataevc5e02582014-06-16 07:08:35 +00001946 return;
1947 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00001948
1949 // Define implicit data-sharing attributes for task.
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001950 DVar = Stack->getImplicitDSA(VD, false);
Alexey Bataev35aaee62016-04-13 13:36:48 +00001951 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
1952 !Stack->isLoopControlVariable(VD).first)
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00001953 ImplicitFirstprivate.push_back(E);
Alexey Bataev758e55e2013-09-06 18:03:48 +00001954 }
1955 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001956 void VisitMemberExpr(MemberExpr *E) {
Alexey Bataev07b79c22016-04-29 09:56:11 +00001957 if (E->isTypeDependent() || E->isValueDependent() ||
1958 E->containsUnexpandedParameterPack() || E->isInstantiationDependent())
1959 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001960 auto *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001961 OpenMPDirectiveKind DKind = Stack->getCurrentDirective();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001962 if (isa<CXXThisExpr>(E->getBase()->IgnoreParens())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +00001963 if (!FD)
1964 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001965 auto DVar = Stack->getTopDSA(FD, false);
1966 // Check if the variable has explicit DSA set and stop analysis if it
1967 // so.
1968 if (DVar.RefExpr || !ImplicitDeclarations.insert(FD).second)
1969 return;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001970
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001971 if (isOpenMPTargetExecutionDirective(DKind) &&
1972 !Stack->isLoopControlVariable(FD).first &&
1973 !Stack->checkMappableExprComponentListsForDecl(
1974 FD, /*CurrentRegionOnly=*/true,
1975 [](OMPClauseMappableExprCommon::MappableExprComponentListRef
1976 StackComponents,
1977 OpenMPClauseKind) {
1978 return isa<CXXThisExpr>(
1979 cast<MemberExpr>(
1980 StackComponents.back().getAssociatedExpression())
1981 ->getBase()
1982 ->IgnoreParens());
1983 })) {
1984 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
1985 // A bit-field cannot appear in a map clause.
1986 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +00001987 if (FD->isBitField())
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001988 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001989 ImplicitMap.emplace_back(E);
1990 return;
1991 }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00001992
Alexey Bataevf47c4b42017-09-26 13:47:31 +00001993 auto ELoc = E->getExprLoc();
1994 // OpenMP [2.9.3.6, Restrictions, p.2]
1995 // A list item that appears in a reduction clause of the innermost
1996 // enclosing worksharing or parallel construct may not be accessed in
1997 // an explicit task.
1998 DVar = Stack->hasInnermostDSA(
1999 FD, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
2000 [](OpenMPDirectiveKind K) -> bool {
2001 return isOpenMPParallelDirective(K) ||
2002 isOpenMPWorksharingDirective(K) || isOpenMPTeamsDirective(K);
2003 },
2004 /*FromParent=*/true);
2005 if (isOpenMPTaskingDirective(DKind) && DVar.CKind == OMPC_reduction) {
2006 ErrorFound = true;
2007 SemaRef.Diag(ELoc, diag::err_omp_reduction_in_task);
2008 ReportOriginalDSA(SemaRef, Stack, FD, DVar);
2009 return;
2010 }
2011
2012 // Define implicit data-sharing attributes for task.
2013 DVar = Stack->getImplicitDSA(FD, false);
2014 if (isOpenMPTaskingDirective(DKind) && DVar.CKind != OMPC_shared &&
2015 !Stack->isLoopControlVariable(FD).first)
2016 ImplicitFirstprivate.push_back(E);
2017 return;
2018 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002019 if (isOpenMPTargetExecutionDirective(DKind)) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002020 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
Alexey Bataevb7a9b742017-12-05 19:20:09 +00002021 if (!CheckMapClauseExpressionBase(SemaRef, E, CurComponents, OMPC_map,
2022 /*NoDiagnose=*/true))
Alexey Bataev27041fa2017-12-05 15:22:49 +00002023 return;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002024 auto *VD = cast<ValueDecl>(
2025 CurComponents.back().getAssociatedDeclaration()->getCanonicalDecl());
2026 if (!Stack->checkMappableExprComponentListsForDecl(
2027 VD, /*CurrentRegionOnly=*/true,
2028 [&CurComponents](
2029 OMPClauseMappableExprCommon::MappableExprComponentListRef
2030 StackComponents,
2031 OpenMPClauseKind) {
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002032 auto CCI = CurComponents.rbegin();
Alexey Bataev5ec38932017-09-26 16:19:04 +00002033 auto CCE = CurComponents.rend();
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002034 for (const auto &SC : llvm::reverse(StackComponents)) {
2035 // Do both expressions have the same kind?
2036 if (CCI->getAssociatedExpression()->getStmtClass() !=
2037 SC.getAssociatedExpression()->getStmtClass())
2038 if (!(isa<OMPArraySectionExpr>(
2039 SC.getAssociatedExpression()) &&
2040 isa<ArraySubscriptExpr>(
2041 CCI->getAssociatedExpression())))
2042 return false;
2043
2044 Decl *CCD = CCI->getAssociatedDeclaration();
2045 Decl *SCD = SC.getAssociatedDeclaration();
2046 CCD = CCD ? CCD->getCanonicalDecl() : nullptr;
2047 SCD = SCD ? SCD->getCanonicalDecl() : nullptr;
2048 if (SCD != CCD)
2049 return false;
2050 std::advance(CCI, 1);
Alexey Bataev5ec38932017-09-26 16:19:04 +00002051 if (CCI == CCE)
2052 break;
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002053 }
2054 return true;
2055 })) {
2056 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002057 }
Alexey Bataev7fcacd82016-11-28 15:55:15 +00002058 } else
2059 Visit(E->getBase());
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002060 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002061 void VisitOMPExecutableDirective(OMPExecutableDirective *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002062 for (auto *C : S->clauses()) {
2063 // Skip analysis of arguments of implicitly defined firstprivate clause
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002064 // for task|target directives.
2065 // Skip analysis of arguments of implicitly defined map clause for target
2066 // directives.
2067 if (C && !((isa<OMPFirstprivateClause>(C) || isa<OMPMapClause>(C)) &&
2068 C->isImplicit())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002069 for (auto *CC : C->children()) {
2070 if (CC)
2071 Visit(CC);
2072 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002073 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002074 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002075 }
2076 void VisitStmt(Stmt *S) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002077 for (auto *C : S->children()) {
2078 if (C && !isa<OMPExecutableDirective>(C))
2079 Visit(C);
2080 }
Alexey Bataeved09d242014-05-28 05:53:51 +00002081 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002082
2083 bool isErrorFound() { return ErrorFound; }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002084 ArrayRef<Expr *> getImplicitFirstprivate() const {
2085 return ImplicitFirstprivate;
2086 }
2087 ArrayRef<Expr *> getImplicitMap() const { return ImplicitMap; }
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002088 llvm::DenseMap<ValueDecl *, Expr *> &getVarsWithInheritedDSA() {
Alexey Bataev4acb8592014-07-07 13:01:15 +00002089 return VarsWithInheritedDSA;
2090 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002091
Alexey Bataev7ff55242014-06-19 09:13:45 +00002092 DSAAttrChecker(DSAStackTy *S, Sema &SemaRef, CapturedStmt *CS)
2093 : Stack(S), SemaRef(SemaRef), ErrorFound(false), CS(CS) {}
Alexey Bataev758e55e2013-09-06 18:03:48 +00002094};
Alexey Bataeved09d242014-05-28 05:53:51 +00002095} // namespace
Alexey Bataev758e55e2013-09-06 18:03:48 +00002096
Alexey Bataevbae9a792014-06-27 10:37:06 +00002097void Sema::ActOnOpenMPRegionStart(OpenMPDirectiveKind DKind, Scope *CurScope) {
Alexey Bataev9959db52014-05-06 10:08:46 +00002098 switch (DKind) {
Kelvin Li70a12c52016-07-13 21:51:49 +00002099 case OMPD_parallel:
2100 case OMPD_parallel_for:
2101 case OMPD_parallel_for_simd:
2102 case OMPD_parallel_sections:
Carlo Bertolliba1487b2017-10-04 14:12:09 +00002103 case OMPD_teams:
Alexey Bataev999277a2017-12-06 14:31:09 +00002104 case OMPD_teams_distribute:
2105 case OMPD_teams_distribute_simd: {
Alexey Bataev9959db52014-05-06 10:08:46 +00002106 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev2377fe92015-09-10 08:12:02 +00002107 QualType KmpInt32PtrTy =
2108 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002109 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002110 std::make_pair(".global_tid.", KmpInt32PtrTy),
2111 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2112 std::make_pair(StringRef(), QualType()) // __context with shared vars
Alexey Bataev9959db52014-05-06 10:08:46 +00002113 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002114 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2115 Params);
Alexey Bataev9959db52014-05-06 10:08:46 +00002116 break;
2117 }
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002118 case OMPD_target_teams:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00002119 case OMPD_target_parallel:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00002120 case OMPD_target_parallel_for:
Alexey Bataevdfa430f2017-12-08 15:03:50 +00002121 case OMPD_target_parallel_for_simd:
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00002122 case OMPD_target_teams_distribute:
2123 case OMPD_target_teams_distribute_simd: {
Alexey Bataev8451efa2018-01-15 19:06:12 +00002124 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2125 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2126 FunctionProtoType::ExtProtoInfo EPI;
2127 EPI.Variadic = true;
2128 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2129 Sema::CapturedParamNameType Params[] = {
2130 std::make_pair(".global_tid.", KmpInt32Ty),
2131 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2132 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2133 std::make_pair(".copy_fn.",
2134 Context.getPointerType(CopyFnType).withConst()),
2135 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2136 std::make_pair(StringRef(), QualType()) // __context with shared vars
2137 };
2138 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2139 Params);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002140 Sema::CapturedParamNameType ParamsTarget[] = {
2141 std::make_pair(StringRef(), QualType()) // __context with shared vars
2142 };
2143 // Start a captured region for 'target' with no implicit parameters.
2144 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2145 ParamsTarget);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002146 QualType KmpInt32PtrTy =
2147 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002148 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002149 std::make_pair(".global_tid.", KmpInt32PtrTy),
2150 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2151 std::make_pair(StringRef(), QualType()) // __context with shared vars
2152 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002153 // Start a captured region for 'teams' or 'parallel'. Both regions have
2154 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002155 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002156 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002157 break;
2158 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002159 case OMPD_target:
2160 case OMPD_target_simd: {
2161 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2162 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2163 FunctionProtoType::ExtProtoInfo EPI;
2164 EPI.Variadic = true;
2165 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2166 Sema::CapturedParamNameType Params[] = {
2167 std::make_pair(".global_tid.", KmpInt32Ty),
2168 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2169 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2170 std::make_pair(".copy_fn.",
2171 Context.getPointerType(CopyFnType).withConst()),
2172 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2173 std::make_pair(StringRef(), QualType()) // __context with shared vars
2174 };
2175 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2176 Params);
2177 // Mark this captured region as inlined, because we don't use outlined
2178 // function directly.
2179 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2180 AlwaysInlineAttr::CreateImplicit(
2181 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2182 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2183 std::make_pair(StringRef(), QualType()));
2184 break;
2185 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002186 case OMPD_simd:
2187 case OMPD_for:
2188 case OMPD_for_simd:
2189 case OMPD_sections:
2190 case OMPD_section:
2191 case OMPD_single:
2192 case OMPD_master:
2193 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002194 case OMPD_taskgroup:
2195 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002196 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002197 case OMPD_ordered:
2198 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002199 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002200 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002201 std::make_pair(StringRef(), QualType()) // __context with shared vars
2202 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002203 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2204 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002205 break;
2206 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002207 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002208 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002209 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2210 FunctionProtoType::ExtProtoInfo EPI;
2211 EPI.Variadic = true;
2212 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002213 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002214 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002215 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2216 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2217 std::make_pair(".copy_fn.",
2218 Context.getPointerType(CopyFnType).withConst()),
2219 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002220 std::make_pair(StringRef(), QualType()) // __context with shared vars
2221 };
2222 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2223 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002224 // Mark this captured region as inlined, because we don't use outlined
2225 // function directly.
2226 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2227 AlwaysInlineAttr::CreateImplicit(
2228 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002229 break;
2230 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002231 case OMPD_taskloop:
2232 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002233 QualType KmpInt32Ty =
2234 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2235 QualType KmpUInt64Ty =
2236 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
2237 QualType KmpInt64Ty =
2238 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
2239 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2240 FunctionProtoType::ExtProtoInfo EPI;
2241 EPI.Variadic = true;
2242 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002243 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002244 std::make_pair(".global_tid.", KmpInt32Ty),
2245 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2246 std::make_pair(".privates.",
2247 Context.VoidPtrTy.withConst().withRestrict()),
2248 std::make_pair(
2249 ".copy_fn.",
2250 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2251 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2252 std::make_pair(".lb.", KmpUInt64Ty),
2253 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
2254 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002255 std::make_pair(".reductions.",
2256 Context.VoidPtrTy.withConst().withRestrict()),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002257 std::make_pair(StringRef(), QualType()) // __context with shared vars
2258 };
2259 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2260 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002261 // Mark this captured region as inlined, because we don't use outlined
2262 // function directly.
2263 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2264 AlwaysInlineAttr::CreateImplicit(
2265 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002266 break;
2267 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002268 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002269 case OMPD_distribute_parallel_for: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00002270 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2271 QualType KmpInt32PtrTy =
2272 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2273 Sema::CapturedParamNameType Params[] = {
2274 std::make_pair(".global_tid.", KmpInt32PtrTy),
2275 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2276 std::make_pair(".previous.lb.", Context.getSizeType()),
2277 std::make_pair(".previous.ub.", Context.getSizeType()),
2278 std::make_pair(StringRef(), QualType()) // __context with shared vars
2279 };
2280 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2281 Params);
2282 break;
2283 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002284 case OMPD_target_teams_distribute_parallel_for:
2285 case OMPD_target_teams_distribute_parallel_for_simd: {
Carlo Bertolli52978c32018-01-03 21:12:44 +00002286 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2287 QualType KmpInt32PtrTy =
2288 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2289
Alexey Bataev8451efa2018-01-15 19:06:12 +00002290 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2291 FunctionProtoType::ExtProtoInfo EPI;
2292 EPI.Variadic = true;
2293 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2294 Sema::CapturedParamNameType Params[] = {
2295 std::make_pair(".global_tid.", KmpInt32Ty),
2296 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2297 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2298 std::make_pair(".copy_fn.",
2299 Context.getPointerType(CopyFnType).withConst()),
2300 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2301 std::make_pair(StringRef(), QualType()) // __context with shared vars
2302 };
2303 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2304 Params);
Carlo Bertolli52978c32018-01-03 21:12:44 +00002305 Sema::CapturedParamNameType ParamsTarget[] = {
2306 std::make_pair(StringRef(), QualType()) // __context with shared vars
2307 };
2308 // Start a captured region for 'target' with no implicit parameters.
2309 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2310 ParamsTarget);
2311
2312 Sema::CapturedParamNameType ParamsTeams[] = {
2313 std::make_pair(".global_tid.", KmpInt32PtrTy),
2314 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2315 std::make_pair(StringRef(), QualType()) // __context with shared vars
2316 };
2317 // Start a captured region for 'target' with no implicit parameters.
2318 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2319 ParamsTeams);
2320
2321 Sema::CapturedParamNameType ParamsParallel[] = {
2322 std::make_pair(".global_tid.", KmpInt32PtrTy),
2323 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2324 std::make_pair(".previous.lb.", Context.getSizeType()),
2325 std::make_pair(".previous.ub.", Context.getSizeType()),
2326 std::make_pair(StringRef(), QualType()) // __context with shared vars
2327 };
2328 // Start a captured region for 'teams' or 'parallel'. Both regions have
2329 // the same implicit parameters.
2330 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2331 ParamsParallel);
2332 break;
2333 }
2334
Alexey Bataev46506272017-12-05 17:41:34 +00002335 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00002336 case OMPD_teams_distribute_parallel_for_simd: {
Carlo Bertolli62fae152017-11-20 20:46:39 +00002337 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2338 QualType KmpInt32PtrTy =
2339 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2340
2341 Sema::CapturedParamNameType ParamsTeams[] = {
2342 std::make_pair(".global_tid.", KmpInt32PtrTy),
2343 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2344 std::make_pair(StringRef(), QualType()) // __context with shared vars
2345 };
2346 // Start a captured region for 'target' with no implicit parameters.
2347 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2348 ParamsTeams);
2349
2350 Sema::CapturedParamNameType ParamsParallel[] = {
2351 std::make_pair(".global_tid.", KmpInt32PtrTy),
2352 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2353 std::make_pair(".previous.lb.", Context.getSizeType()),
2354 std::make_pair(".previous.ub.", Context.getSizeType()),
2355 std::make_pair(StringRef(), QualType()) // __context with shared vars
2356 };
2357 // Start a captured region for 'teams' or 'parallel'. Both regions have
2358 // the same implicit parameters.
2359 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2360 ParamsParallel);
2361 break;
2362 }
Alexey Bataev7828b252017-11-21 17:08:48 +00002363 case OMPD_target_update:
2364 case OMPD_target_enter_data:
2365 case OMPD_target_exit_data: {
2366 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2367 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2368 FunctionProtoType::ExtProtoInfo EPI;
2369 EPI.Variadic = true;
2370 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2371 Sema::CapturedParamNameType Params[] = {
2372 std::make_pair(".global_tid.", KmpInt32Ty),
2373 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2374 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2375 std::make_pair(".copy_fn.",
2376 Context.getPointerType(CopyFnType).withConst()),
2377 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2378 std::make_pair(StringRef(), QualType()) // __context with shared vars
2379 };
2380 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2381 Params);
2382 // Mark this captured region as inlined, because we don't use outlined
2383 // function directly.
2384 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2385 AlwaysInlineAttr::CreateImplicit(
2386 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2387 break;
2388 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002389 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002390 case OMPD_taskyield:
2391 case OMPD_barrier:
2392 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002393 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002394 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002395 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002396 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002397 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002398 case OMPD_declare_target:
2399 case OMPD_end_declare_target:
Alexey Bataev9959db52014-05-06 10:08:46 +00002400 llvm_unreachable("OpenMP Directive is not allowed");
2401 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002402 llvm_unreachable("Unknown OpenMP directive");
2403 }
2404}
2405
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002406int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2407 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2408 getOpenMPCaptureRegions(CaptureRegions, DKind);
2409 return CaptureRegions.size();
2410}
2411
Alexey Bataev3392d762016-02-16 11:18:12 +00002412static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002413 Expr *CaptureExpr, bool WithInit,
2414 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002415 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002416 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002417 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002418 QualType Ty = Init->getType();
2419 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002420 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00002421 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002422 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00002423 Ty = C.getPointerType(Ty);
2424 ExprResult Res =
2425 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2426 if (!Res.isUsable())
2427 return nullptr;
2428 Init = Res.get();
2429 }
Alexey Bataev61205072016-03-02 04:57:40 +00002430 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002431 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002432 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2433 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002434 if (!WithInit)
2435 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00002436 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002437 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002438 return CED;
2439}
2440
Alexey Bataev61205072016-03-02 04:57:40 +00002441static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2442 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002443 OMPCapturedExprDecl *CD;
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002444 if (auto *VD = S.IsOpenMPCapturedDecl(D)) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002445 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002446 } else {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002447 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2448 /*AsExpression=*/false);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002449 }
Alexey Bataev3392d762016-02-16 11:18:12 +00002450 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002451 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002452}
2453
Alexey Bataev5a3af132016-03-29 08:58:54 +00002454static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002455 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002456 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002457 OMPCapturedExprDecl *CD = buildCaptureDecl(
2458 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2459 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00002460 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2461 CaptureExpr->getExprLoc());
2462 }
2463 ExprResult Res = Ref;
2464 if (!S.getLangOpts().CPlusPlus &&
2465 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002466 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002467 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002468 if (!Res.isUsable())
2469 return ExprError();
2470 }
2471 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002472}
2473
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002474namespace {
2475// OpenMP directives parsed in this section are represented as a
2476// CapturedStatement with an associated statement. If a syntax error
2477// is detected during the parsing of the associated statement, the
2478// compiler must abort processing and close the CapturedStatement.
2479//
2480// Combined directives such as 'target parallel' have more than one
2481// nested CapturedStatements. This RAII ensures that we unwind out
2482// of all the nested CapturedStatements when an error is found.
2483class CaptureRegionUnwinderRAII {
2484private:
2485 Sema &S;
2486 bool &ErrorFound;
2487 OpenMPDirectiveKind DKind;
2488
2489public:
2490 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2491 OpenMPDirectiveKind DKind)
2492 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2493 ~CaptureRegionUnwinderRAII() {
2494 if (ErrorFound) {
2495 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2496 while (--ThisCaptureLevel >= 0)
2497 S.ActOnCapturedRegionError();
2498 }
2499 }
2500};
2501} // namespace
2502
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002503StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2504 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002505 bool ErrorFound = false;
2506 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2507 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002508 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002509 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002510 return StmtError();
2511 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002512
Alexey Bataev2ba67042017-11-28 21:11:44 +00002513 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2514 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00002515 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002516 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002517 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002518 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002519 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002520 for (auto *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002521 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2522 Clause->getClauseKind() == OMPC_in_reduction) {
2523 // Capture taskgroup task_reduction descriptors inside the tasking regions
2524 // with the corresponding in_reduction items.
2525 auto *IRC = cast<OMPInReductionClause>(Clause);
2526 for (auto *E : IRC->taskgroup_descriptors())
2527 if (E)
2528 MarkDeclarationsReferencedInExpr(E);
2529 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002530 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002531 Clause->getClauseKind() == OMPC_copyprivate ||
2532 (getLangOpts().OpenMPUseTLS &&
2533 getASTContext().getTargetInfo().isTLSSupported() &&
2534 Clause->getClauseKind() == OMPC_copyin)) {
2535 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002536 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002537 for (auto *VarRef : Clause->children()) {
2538 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002539 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002540 }
2541 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002542 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00002543 } else if (CaptureRegions.size() > 1 ||
2544 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002545 if (auto *C = OMPClauseWithPreInit::get(Clause))
2546 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002547 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2548 if (auto *E = C->getPostUpdateExpr())
2549 MarkDeclarationsReferencedInExpr(E);
2550 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002551 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002552 if (Clause->getClauseKind() == OMPC_schedule)
2553 SC = cast<OMPScheduleClause>(Clause);
2554 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002555 OC = cast<OMPOrderedClause>(Clause);
2556 else if (Clause->getClauseKind() == OMPC_linear)
2557 LCs.push_back(cast<OMPLinearClause>(Clause));
2558 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002559 // OpenMP, 2.7.1 Loop Construct, Restrictions
2560 // The nonmonotonic modifier cannot be specified if an ordered clause is
2561 // specified.
2562 if (SC &&
2563 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2564 SC->getSecondScheduleModifier() ==
2565 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2566 OC) {
2567 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2568 ? SC->getFirstScheduleModifierLoc()
2569 : SC->getSecondScheduleModifierLoc(),
2570 diag::err_omp_schedule_nonmonotonic_ordered)
2571 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2572 ErrorFound = true;
2573 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002574 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2575 for (auto *C : LCs) {
2576 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2577 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2578 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002579 ErrorFound = true;
2580 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002581 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2582 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2583 OC->getNumForLoops()) {
2584 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2585 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2586 ErrorFound = true;
2587 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002588 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002589 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002590 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002591 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00002592 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002593 // Mark all variables in private list clauses as used in inner region.
2594 // Required for proper codegen of combined directives.
2595 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00002596 if (ThisCaptureRegion != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002597 for (auto *C : PICs) {
2598 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2599 // Find the particular capture region for the clause if the
2600 // directive is a combined one with multiple capture regions.
2601 // If the directive is not a combined one, the capture region
2602 // associated with the clause is OMPD_unknown and is generated
2603 // only once.
2604 if (CaptureRegion == ThisCaptureRegion ||
2605 CaptureRegion == OMPD_unknown) {
2606 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2607 for (auto *D : DS->decls())
2608 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2609 }
2610 }
2611 }
2612 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002613 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002614 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002615 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002616}
2617
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002618static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2619 OpenMPDirectiveKind CancelRegion,
2620 SourceLocation StartLoc) {
2621 // CancelRegion is only needed for cancel and cancellation_point.
2622 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2623 return false;
2624
2625 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2626 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2627 return false;
2628
2629 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2630 << getOpenMPDirectiveName(CancelRegion);
2631 return true;
2632}
2633
2634static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002635 OpenMPDirectiveKind CurrentRegion,
2636 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002637 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002638 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002639 if (Stack->getCurScope()) {
2640 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002641 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002642 bool NestingProhibited = false;
2643 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002644 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002645 enum {
2646 NoRecommend,
2647 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002648 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002649 ShouldBeInTargetRegion,
2650 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002651 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002652 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002653 // OpenMP [2.16, Nesting of Regions]
2654 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002655 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002656 // An ordered construct with the simd clause is the only OpenMP
2657 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002658 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002659 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2660 // message.
2661 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2662 ? diag::err_omp_prohibited_region_simd
2663 : diag::warn_omp_nesting_simd);
2664 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002665 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002666 if (ParentRegion == OMPD_atomic) {
2667 // OpenMP [2.16, Nesting of Regions]
2668 // OpenMP constructs may not be nested inside an atomic region.
2669 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2670 return true;
2671 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002672 if (CurrentRegion == OMPD_section) {
2673 // OpenMP [2.7.2, sections Construct, Restrictions]
2674 // Orphaned section directives are prohibited. That is, the section
2675 // directives must appear within the sections construct and must not be
2676 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002677 if (ParentRegion != OMPD_sections &&
2678 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002679 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2680 << (ParentRegion != OMPD_unknown)
2681 << getOpenMPDirectiveName(ParentRegion);
2682 return true;
2683 }
2684 return false;
2685 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002686 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002687 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002688 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002689 if (ParentRegion == OMPD_unknown &&
2690 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002691 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002692 if (CurrentRegion == OMPD_cancellation_point ||
2693 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002694 // OpenMP [2.16, Nesting of Regions]
2695 // A cancellation point construct for which construct-type-clause is
2696 // taskgroup must be nested inside a task construct. A cancellation
2697 // point construct for which construct-type-clause is not taskgroup must
2698 // be closely nested inside an OpenMP construct that matches the type
2699 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002700 // A cancel construct for which construct-type-clause is taskgroup must be
2701 // nested inside a task construct. A cancel construct for which
2702 // construct-type-clause is not taskgroup must be closely nested inside an
2703 // OpenMP construct that matches the type specified in
2704 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002705 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002706 !((CancelRegion == OMPD_parallel &&
2707 (ParentRegion == OMPD_parallel ||
2708 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002709 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002710 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002711 ParentRegion == OMPD_target_parallel_for ||
2712 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00002713 ParentRegion == OMPD_teams_distribute_parallel_for ||
2714 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002715 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2716 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002717 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2718 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002719 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002720 // OpenMP [2.16, Nesting of Regions]
2721 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002722 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002723 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002724 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002725 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2726 // OpenMP [2.16, Nesting of Regions]
2727 // A critical region may not be nested (closely or otherwise) inside a
2728 // critical region with the same name. Note that this restriction is not
2729 // sufficient to prevent deadlock.
2730 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002731 bool DeadLock = Stack->hasDirective(
2732 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2733 const DeclarationNameInfo &DNI,
2734 SourceLocation Loc) -> bool {
2735 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2736 PreviousCriticalLoc = Loc;
2737 return true;
2738 } else
2739 return false;
2740 },
2741 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002742 if (DeadLock) {
2743 SemaRef.Diag(StartLoc,
2744 diag::err_omp_prohibited_region_critical_same_name)
2745 << CurrentName.getName();
2746 if (PreviousCriticalLoc.isValid())
2747 SemaRef.Diag(PreviousCriticalLoc,
2748 diag::note_omp_previous_critical_region);
2749 return true;
2750 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002751 } else if (CurrentRegion == OMPD_barrier) {
2752 // OpenMP [2.16, Nesting of Regions]
2753 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002754 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002755 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2756 isOpenMPTaskingDirective(ParentRegion) ||
2757 ParentRegion == OMPD_master ||
2758 ParentRegion == OMPD_critical ||
2759 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002760 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002761 !isOpenMPParallelDirective(CurrentRegion) &&
2762 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002763 // OpenMP [2.16, Nesting of Regions]
2764 // A worksharing region may not be closely nested inside a worksharing,
2765 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002766 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2767 isOpenMPTaskingDirective(ParentRegion) ||
2768 ParentRegion == OMPD_master ||
2769 ParentRegion == OMPD_critical ||
2770 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002771 Recommend = ShouldBeInParallelRegion;
2772 } else if (CurrentRegion == OMPD_ordered) {
2773 // OpenMP [2.16, Nesting of Regions]
2774 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002775 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002776 // An ordered region must be closely nested inside a loop region (or
2777 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002778 // OpenMP [2.8.1,simd Construct, Restrictions]
2779 // An ordered construct with the simd clause is the only OpenMP construct
2780 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002781 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002782 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002783 !(isOpenMPSimdDirective(ParentRegion) ||
2784 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002785 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002786 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002787 // OpenMP [2.16, Nesting of Regions]
2788 // If specified, a teams construct must be contained within a target
2789 // construct.
2790 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002791 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002792 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002793 }
Kelvin Libf594a52016-12-17 05:48:59 +00002794 if (!NestingProhibited &&
2795 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2796 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2797 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002798 // OpenMP [2.16, Nesting of Regions]
2799 // distribute, parallel, parallel sections, parallel workshare, and the
2800 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2801 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002802 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2803 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002804 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002805 }
David Majnemer9d168222016-08-05 17:44:54 +00002806 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002807 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002808 // OpenMP 4.5 [2.17 Nesting of Regions]
2809 // The region associated with the distribute construct must be strictly
2810 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002811 NestingProhibited =
2812 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002813 Recommend = ShouldBeInTeamsRegion;
2814 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002815 if (!NestingProhibited &&
2816 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2817 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2818 // OpenMP 4.5 [2.17 Nesting of Regions]
2819 // If a target, target update, target data, target enter data, or
2820 // target exit data construct is encountered during execution of a
2821 // target region, the behavior is unspecified.
2822 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002823 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2824 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002825 if (isOpenMPTargetExecutionDirective(K)) {
2826 OffendingRegion = K;
2827 return true;
2828 } else
2829 return false;
2830 },
2831 false /* don't skip top directive */);
2832 CloseNesting = false;
2833 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002834 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002835 if (OrphanSeen) {
2836 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2837 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2838 } else {
2839 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2840 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2841 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2842 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002843 return true;
2844 }
2845 }
2846 return false;
2847}
2848
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002849static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2850 ArrayRef<OMPClause *> Clauses,
2851 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2852 bool ErrorFound = false;
2853 unsigned NamedModifiersNumber = 0;
2854 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2855 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002856 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002857 for (const auto *C : Clauses) {
2858 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2859 // At most one if clause without a directive-name-modifier can appear on
2860 // the directive.
2861 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2862 if (FoundNameModifiers[CurNM]) {
2863 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2864 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2865 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2866 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002867 } else if (CurNM != OMPD_unknown) {
2868 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002869 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002870 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002871 FoundNameModifiers[CurNM] = IC;
2872 if (CurNM == OMPD_unknown)
2873 continue;
2874 // Check if the specified name modifier is allowed for the current
2875 // directive.
2876 // At most one if clause with the particular directive-name-modifier can
2877 // appear on the directive.
2878 bool MatchFound = false;
2879 for (auto NM : AllowedNameModifiers) {
2880 if (CurNM == NM) {
2881 MatchFound = true;
2882 break;
2883 }
2884 }
2885 if (!MatchFound) {
2886 S.Diag(IC->getNameModifierLoc(),
2887 diag::err_omp_wrong_if_directive_name_modifier)
2888 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2889 ErrorFound = true;
2890 }
2891 }
2892 }
2893 // If any if clause on the directive includes a directive-name-modifier then
2894 // all if clauses on the directive must include a directive-name-modifier.
2895 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2896 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2897 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2898 diag::err_omp_no_more_if_clause);
2899 } else {
2900 std::string Values;
2901 std::string Sep(", ");
2902 unsigned AllowedCnt = 0;
2903 unsigned TotalAllowedNum =
2904 AllowedNameModifiers.size() - NamedModifiersNumber;
2905 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2906 ++Cnt) {
2907 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2908 if (!FoundNameModifiers[NM]) {
2909 Values += "'";
2910 Values += getOpenMPDirectiveName(NM);
2911 Values += "'";
2912 if (AllowedCnt + 2 == TotalAllowedNum)
2913 Values += " or ";
2914 else if (AllowedCnt + 1 != TotalAllowedNum)
2915 Values += Sep;
2916 ++AllowedCnt;
2917 }
2918 }
2919 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2920 diag::err_omp_unnamed_if_clause)
2921 << (TotalAllowedNum > 1) << Values;
2922 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002923 for (auto Loc : NameModifierLoc) {
2924 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2925 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002926 ErrorFound = true;
2927 }
2928 return ErrorFound;
2929}
2930
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002931StmtResult Sema::ActOnOpenMPExecutableDirective(
2932 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2933 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2934 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002935 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002936 // First check CancelRegion which is then used in checkNestingOfRegions.
2937 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2938 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002939 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002940 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002941
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002942 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002943 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002944 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002945 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002946 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002947 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2948
2949 // Check default data sharing attributes for referenced variables.
2950 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002951 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2952 Stmt *S = AStmt;
2953 while (--ThisCaptureLevel >= 0)
2954 S = cast<CapturedStmt>(S)->getCapturedStmt();
2955 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002956 if (DSAChecker.isErrorFound())
2957 return StmtError();
2958 // Generate list of implicitly defined firstprivate variables.
2959 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002960
Alexey Bataev88202be2017-07-27 13:20:36 +00002961 SmallVector<Expr *, 4> ImplicitFirstprivates(
2962 DSAChecker.getImplicitFirstprivate().begin(),
2963 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002964 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
2965 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00002966 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
2967 for (auto *C : Clauses) {
2968 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
2969 for (auto *E : IRC->taskgroup_descriptors())
2970 if (E)
2971 ImplicitFirstprivates.emplace_back(E);
2972 }
2973 }
2974 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002975 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00002976 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
2977 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002978 ClausesWithImplicit.push_back(Implicit);
2979 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00002980 ImplicitFirstprivates.size();
Alexey Bataev68446b72014-07-18 07:47:19 +00002981 } else
2982 ErrorFound = true;
2983 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002984 if (!ImplicitMaps.empty()) {
2985 if (OMPClause *Implicit = ActOnOpenMPMapClause(
2986 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
2987 SourceLocation(), SourceLocation(), ImplicitMaps,
2988 SourceLocation(), SourceLocation(), SourceLocation())) {
2989 ClausesWithImplicit.emplace_back(Implicit);
2990 ErrorFound |=
2991 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
2992 } else
2993 ErrorFound = true;
2994 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002995 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00002996
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002997 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002998 switch (Kind) {
2999 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003000 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3001 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003002 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003003 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003004 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003005 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3006 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003007 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003008 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003009 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3010 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003011 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003012 case OMPD_for_simd:
3013 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3014 EndLoc, VarsWithInheritedDSA);
3015 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003016 case OMPD_sections:
3017 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3018 EndLoc);
3019 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003020 case OMPD_section:
3021 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003022 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003023 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3024 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003025 case OMPD_single:
3026 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3027 EndLoc);
3028 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003029 case OMPD_master:
3030 assert(ClausesWithImplicit.empty() &&
3031 "No clauses are allowed for 'omp master' directive");
3032 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3033 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003034 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003035 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3036 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003037 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003038 case OMPD_parallel_for:
3039 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3040 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003041 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003042 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003043 case OMPD_parallel_for_simd:
3044 Res = ActOnOpenMPParallelForSimdDirective(
3045 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003046 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003047 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003048 case OMPD_parallel_sections:
3049 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3050 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003051 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003052 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003053 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003054 Res =
3055 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003056 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003057 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003058 case OMPD_taskyield:
3059 assert(ClausesWithImplicit.empty() &&
3060 "No clauses are allowed for 'omp taskyield' directive");
3061 assert(AStmt == nullptr &&
3062 "No associated statement allowed for 'omp taskyield' directive");
3063 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3064 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003065 case OMPD_barrier:
3066 assert(ClausesWithImplicit.empty() &&
3067 "No clauses are allowed for 'omp barrier' directive");
3068 assert(AStmt == nullptr &&
3069 "No associated statement allowed for 'omp barrier' directive");
3070 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3071 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003072 case OMPD_taskwait:
3073 assert(ClausesWithImplicit.empty() &&
3074 "No clauses are allowed for 'omp taskwait' directive");
3075 assert(AStmt == nullptr &&
3076 "No associated statement allowed for 'omp taskwait' directive");
3077 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3078 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003079 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003080 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3081 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003082 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003083 case OMPD_flush:
3084 assert(AStmt == nullptr &&
3085 "No associated statement allowed for 'omp flush' directive");
3086 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3087 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003088 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003089 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3090 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003091 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003092 case OMPD_atomic:
3093 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3094 EndLoc);
3095 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003096 case OMPD_teams:
3097 Res =
3098 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3099 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003100 case OMPD_target:
3101 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3102 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003103 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003104 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003105 case OMPD_target_parallel:
3106 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3107 StartLoc, EndLoc);
3108 AllowedNameModifiers.push_back(OMPD_target);
3109 AllowedNameModifiers.push_back(OMPD_parallel);
3110 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003111 case OMPD_target_parallel_for:
3112 Res = ActOnOpenMPTargetParallelForDirective(
3113 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3114 AllowedNameModifiers.push_back(OMPD_target);
3115 AllowedNameModifiers.push_back(OMPD_parallel);
3116 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003117 case OMPD_cancellation_point:
3118 assert(ClausesWithImplicit.empty() &&
3119 "No clauses are allowed for 'omp cancellation point' directive");
3120 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3121 "cancellation point' directive");
3122 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3123 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003124 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003125 assert(AStmt == nullptr &&
3126 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003127 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3128 CancelRegion);
3129 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003130 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003131 case OMPD_target_data:
3132 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3133 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003134 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003135 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003136 case OMPD_target_enter_data:
3137 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003138 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003139 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3140 break;
Samuel Antao72590762016-01-19 20:04:50 +00003141 case OMPD_target_exit_data:
3142 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003143 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003144 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3145 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003146 case OMPD_taskloop:
3147 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3148 EndLoc, VarsWithInheritedDSA);
3149 AllowedNameModifiers.push_back(OMPD_taskloop);
3150 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003151 case OMPD_taskloop_simd:
3152 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3153 EndLoc, VarsWithInheritedDSA);
3154 AllowedNameModifiers.push_back(OMPD_taskloop);
3155 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003156 case OMPD_distribute:
3157 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3158 EndLoc, VarsWithInheritedDSA);
3159 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003160 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003161 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3162 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003163 AllowedNameModifiers.push_back(OMPD_target_update);
3164 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003165 case OMPD_distribute_parallel_for:
3166 Res = ActOnOpenMPDistributeParallelForDirective(
3167 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3168 AllowedNameModifiers.push_back(OMPD_parallel);
3169 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003170 case OMPD_distribute_parallel_for_simd:
3171 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3172 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3173 AllowedNameModifiers.push_back(OMPD_parallel);
3174 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003175 case OMPD_distribute_simd:
3176 Res = ActOnOpenMPDistributeSimdDirective(
3177 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3178 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003179 case OMPD_target_parallel_for_simd:
3180 Res = ActOnOpenMPTargetParallelForSimdDirective(
3181 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3182 AllowedNameModifiers.push_back(OMPD_target);
3183 AllowedNameModifiers.push_back(OMPD_parallel);
3184 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003185 case OMPD_target_simd:
3186 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3187 EndLoc, VarsWithInheritedDSA);
3188 AllowedNameModifiers.push_back(OMPD_target);
3189 break;
Kelvin Li02532872016-08-05 14:37:37 +00003190 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003191 Res = ActOnOpenMPTeamsDistributeDirective(
3192 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003193 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003194 case OMPD_teams_distribute_simd:
3195 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3196 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3197 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003198 case OMPD_teams_distribute_parallel_for_simd:
3199 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3200 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3201 AllowedNameModifiers.push_back(OMPD_parallel);
3202 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003203 case OMPD_teams_distribute_parallel_for:
3204 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3205 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3206 AllowedNameModifiers.push_back(OMPD_parallel);
3207 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003208 case OMPD_target_teams:
3209 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3210 EndLoc);
3211 AllowedNameModifiers.push_back(OMPD_target);
3212 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003213 case OMPD_target_teams_distribute:
3214 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3215 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3216 AllowedNameModifiers.push_back(OMPD_target);
3217 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003218 case OMPD_target_teams_distribute_parallel_for:
3219 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3220 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3221 AllowedNameModifiers.push_back(OMPD_target);
3222 AllowedNameModifiers.push_back(OMPD_parallel);
3223 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003224 case OMPD_target_teams_distribute_parallel_for_simd:
3225 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3226 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3227 AllowedNameModifiers.push_back(OMPD_target);
3228 AllowedNameModifiers.push_back(OMPD_parallel);
3229 break;
Kelvin Lida681182017-01-10 18:08:18 +00003230 case OMPD_target_teams_distribute_simd:
3231 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3232 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3233 AllowedNameModifiers.push_back(OMPD_target);
3234 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003235 case OMPD_declare_target:
3236 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003237 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003238 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003239 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003240 llvm_unreachable("OpenMP Directive is not allowed");
3241 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003242 llvm_unreachable("Unknown OpenMP directive");
3243 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003244
Alexey Bataev4acb8592014-07-07 13:01:15 +00003245 for (auto P : VarsWithInheritedDSA) {
3246 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3247 << P.first << P.second->getSourceRange();
3248 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003249 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3250
3251 if (!AllowedNameModifiers.empty())
3252 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3253 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003254
Alexey Bataeved09d242014-05-28 05:53:51 +00003255 if (ErrorFound)
3256 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003257 return Res;
3258}
3259
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003260Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3261 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003262 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003263 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3264 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003265 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003266 assert(Linears.size() == LinModifiers.size());
3267 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003268 if (!DG || DG.get().isNull())
3269 return DeclGroupPtrTy();
3270
3271 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003272 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003273 return DG;
3274 }
3275 auto *ADecl = DG.get().getSingleDecl();
3276 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3277 ADecl = FTD->getTemplatedDecl();
3278
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003279 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3280 if (!FD) {
3281 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003282 return DeclGroupPtrTy();
3283 }
3284
Alexey Bataev2af33e32016-04-07 12:45:37 +00003285 // OpenMP [2.8.2, declare simd construct, Description]
3286 // The parameter of the simdlen clause must be a constant positive integer
3287 // expression.
3288 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003289 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003290 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003291 // OpenMP [2.8.2, declare simd construct, Description]
3292 // The special this pointer can be used as if was one of the arguments to the
3293 // function in any of the linear, aligned, or uniform clauses.
3294 // The uniform clause declares one or more arguments to have an invariant
3295 // value for all concurrent invocations of the function in the execution of a
3296 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00003297 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3298 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003299 for (auto *E : Uniforms) {
3300 E = E->IgnoreParenImpCasts();
3301 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3302 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3303 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3304 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003305 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3306 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003307 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003308 }
3309 if (isa<CXXThisExpr>(E)) {
3310 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003311 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003312 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003313 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3314 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003315 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003316 // OpenMP [2.8.2, declare simd construct, Description]
3317 // The aligned clause declares that the object to which each list item points
3318 // is aligned to the number of bytes expressed in the optional parameter of
3319 // the aligned clause.
3320 // The special this pointer can be used as if was one of the arguments to the
3321 // function in any of the linear, aligned, or uniform clauses.
3322 // The type of list items appearing in the aligned clause must be array,
3323 // pointer, reference to array, or reference to pointer.
3324 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3325 Expr *AlignedThis = nullptr;
3326 for (auto *E : Aligneds) {
3327 E = E->IgnoreParenImpCasts();
3328 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3329 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3330 auto *CanonPVD = PVD->getCanonicalDecl();
3331 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3332 FD->getParamDecl(PVD->getFunctionScopeIndex())
3333 ->getCanonicalDecl() == CanonPVD) {
3334 // OpenMP [2.8.1, simd construct, Restrictions]
3335 // A list-item cannot appear in more than one aligned clause.
3336 if (AlignedArgs.count(CanonPVD) > 0) {
3337 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3338 << 1 << E->getSourceRange();
3339 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3340 diag::note_omp_explicit_dsa)
3341 << getOpenMPClauseName(OMPC_aligned);
3342 continue;
3343 }
3344 AlignedArgs[CanonPVD] = E;
3345 QualType QTy = PVD->getType()
3346 .getNonReferenceType()
3347 .getUnqualifiedType()
3348 .getCanonicalType();
3349 const Type *Ty = QTy.getTypePtrOrNull();
3350 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3351 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3352 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3353 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3354 }
3355 continue;
3356 }
3357 }
3358 if (isa<CXXThisExpr>(E)) {
3359 if (AlignedThis) {
3360 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3361 << 2 << E->getSourceRange();
3362 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3363 << getOpenMPClauseName(OMPC_aligned);
3364 }
3365 AlignedThis = E;
3366 continue;
3367 }
3368 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3369 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3370 }
3371 // The optional parameter of the aligned clause, alignment, must be a constant
3372 // positive integer expression. If no optional parameter is specified,
3373 // implementation-defined default alignments for SIMD instructions on the
3374 // target platforms are assumed.
3375 SmallVector<Expr *, 4> NewAligns;
3376 for (auto *E : Alignments) {
3377 ExprResult Align;
3378 if (E)
3379 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3380 NewAligns.push_back(Align.get());
3381 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003382 // OpenMP [2.8.2, declare simd construct, Description]
3383 // The linear clause declares one or more list items to be private to a SIMD
3384 // lane and to have a linear relationship with respect to the iteration space
3385 // of a loop.
3386 // The special this pointer can be used as if was one of the arguments to the
3387 // function in any of the linear, aligned, or uniform clauses.
3388 // When a linear-step expression is specified in a linear clause it must be
3389 // either a constant integer expression or an integer-typed parameter that is
3390 // specified in a uniform clause on the directive.
3391 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3392 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3393 auto MI = LinModifiers.begin();
3394 for (auto *E : Linears) {
3395 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3396 ++MI;
3397 E = E->IgnoreParenImpCasts();
3398 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3399 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3400 auto *CanonPVD = PVD->getCanonicalDecl();
3401 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3402 FD->getParamDecl(PVD->getFunctionScopeIndex())
3403 ->getCanonicalDecl() == CanonPVD) {
3404 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3405 // A list-item cannot appear in more than one linear clause.
3406 if (LinearArgs.count(CanonPVD) > 0) {
3407 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3408 << getOpenMPClauseName(OMPC_linear)
3409 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3410 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3411 diag::note_omp_explicit_dsa)
3412 << getOpenMPClauseName(OMPC_linear);
3413 continue;
3414 }
3415 // Each argument can appear in at most one uniform or linear clause.
3416 if (UniformedArgs.count(CanonPVD) > 0) {
3417 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3418 << getOpenMPClauseName(OMPC_linear)
3419 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3420 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3421 diag::note_omp_explicit_dsa)
3422 << getOpenMPClauseName(OMPC_uniform);
3423 continue;
3424 }
3425 LinearArgs[CanonPVD] = E;
3426 if (E->isValueDependent() || E->isTypeDependent() ||
3427 E->isInstantiationDependent() ||
3428 E->containsUnexpandedParameterPack())
3429 continue;
3430 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3431 PVD->getOriginalType());
3432 continue;
3433 }
3434 }
3435 if (isa<CXXThisExpr>(E)) {
3436 if (UniformedLinearThis) {
3437 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3438 << getOpenMPClauseName(OMPC_linear)
3439 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3440 << E->getSourceRange();
3441 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3442 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3443 : OMPC_linear);
3444 continue;
3445 }
3446 UniformedLinearThis = E;
3447 if (E->isValueDependent() || E->isTypeDependent() ||
3448 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3449 continue;
3450 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3451 E->getType());
3452 continue;
3453 }
3454 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3455 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3456 }
3457 Expr *Step = nullptr;
3458 Expr *NewStep = nullptr;
3459 SmallVector<Expr *, 4> NewSteps;
3460 for (auto *E : Steps) {
3461 // Skip the same step expression, it was checked already.
3462 if (Step == E || !E) {
3463 NewSteps.push_back(E ? NewStep : nullptr);
3464 continue;
3465 }
3466 Step = E;
3467 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3468 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3469 auto *CanonPVD = PVD->getCanonicalDecl();
3470 if (UniformedArgs.count(CanonPVD) == 0) {
3471 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3472 << Step->getSourceRange();
3473 } else if (E->isValueDependent() || E->isTypeDependent() ||
3474 E->isInstantiationDependent() ||
3475 E->containsUnexpandedParameterPack() ||
3476 CanonPVD->getType()->hasIntegerRepresentation())
3477 NewSteps.push_back(Step);
3478 else {
3479 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3480 << Step->getSourceRange();
3481 }
3482 continue;
3483 }
3484 NewStep = Step;
3485 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3486 !Step->isInstantiationDependent() &&
3487 !Step->containsUnexpandedParameterPack()) {
3488 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3489 .get();
3490 if (NewStep)
3491 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3492 }
3493 NewSteps.push_back(NewStep);
3494 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003495 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3496 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003497 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003498 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3499 const_cast<Expr **>(Linears.data()), Linears.size(),
3500 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3501 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003502 ADecl->addAttr(NewAttr);
3503 return ConvertDeclToDeclGroup(ADecl);
3504}
3505
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003506StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3507 Stmt *AStmt,
3508 SourceLocation StartLoc,
3509 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003510 if (!AStmt)
3511 return StmtError();
3512
Alexey Bataev9959db52014-05-06 10:08:46 +00003513 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3514 // 1.2.2 OpenMP Language Terminology
3515 // Structured block - An executable statement with a single entry at the
3516 // top and a single exit at the bottom.
3517 // The point of exit cannot be a branch out of the structured block.
3518 // longjmp() and throw() must not violate the entry/exit criteria.
3519 CS->getCapturedDecl()->setNothrow();
3520
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003521 getCurFunction()->setHasBranchProtectedScope();
3522
Alexey Bataev25e5b442015-09-15 12:52:43 +00003523 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3524 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003525}
3526
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003527namespace {
3528/// \brief Helper class for checking canonical form of the OpenMP loops and
3529/// extracting iteration space of each loop in the loop nest, that will be used
3530/// for IR generation.
3531class OpenMPIterationSpaceChecker {
3532 /// \brief Reference to Sema.
3533 Sema &SemaRef;
3534 /// \brief A location for diagnostics (when there is no some better location).
3535 SourceLocation DefaultLoc;
3536 /// \brief A location for diagnostics (when increment is not compatible).
3537 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003538 /// \brief A source location for referring to loop init later.
3539 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003540 /// \brief A source location for referring to condition later.
3541 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003542 /// \brief A source location for referring to increment later.
3543 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003544 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003545 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003546 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003547 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003548 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003549 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003550 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003551 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003552 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003553 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003554 /// \brief This flag is true when condition is one of:
3555 /// Var < UB
3556 /// Var <= UB
3557 /// UB > Var
3558 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003559 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003560 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003561 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003562 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003563 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003564
3565public:
3566 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003567 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003568 /// \brief Check init-expr for canonical loop form and save loop counter
3569 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003570 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003571 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3572 /// for less/greater and for strict/non-strict comparison.
3573 bool CheckCond(Expr *S);
3574 /// \brief Check incr-expr for canonical loop form and return true if it
3575 /// does not conform, otherwise save loop step (#Step).
3576 bool CheckInc(Expr *S);
3577 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003578 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003579 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003580 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003581 /// \brief Source range of the loop init.
3582 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3583 /// \brief Source range of the loop condition.
3584 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3585 /// \brief Source range of the loop increment.
3586 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3587 /// \brief True if the step should be subtracted.
3588 bool ShouldSubtractStep() const { return SubtractStep; }
3589 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003590 Expr *
3591 BuildNumIterations(Scope *S, const bool LimitedType,
3592 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003593 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003594 Expr *BuildPreCond(Scope *S, Expr *Cond,
3595 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003596 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003597 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3598 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003599 /// \brief Build reference expression to the private counter be used for
3600 /// codegen.
3601 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003602 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003603 Expr *BuildCounterInit() const;
3604 /// \brief Build step of the counter be used for codegen.
3605 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003606 /// \brief Return true if any expression is dependent.
3607 bool Dependent() const;
3608
3609private:
3610 /// \brief Check the right-hand side of an assignment in the increment
3611 /// expression.
3612 bool CheckIncRHS(Expr *RHS);
3613 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003614 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003615 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003616 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003617 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003618 /// \brief Helper to set loop increment.
3619 bool SetStep(Expr *NewStep, bool Subtract);
3620};
3621
3622bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003623 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003624 assert(!LB && !UB && !Step);
3625 return false;
3626 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003627 return LCDecl->getType()->isDependentType() ||
3628 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3629 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003630}
3631
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003632bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3633 Expr *NewLCRefExpr,
3634 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003635 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003636 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003637 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003638 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003639 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003640 LCDecl = getCanonicalDecl(NewLCDecl);
3641 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003642 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3643 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003644 if ((Ctor->isCopyOrMoveConstructor() ||
3645 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3646 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003647 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003648 LB = NewLB;
3649 return false;
3650}
3651
3652bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003653 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003654 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003655 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3656 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003657 if (!NewUB)
3658 return true;
3659 UB = NewUB;
3660 TestIsLessOp = LessOp;
3661 TestIsStrictOp = StrictOp;
3662 ConditionSrcRange = SR;
3663 ConditionLoc = SL;
3664 return false;
3665}
3666
3667bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3668 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003669 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003670 if (!NewStep)
3671 return true;
3672 if (!NewStep->isValueDependent()) {
3673 // Check that the step is integer expression.
3674 SourceLocation StepLoc = NewStep->getLocStart();
Alexey Bataev5372fb82017-08-31 23:06:52 +00003675 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3676 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003677 if (Val.isInvalid())
3678 return true;
3679 NewStep = Val.get();
3680
3681 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3682 // If test-expr is of form var relational-op b and relational-op is < or
3683 // <= then incr-expr must cause var to increase on each iteration of the
3684 // loop. If test-expr is of form var relational-op b and relational-op is
3685 // > or >= then incr-expr must cause var to decrease on each iteration of
3686 // the loop.
3687 // If test-expr is of form b relational-op var and relational-op is < or
3688 // <= then incr-expr must cause var to decrease on each iteration of the
3689 // loop. If test-expr is of form b relational-op var and relational-op is
3690 // > or >= then incr-expr must cause var to increase on each iteration of
3691 // the loop.
3692 llvm::APSInt Result;
3693 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3694 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3695 bool IsConstNeg =
3696 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003697 bool IsConstPos =
3698 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003699 bool IsConstZero = IsConstant && !Result.getBoolValue();
3700 if (UB && (IsConstZero ||
3701 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003702 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003703 SemaRef.Diag(NewStep->getExprLoc(),
3704 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003705 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003706 SemaRef.Diag(ConditionLoc,
3707 diag::note_omp_loop_cond_requres_compatible_incr)
3708 << TestIsLessOp << ConditionSrcRange;
3709 return true;
3710 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003711 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003712 NewStep =
3713 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3714 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003715 Subtract = !Subtract;
3716 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003717 }
3718
3719 Step = NewStep;
3720 SubtractStep = Subtract;
3721 return false;
3722}
3723
Alexey Bataev9c821032015-04-30 04:23:23 +00003724bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003725 // Check init-expr for canonical loop form and save loop counter
3726 // variable - #Var and its initialization value - #LB.
3727 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3728 // var = lb
3729 // integer-type var = lb
3730 // random-access-iterator-type var = lb
3731 // pointer-type var = lb
3732 //
3733 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003734 if (EmitDiags) {
3735 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3736 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003737 return true;
3738 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003739 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3740 if (!ExprTemp->cleanupsHaveSideEffects())
3741 S = ExprTemp->getSubExpr();
3742
Alexander Musmana5f070a2014-10-01 06:03:56 +00003743 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003744 if (Expr *E = dyn_cast<Expr>(S))
3745 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003746 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003747 if (BO->getOpcode() == BO_Assign) {
3748 auto *LHS = BO->getLHS()->IgnoreParens();
3749 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3750 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3751 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3752 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3753 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3754 }
3755 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3756 if (ME->isArrow() &&
3757 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3758 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3759 }
3760 }
David Majnemer9d168222016-08-05 17:44:54 +00003761 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003762 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003763 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003764 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003765 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003766 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003767 SemaRef.Diag(S->getLocStart(),
3768 diag::ext_omp_loop_not_canonical_init)
3769 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003770 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003771 }
3772 }
3773 }
David Majnemer9d168222016-08-05 17:44:54 +00003774 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003775 if (CE->getOperator() == OO_Equal) {
3776 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003777 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003778 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3779 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3780 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3781 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3782 }
3783 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3784 if (ME->isArrow() &&
3785 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3786 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3787 }
3788 }
3789 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003790
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003791 if (Dependent() || SemaRef.CurContext->isDependentContext())
3792 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003793 if (EmitDiags) {
3794 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3795 << S->getSourceRange();
3796 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003797 return true;
3798}
3799
Alexey Bataev23b69422014-06-18 07:08:49 +00003800/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003801/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003802static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003803 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003804 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003805 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003806 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3807 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003808 if ((Ctor->isCopyOrMoveConstructor() ||
3809 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3810 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003811 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003812 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003813 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003814 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003815 }
3816 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3817 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3818 return getCanonicalDecl(ME->getMemberDecl());
3819 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003820}
3821
3822bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3823 // Check test-expr for canonical form, save upper-bound UB, flags for
3824 // less/greater and for strict/non-strict comparison.
3825 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3826 // var relational-op b
3827 // b relational-op var
3828 //
3829 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003830 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003831 return true;
3832 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003833 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003834 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003835 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003836 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003837 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003838 return SetUB(BO->getRHS(),
3839 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3840 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3841 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003842 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003843 return SetUB(BO->getLHS(),
3844 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3845 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3846 BO->getSourceRange(), BO->getOperatorLoc());
3847 }
David Majnemer9d168222016-08-05 17:44:54 +00003848 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003849 if (CE->getNumArgs() == 2) {
3850 auto Op = CE->getOperator();
3851 switch (Op) {
3852 case OO_Greater:
3853 case OO_GreaterEqual:
3854 case OO_Less:
3855 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003856 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003857 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3858 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3859 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003860 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003861 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3862 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3863 CE->getOperatorLoc());
3864 break;
3865 default:
3866 break;
3867 }
3868 }
3869 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003870 if (Dependent() || SemaRef.CurContext->isDependentContext())
3871 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003872 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003873 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003874 return true;
3875}
3876
3877bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3878 // RHS of canonical loop form increment can be:
3879 // var + incr
3880 // incr + var
3881 // var - incr
3882 //
3883 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003884 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003885 if (BO->isAdditiveOp()) {
3886 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003887 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003888 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003889 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003890 return SetStep(BO->getLHS(), false);
3891 }
David Majnemer9d168222016-08-05 17:44:54 +00003892 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003893 bool IsAdd = CE->getOperator() == OO_Plus;
3894 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003895 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003896 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003897 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003898 return SetStep(CE->getArg(0), false);
3899 }
3900 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003901 if (Dependent() || SemaRef.CurContext->isDependentContext())
3902 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003903 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003904 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003905 return true;
3906}
3907
3908bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3909 // Check incr-expr for canonical loop form and return true if it
3910 // does not conform.
3911 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3912 // ++var
3913 // var++
3914 // --var
3915 // var--
3916 // var += incr
3917 // var -= incr
3918 // var = var + incr
3919 // var = incr + var
3920 // var = var - incr
3921 //
3922 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003923 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003924 return true;
3925 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003926 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3927 if (!ExprTemp->cleanupsHaveSideEffects())
3928 S = ExprTemp->getSubExpr();
3929
Alexander Musmana5f070a2014-10-01 06:03:56 +00003930 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003931 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003932 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003933 if (UO->isIncrementDecrementOp() &&
3934 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003935 return SetStep(SemaRef
3936 .ActOnIntegerConstant(UO->getLocStart(),
3937 (UO->isDecrementOp() ? -1 : 1))
3938 .get(),
3939 false);
3940 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003941 switch (BO->getOpcode()) {
3942 case BO_AddAssign:
3943 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003944 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003945 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3946 break;
3947 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003948 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003949 return CheckIncRHS(BO->getRHS());
3950 break;
3951 default:
3952 break;
3953 }
David Majnemer9d168222016-08-05 17:44:54 +00003954 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003955 switch (CE->getOperator()) {
3956 case OO_PlusPlus:
3957 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003958 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003959 return SetStep(SemaRef
3960 .ActOnIntegerConstant(
3961 CE->getLocStart(),
3962 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3963 .get(),
3964 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003965 break;
3966 case OO_PlusEqual:
3967 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003968 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003969 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3970 break;
3971 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003972 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003973 return CheckIncRHS(CE->getArg(1));
3974 break;
3975 default:
3976 break;
3977 }
3978 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003979 if (Dependent() || SemaRef.CurContext->isDependentContext())
3980 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003981 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003982 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003983 return true;
3984}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003985
Alexey Bataev5a3af132016-03-29 08:58:54 +00003986static ExprResult
3987tryBuildCapture(Sema &SemaRef, Expr *Capture,
3988 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003989 if (SemaRef.CurContext->isDependentContext())
3990 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003991 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3992 return SemaRef.PerformImplicitConversion(
3993 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3994 /*AllowExplicit=*/true);
3995 auto I = Captures.find(Capture);
3996 if (I != Captures.end())
3997 return buildCapture(SemaRef, Capture, I->second);
3998 DeclRefExpr *Ref = nullptr;
3999 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4000 Captures[Capture] = Ref;
4001 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004002}
4003
Alexander Musmana5f070a2014-10-01 06:03:56 +00004004/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004005Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
4006 Scope *S, const bool LimitedType,
4007 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004008 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004009 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004010 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004011 SemaRef.getLangOpts().CPlusPlus) {
4012 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004013 auto *UBExpr = TestIsLessOp ? UB : LB;
4014 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004015 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4016 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004017 if (!Upper || !Lower)
4018 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004019
4020 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4021
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004022 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004023 // BuildBinOp already emitted error, this one is to point user to upper
4024 // and lower bound, and to tell what is passed to 'operator-'.
4025 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
4026 << Upper->getSourceRange() << Lower->getSourceRange();
4027 return nullptr;
4028 }
4029 }
4030
4031 if (!Diff.isUsable())
4032 return nullptr;
4033
4034 // Upper - Lower [- 1]
4035 if (TestIsStrictOp)
4036 Diff = SemaRef.BuildBinOp(
4037 S, DefaultLoc, BO_Sub, Diff.get(),
4038 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4039 if (!Diff.isUsable())
4040 return nullptr;
4041
4042 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00004043 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
4044 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004045 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004046 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004047 if (!Diff.isUsable())
4048 return nullptr;
4049
4050 // Parentheses (for dumping/debugging purposes only).
4051 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4052 if (!Diff.isUsable())
4053 return nullptr;
4054
4055 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004056 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004057 if (!Diff.isUsable())
4058 return nullptr;
4059
Alexander Musman174b3ca2014-10-06 11:16:29 +00004060 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004061 QualType Type = Diff.get()->getType();
4062 auto &C = SemaRef.Context;
4063 bool UseVarType = VarType->hasIntegerRepresentation() &&
4064 C.getTypeSize(Type) > C.getTypeSize(VarType);
4065 if (!Type->isIntegerType() || UseVarType) {
4066 unsigned NewSize =
4067 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4068 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4069 : Type->hasSignedIntegerRepresentation();
4070 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004071 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4072 Diff = SemaRef.PerformImplicitConversion(
4073 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4074 if (!Diff.isUsable())
4075 return nullptr;
4076 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004077 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004078 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004079 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4080 if (NewSize != C.getTypeSize(Type)) {
4081 if (NewSize < C.getTypeSize(Type)) {
4082 assert(NewSize == 64 && "incorrect loop var size");
4083 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4084 << InitSrcRange << ConditionSrcRange;
4085 }
4086 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004087 NewSize, Type->hasSignedIntegerRepresentation() ||
4088 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004089 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4090 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4091 Sema::AA_Converting, true);
4092 if (!Diff.isUsable())
4093 return nullptr;
4094 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004095 }
4096 }
4097
Alexander Musmana5f070a2014-10-01 06:03:56 +00004098 return Diff.get();
4099}
4100
Alexey Bataev5a3af132016-03-29 08:58:54 +00004101Expr *OpenMPIterationSpaceChecker::BuildPreCond(
4102 Scope *S, Expr *Cond,
4103 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004104 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4105 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4106 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004107
Alexey Bataev5a3af132016-03-29 08:58:54 +00004108 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
4109 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
4110 if (!NewLB.isUsable() || !NewUB.isUsable())
4111 return nullptr;
4112
Alexey Bataev62dbb972015-04-22 11:59:37 +00004113 auto CondExpr = SemaRef.BuildBinOp(
4114 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
4115 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004116 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004117 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004118 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4119 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004120 CondExpr = SemaRef.PerformImplicitConversion(
4121 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4122 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004123 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004124 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4125 // Otherwise use original loop conditon and evaluate it in runtime.
4126 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4127}
4128
Alexander Musmana5f070a2014-10-01 06:03:56 +00004129/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004130DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004131 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004132 auto *VD = dyn_cast<VarDecl>(LCDecl);
4133 if (!VD) {
4134 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
4135 auto *Ref = buildDeclRefExpr(
4136 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004137 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4138 // If the loop control decl is explicitly marked as private, do not mark it
4139 // as captured again.
4140 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4141 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004142 return Ref;
4143 }
4144 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004145 DefaultLoc);
4146}
4147
4148Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004149 if (LCDecl && !LCDecl->isInvalidDecl()) {
4150 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00004151 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004152 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
4153 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004154 if (PrivateVar->isInvalidDecl())
4155 return nullptr;
4156 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4157 }
4158 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004159}
4160
Samuel Antao4c8035b2016-12-12 18:00:20 +00004161/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004162Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4163
4164/// \brief Build step of the counter be used for codegen.
4165Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4166
4167/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004168struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004169 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004170 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004171 /// \brief This expression calculates the number of iterations in the loop.
4172 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004173 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004174 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004175 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00004176 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004177 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004178 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004179 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004180 /// \brief This is step for the #CounterVar used to generate its update:
4181 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004182 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004183 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004184 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004185 /// \brief Source range of the loop init.
4186 SourceRange InitSrcRange;
4187 /// \brief Source range of the loop condition.
4188 SourceRange CondSrcRange;
4189 /// \brief Source range of the loop increment.
4190 SourceRange IncSrcRange;
4191};
4192
Alexey Bataev23b69422014-06-18 07:08:49 +00004193} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004194
Alexey Bataev9c821032015-04-30 04:23:23 +00004195void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4196 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4197 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004198 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4199 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004200 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4201 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004202 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4203 if (auto *D = ISC.GetLoopDecl()) {
4204 auto *VD = dyn_cast<VarDecl>(D);
4205 if (!VD) {
4206 if (auto *Private = IsOpenMPCapturedDecl(D))
4207 VD = Private;
4208 else {
4209 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4210 /*WithInit=*/false);
4211 VD = cast<VarDecl>(Ref->getDecl());
4212 }
4213 }
4214 DSAStack->addLoopControlVariable(D, VD);
4215 }
4216 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004217 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004218 }
4219}
4220
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004221/// \brief Called on a for stmt to check and extract its iteration space
4222/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00004223static bool CheckOpenMPIterationSpace(
4224 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4225 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004226 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004227 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004228 LoopIterationSpace &ResultIterSpace,
4229 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004230 // OpenMP [2.6, Canonical Loop Form]
4231 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004232 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004233 if (!For) {
4234 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004235 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4236 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4237 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4238 if (NestedLoopCount > 1) {
4239 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4240 SemaRef.Diag(DSA.getConstructLoc(),
4241 diag::note_omp_collapse_ordered_expr)
4242 << 2 << CollapseLoopCountExpr->getSourceRange()
4243 << OrderedLoopCountExpr->getSourceRange();
4244 else if (CollapseLoopCountExpr)
4245 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4246 diag::note_omp_collapse_ordered_expr)
4247 << 0 << CollapseLoopCountExpr->getSourceRange();
4248 else
4249 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4250 diag::note_omp_collapse_ordered_expr)
4251 << 1 << OrderedLoopCountExpr->getSourceRange();
4252 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004253 return true;
4254 }
4255 assert(For->getBody());
4256
4257 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4258
4259 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00004260 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004261 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004262 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004263
4264 bool HasErrors = false;
4265
4266 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004267 if (auto *LCDecl = ISC.GetLoopDecl()) {
4268 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004269
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004270 // OpenMP [2.6, Canonical Loop Form]
4271 // Var is one of the following:
4272 // A variable of signed or unsigned integer type.
4273 // For C++, a variable of a random access iterator type.
4274 // For C, a variable of a pointer type.
4275 auto VarType = LCDecl->getType().getNonReferenceType();
4276 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4277 !VarType->isPointerType() &&
4278 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4279 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4280 << SemaRef.getLangOpts().CPlusPlus;
4281 HasErrors = true;
4282 }
4283
4284 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4285 // a Construct
4286 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4287 // parallel for construct is (are) private.
4288 // The loop iteration variable in the associated for-loop of a simd
4289 // construct with just one associated for-loop is linear with a
4290 // constant-linear-step that is the increment of the associated for-loop.
4291 // Exclude loop var from the list of variables with implicitly defined data
4292 // sharing attributes.
4293 VarsWithImplicitDSA.erase(LCDecl);
4294
4295 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4296 // in a Construct, C/C++].
4297 // The loop iteration variable in the associated for-loop of a simd
4298 // construct with just one associated for-loop may be listed in a linear
4299 // clause with a constant-linear-step that is the increment of the
4300 // associated for-loop.
4301 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4302 // parallel for construct may be listed in a private or lastprivate clause.
4303 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4304 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4305 // declared in the loop and it is predetermined as a private.
4306 auto PredeterminedCKind =
4307 isOpenMPSimdDirective(DKind)
4308 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4309 : OMPC_private;
4310 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4311 DVar.CKind != PredeterminedCKind) ||
4312 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4313 isOpenMPDistributeDirective(DKind)) &&
4314 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4315 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4316 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4317 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4318 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4319 << getOpenMPClauseName(PredeterminedCKind);
4320 if (DVar.RefExpr == nullptr)
4321 DVar.CKind = PredeterminedCKind;
4322 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4323 HasErrors = true;
4324 } else if (LoopDeclRefExpr != nullptr) {
4325 // Make the loop iteration variable private (for worksharing constructs),
4326 // linear (for simd directives with the only one associated loop) or
4327 // lastprivate (for simd directives with several collapsed or ordered
4328 // loops).
4329 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004330 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4331 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004332 /*FromParent=*/false);
4333 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4334 }
4335
4336 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4337
4338 // Check test-expr.
4339 HasErrors |= ISC.CheckCond(For->getCond());
4340
4341 // Check incr-expr.
4342 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004343 }
4344
Alexander Musmana5f070a2014-10-01 06:03:56 +00004345 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004346 return HasErrors;
4347
Alexander Musmana5f070a2014-10-01 06:03:56 +00004348 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004349 ResultIterSpace.PreCond =
4350 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00004351 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004352 DSA.getCurScope(),
4353 (isOpenMPWorksharingDirective(DKind) ||
4354 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4355 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004356 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00004357 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004358 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4359 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4360 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4361 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4362 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4363 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4364
Alexey Bataev62dbb972015-04-22 11:59:37 +00004365 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4366 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004367 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004368 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004369 ResultIterSpace.CounterInit == nullptr ||
4370 ResultIterSpace.CounterStep == nullptr);
4371
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004372 return HasErrors;
4373}
4374
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004375/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004376static ExprResult
4377BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4378 ExprResult Start,
4379 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004380 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004381 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4382 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004383 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004384 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004385 VarRef.get()->getType())) {
4386 NewStart = SemaRef.PerformImplicitConversion(
4387 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4388 /*AllowExplicit=*/true);
4389 if (!NewStart.isUsable())
4390 return ExprError();
4391 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004392
4393 auto Init =
4394 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4395 return Init;
4396}
4397
Alexander Musmana5f070a2014-10-01 06:03:56 +00004398/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004399static ExprResult
4400BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4401 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4402 ExprResult Step, bool Subtract,
4403 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004404 // Add parentheses (for debugging purposes only).
4405 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4406 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4407 !Step.isUsable())
4408 return ExprError();
4409
Alexey Bataev5a3af132016-03-29 08:58:54 +00004410 ExprResult NewStep = Step;
4411 if (Captures)
4412 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004413 if (NewStep.isInvalid())
4414 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004415 ExprResult Update =
4416 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004417 if (!Update.isUsable())
4418 return ExprError();
4419
Alexey Bataevc0214e02016-02-16 12:13:49 +00004420 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4421 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004422 ExprResult NewStart = Start;
4423 if (Captures)
4424 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004425 if (NewStart.isInvalid())
4426 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004427
Alexey Bataevc0214e02016-02-16 12:13:49 +00004428 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4429 ExprResult SavedUpdate = Update;
4430 ExprResult UpdateVal;
4431 if (VarRef.get()->getType()->isOverloadableType() ||
4432 NewStart.get()->getType()->isOverloadableType() ||
4433 Update.get()->getType()->isOverloadableType()) {
4434 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4435 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4436 Update =
4437 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4438 if (Update.isUsable()) {
4439 UpdateVal =
4440 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4441 VarRef.get(), SavedUpdate.get());
4442 if (UpdateVal.isUsable()) {
4443 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4444 UpdateVal.get());
4445 }
4446 }
4447 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4448 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004449
Alexey Bataevc0214e02016-02-16 12:13:49 +00004450 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4451 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4452 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4453 NewStart.get(), SavedUpdate.get());
4454 if (!Update.isUsable())
4455 return ExprError();
4456
Alexey Bataev11481f52016-02-17 10:29:05 +00004457 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4458 VarRef.get()->getType())) {
4459 Update = SemaRef.PerformImplicitConversion(
4460 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4461 if (!Update.isUsable())
4462 return ExprError();
4463 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004464
4465 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4466 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004467 return Update;
4468}
4469
4470/// \brief Convert integer expression \a E to make it have at least \a Bits
4471/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004472static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004473 if (E == nullptr)
4474 return ExprError();
4475 auto &C = SemaRef.Context;
4476 QualType OldType = E->getType();
4477 unsigned HasBits = C.getTypeSize(OldType);
4478 if (HasBits >= Bits)
4479 return ExprResult(E);
4480 // OK to convert to signed, because new type has more bits than old.
4481 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4482 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4483 true);
4484}
4485
4486/// \brief Check if the given expression \a E is a constant integer that fits
4487/// into \a Bits bits.
4488static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4489 if (E == nullptr)
4490 return false;
4491 llvm::APSInt Result;
4492 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4493 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4494 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004495}
4496
Alexey Bataev5a3af132016-03-29 08:58:54 +00004497/// Build preinits statement for the given declarations.
4498static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00004499 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004500 if (!PreInits.empty()) {
4501 return new (Context) DeclStmt(
4502 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4503 SourceLocation(), SourceLocation());
4504 }
4505 return nullptr;
4506}
4507
4508/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00004509static Stmt *
4510buildPreInits(ASTContext &Context,
4511 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004512 if (!Captures.empty()) {
4513 SmallVector<Decl *, 16> PreInits;
4514 for (auto &Pair : Captures)
4515 PreInits.push_back(Pair.second->getDecl());
4516 return buildPreInits(Context, PreInits);
4517 }
4518 return nullptr;
4519}
4520
4521/// Build postupdate expression for the given list of postupdates expressions.
4522static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4523 Expr *PostUpdate = nullptr;
4524 if (!PostUpdates.empty()) {
4525 for (auto *E : PostUpdates) {
4526 Expr *ConvE = S.BuildCStyleCastExpr(
4527 E->getExprLoc(),
4528 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4529 E->getExprLoc(), E)
4530 .get();
4531 PostUpdate = PostUpdate
4532 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4533 PostUpdate, ConvE)
4534 .get()
4535 : ConvE;
4536 }
4537 }
4538 return PostUpdate;
4539}
4540
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004541/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004542/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4543/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004544static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004545CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4546 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4547 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004548 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004549 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004550 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004551 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004552 // Found 'collapse' clause - calculate collapse number.
4553 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004554 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004555 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004556 }
4557 if (OrderedLoopCountExpr) {
4558 // Found 'ordered' clause - calculate collapse number.
4559 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004560 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4561 if (Result.getLimitedValue() < NestedLoopCount) {
4562 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4563 diag::err_omp_wrong_ordered_loop_count)
4564 << OrderedLoopCountExpr->getSourceRange();
4565 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4566 diag::note_collapse_loop_count)
4567 << CollapseLoopCountExpr->getSourceRange();
4568 }
4569 NestedLoopCount = Result.getLimitedValue();
4570 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004571 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004572 // This is helper routine for loop directives (e.g., 'for', 'simd',
4573 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004574 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004575 SmallVector<LoopIterationSpace, 4> IterSpaces;
4576 IterSpaces.resize(NestedLoopCount);
4577 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004578 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004579 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004580 NestedLoopCount, CollapseLoopCountExpr,
4581 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004582 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004583 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004584 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004585 // OpenMP [2.8.1, simd construct, Restrictions]
4586 // All loops associated with the construct must be perfectly nested; that
4587 // is, there must be no intervening code nor any OpenMP directive between
4588 // any two loops.
4589 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004590 }
4591
Alexander Musmana5f070a2014-10-01 06:03:56 +00004592 Built.clear(/* size */ NestedLoopCount);
4593
4594 if (SemaRef.CurContext->isDependentContext())
4595 return NestedLoopCount;
4596
4597 // An example of what is generated for the following code:
4598 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004599 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004600 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004601 // for (k = 0; k < NK; ++k)
4602 // for (j = J0; j < NJ; j+=2) {
4603 // <loop body>
4604 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004605 //
4606 // We generate the code below.
4607 // Note: the loop body may be outlined in CodeGen.
4608 // Note: some counters may be C++ classes, operator- is used to find number of
4609 // iterations and operator+= to calculate counter value.
4610 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4611 // or i64 is currently supported).
4612 //
4613 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4614 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4615 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4616 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4617 // // similar updates for vars in clauses (e.g. 'linear')
4618 // <loop body (using local i and j)>
4619 // }
4620 // i = NI; // assign final values of counters
4621 // j = NJ;
4622 //
4623
4624 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4625 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004626 // Precondition tests if there is at least one iteration (all conditions are
4627 // true).
4628 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004629 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004630 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004631 32 /* Bits */, SemaRef
4632 .PerformImplicitConversion(
4633 N0->IgnoreImpCasts(), N0->getType(),
4634 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004635 .get(),
4636 SemaRef);
4637 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004638 64 /* Bits */, SemaRef
4639 .PerformImplicitConversion(
4640 N0->IgnoreImpCasts(), N0->getType(),
4641 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004642 .get(),
4643 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004644
4645 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4646 return NestedLoopCount;
4647
4648 auto &C = SemaRef.Context;
4649 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4650
4651 Scope *CurScope = DSA.getCurScope();
4652 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004653 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004654 PreCond =
4655 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4656 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004657 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004658 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004659 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004660 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4661 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004662 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004663 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004664 SemaRef
4665 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4666 Sema::AA_Converting,
4667 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004668 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004669 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004670 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004671 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004672 SemaRef
4673 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4674 Sema::AA_Converting,
4675 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004676 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004677 }
4678
4679 // Choose either the 32-bit or 64-bit version.
4680 ExprResult LastIteration = LastIteration64;
4681 if (LastIteration32.isUsable() &&
4682 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4683 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4684 FitsInto(
4685 32 /* Bits */,
4686 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4687 LastIteration64.get(), SemaRef)))
4688 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004689 QualType VType = LastIteration.get()->getType();
4690 QualType RealVType = VType;
4691 QualType StrideVType = VType;
4692 if (isOpenMPTaskLoopDirective(DKind)) {
4693 VType =
4694 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4695 StrideVType =
4696 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4697 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004698
4699 if (!LastIteration.isUsable())
4700 return 0;
4701
4702 // Save the number of iterations.
4703 ExprResult NumIterations = LastIteration;
4704 {
4705 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004706 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4707 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004708 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4709 if (!LastIteration.isUsable())
4710 return 0;
4711 }
4712
4713 // Calculate the last iteration number beforehand instead of doing this on
4714 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4715 llvm::APSInt Result;
4716 bool IsConstant =
4717 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4718 ExprResult CalcLastIteration;
4719 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004720 ExprResult SaveRef =
4721 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004722 LastIteration = SaveRef;
4723
4724 // Prepare SaveRef + 1.
4725 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004726 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004727 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4728 if (!NumIterations.isUsable())
4729 return 0;
4730 }
4731
4732 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4733
David Majnemer9d168222016-08-05 17:44:54 +00004734 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004735 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004736 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4737 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004738 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004739 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4740 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004741 SemaRef.AddInitializerToDecl(LBDecl,
4742 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4743 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004744
4745 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004746 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4747 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004748 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004749 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004750
4751 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4752 // This will be used to implement clause 'lastprivate'.
4753 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004754 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4755 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004756 SemaRef.AddInitializerToDecl(ILDecl,
4757 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4758 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004759
4760 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004761 VarDecl *STDecl =
4762 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4763 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004764 SemaRef.AddInitializerToDecl(STDecl,
4765 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4766 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004767
4768 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004769 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004770 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4771 UB.get(), LastIteration.get());
4772 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4773 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4774 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4775 CondOp.get());
4776 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004777
4778 // If we have a combined directive that combines 'distribute', 'for' or
4779 // 'simd' we need to be able to access the bounds of the schedule of the
4780 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4781 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4782 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004783
Carlo Bertolliffafe102017-04-20 00:39:39 +00004784 // Lower bound variable, initialized with zero.
4785 VarDecl *CombLBDecl =
4786 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4787 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4788 SemaRef.AddInitializerToDecl(
4789 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4790 /*DirectInit*/ false);
4791
4792 // Upper bound variable, initialized with last iteration number.
4793 VarDecl *CombUBDecl =
4794 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4795 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4796 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4797 /*DirectInit*/ false);
4798
4799 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4800 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4801 ExprResult CombCondOp =
4802 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4803 LastIteration.get(), CombUB.get());
4804 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4805 CombCondOp.get());
4806 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4807
4808 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004809 // We expect to have at least 2 more parameters than the 'parallel'
4810 // directive does - the lower and upper bounds of the previous schedule.
4811 assert(CD->getNumParams() >= 4 &&
4812 "Unexpected number of parameters in loop combined directive");
4813
4814 // Set the proper type for the bounds given what we learned from the
4815 // enclosed loops.
4816 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4817 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4818
4819 // Previous lower and upper bounds are obtained from the region
4820 // parameters.
4821 PrevLB =
4822 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4823 PrevUB =
4824 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4825 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004826 }
4827
4828 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004829 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004830 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004831 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004832 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4833 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004834 Expr *RHS =
4835 (isOpenMPWorksharingDirective(DKind) ||
4836 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4837 ? LB.get()
4838 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004839 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4840 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004841
4842 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4843 Expr *CombRHS =
4844 (isOpenMPWorksharingDirective(DKind) ||
4845 isOpenMPTaskLoopDirective(DKind) ||
4846 isOpenMPDistributeDirective(DKind))
4847 ? CombLB.get()
4848 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4849 CombInit =
4850 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4851 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4852 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004853 }
4854
Alexander Musmanc6388682014-12-15 07:07:06 +00004855 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004856 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004857 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004858 (isOpenMPWorksharingDirective(DKind) ||
4859 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004860 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4861 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4862 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004863 ExprResult CombCond;
4864 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4865 CombCond =
4866 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4867 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004868 // Loop increment (IV = IV + 1)
4869 SourceLocation IncLoc;
4870 ExprResult Inc =
4871 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4872 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4873 if (!Inc.isUsable())
4874 return 0;
4875 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004876 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4877 if (!Inc.isUsable())
4878 return 0;
4879
4880 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4881 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004882 // In combined construct, add combined version that use CombLB and CombUB
4883 // base variables for the update
4884 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004885 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4886 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004887 // LB + ST
4888 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4889 if (!NextLB.isUsable())
4890 return 0;
4891 // LB = LB + ST
4892 NextLB =
4893 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4894 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4895 if (!NextLB.isUsable())
4896 return 0;
4897 // UB + ST
4898 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4899 if (!NextUB.isUsable())
4900 return 0;
4901 // UB = UB + ST
4902 NextUB =
4903 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4904 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4905 if (!NextUB.isUsable())
4906 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004907 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4908 CombNextLB =
4909 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4910 if (!NextLB.isUsable())
4911 return 0;
4912 // LB = LB + ST
4913 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4914 CombNextLB.get());
4915 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4916 if (!CombNextLB.isUsable())
4917 return 0;
4918 // UB + ST
4919 CombNextUB =
4920 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4921 if (!CombNextUB.isUsable())
4922 return 0;
4923 // UB = UB + ST
4924 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4925 CombNextUB.get());
4926 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4927 if (!CombNextUB.isUsable())
4928 return 0;
4929 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004930 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004931
Carlo Bertolliffafe102017-04-20 00:39:39 +00004932 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004933 // directive with for as IV = IV + ST; ensure upper bound expression based
4934 // on PrevUB instead of NumIterations - used to implement 'for' when found
4935 // in combination with 'distribute', like in 'distribute parallel for'
4936 SourceLocation DistIncLoc;
4937 ExprResult DistCond, DistInc, PrevEUB;
4938 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4939 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4940 assert(DistCond.isUsable() && "distribute cond expr was not built");
4941
4942 DistInc =
4943 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4944 assert(DistInc.isUsable() && "distribute inc expr was not built");
4945 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4946 DistInc.get());
4947 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4948 assert(DistInc.isUsable() && "distribute inc expr was not built");
4949
4950 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4951 // construct
4952 SourceLocation DistEUBLoc;
4953 ExprResult IsUBGreater =
4954 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4955 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4956 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4957 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4958 CondOp.get());
4959 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4960 }
4961
Alexander Musmana5f070a2014-10-01 06:03:56 +00004962 // Build updates and final values of the loop counters.
4963 bool HasErrors = false;
4964 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004965 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004966 Built.Updates.resize(NestedLoopCount);
4967 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004968 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004969 {
4970 ExprResult Div;
4971 // Go from inner nested loop to outer.
4972 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4973 LoopIterationSpace &IS = IterSpaces[Cnt];
4974 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4975 // Build: Iter = (IV / Div) % IS.NumIters
4976 // where Div is product of previous iterations' IS.NumIters.
4977 ExprResult Iter;
4978 if (Div.isUsable()) {
4979 Iter =
4980 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4981 } else {
4982 Iter = IV;
4983 assert((Cnt == (int)NestedLoopCount - 1) &&
4984 "unusable div expected on first iteration only");
4985 }
4986
4987 if (Cnt != 0 && Iter.isUsable())
4988 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4989 IS.NumIterations);
4990 if (!Iter.isUsable()) {
4991 HasErrors = true;
4992 break;
4993 }
4994
Alexey Bataev39f915b82015-05-08 10:41:21 +00004995 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004996 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
4997 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
4998 IS.CounterVar->getExprLoc(),
4999 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005000 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005001 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005002 if (!Init.isUsable()) {
5003 HasErrors = true;
5004 break;
5005 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00005006 ExprResult Update = BuildCounterUpdate(
5007 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5008 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005009 if (!Update.isUsable()) {
5010 HasErrors = true;
5011 break;
5012 }
5013
5014 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
5015 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00005016 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005017 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005018 if (!Final.isUsable()) {
5019 HasErrors = true;
5020 break;
5021 }
5022
5023 // Build Div for the next iteration: Div <- Div * IS.NumIters
5024 if (Cnt != 0) {
5025 if (Div.isUnset())
5026 Div = IS.NumIterations;
5027 else
5028 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
5029 IS.NumIterations);
5030
5031 // Add parentheses (for debugging purposes only).
5032 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00005033 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005034 if (!Div.isUsable()) {
5035 HasErrors = true;
5036 break;
5037 }
Alexey Bataev8b427062016-05-25 12:36:08 +00005038 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005039 }
5040 if (!Update.isUsable() || !Final.isUsable()) {
5041 HasErrors = true;
5042 break;
5043 }
5044 // Save results
5045 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00005046 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005047 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005048 Built.Updates[Cnt] = Update.get();
5049 Built.Finals[Cnt] = Final.get();
5050 }
5051 }
5052
5053 if (HasErrors)
5054 return 0;
5055
5056 // Save results
5057 Built.IterationVarRef = IV.get();
5058 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00005059 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005060 Built.CalcLastIteration =
5061 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005062 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00005063 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005064 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005065 Built.Init = Init.get();
5066 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005067 Built.LB = LB.get();
5068 Built.UB = UB.get();
5069 Built.IL = IL.get();
5070 Built.ST = ST.get();
5071 Built.EUB = EUB.get();
5072 Built.NLB = NextLB.get();
5073 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005074 Built.PrevLB = PrevLB.get();
5075 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005076 Built.DistInc = DistInc.get();
5077 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00005078 Built.DistCombinedFields.LB = CombLB.get();
5079 Built.DistCombinedFields.UB = CombUB.get();
5080 Built.DistCombinedFields.EUB = CombEUB.get();
5081 Built.DistCombinedFields.Init = CombInit.get();
5082 Built.DistCombinedFields.Cond = CombCond.get();
5083 Built.DistCombinedFields.NLB = CombNextLB.get();
5084 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005085
Alexey Bataev8b427062016-05-25 12:36:08 +00005086 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
5087 // Fill data for doacross depend clauses.
5088 for (auto Pair : DSA.getDoacrossDependClauses()) {
5089 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5090 Pair.first->setCounterValue(CounterVal);
5091 else {
5092 if (NestedLoopCount != Pair.second.size() ||
5093 NestedLoopCount != LoopMultipliers.size() + 1) {
5094 // Erroneous case - clause has some problems.
5095 Pair.first->setCounterValue(CounterVal);
5096 continue;
5097 }
5098 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
5099 auto I = Pair.second.rbegin();
5100 auto IS = IterSpaces.rbegin();
5101 auto ILM = LoopMultipliers.rbegin();
5102 Expr *UpCounterVal = CounterVal;
5103 Expr *Multiplier = nullptr;
5104 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5105 if (I->first) {
5106 assert(IS->CounterStep);
5107 Expr *NormalizedOffset =
5108 SemaRef
5109 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
5110 I->first, IS->CounterStep)
5111 .get();
5112 if (Multiplier) {
5113 NormalizedOffset =
5114 SemaRef
5115 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
5116 NormalizedOffset, Multiplier)
5117 .get();
5118 }
5119 assert(I->second == OO_Plus || I->second == OO_Minus);
5120 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00005121 UpCounterVal = SemaRef
5122 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
5123 UpCounterVal, NormalizedOffset)
5124 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00005125 }
5126 Multiplier = *ILM;
5127 ++I;
5128 ++IS;
5129 ++ILM;
5130 }
5131 Pair.first->setCounterValue(UpCounterVal);
5132 }
5133 }
5134
Alexey Bataevabfc0692014-06-25 06:52:00 +00005135 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005136}
5137
Alexey Bataev10e775f2015-07-30 11:36:16 +00005138static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005139 auto CollapseClauses =
5140 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5141 if (CollapseClauses.begin() != CollapseClauses.end())
5142 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005143 return nullptr;
5144}
5145
Alexey Bataev10e775f2015-07-30 11:36:16 +00005146static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005147 auto OrderedClauses =
5148 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5149 if (OrderedClauses.begin() != OrderedClauses.end())
5150 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005151 return nullptr;
5152}
5153
Kelvin Lic5609492016-07-15 04:39:07 +00005154static bool checkSimdlenSafelenSpecified(Sema &S,
5155 const ArrayRef<OMPClause *> Clauses) {
5156 OMPSafelenClause *Safelen = nullptr;
5157 OMPSimdlenClause *Simdlen = nullptr;
5158
5159 for (auto *Clause : Clauses) {
5160 if (Clause->getClauseKind() == OMPC_safelen)
5161 Safelen = cast<OMPSafelenClause>(Clause);
5162 else if (Clause->getClauseKind() == OMPC_simdlen)
5163 Simdlen = cast<OMPSimdlenClause>(Clause);
5164 if (Safelen && Simdlen)
5165 break;
5166 }
5167
5168 if (Simdlen && Safelen) {
5169 llvm::APSInt SimdlenRes, SafelenRes;
5170 auto SimdlenLength = Simdlen->getSimdlen();
5171 auto SafelenLength = Safelen->getSafelen();
5172 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5173 SimdlenLength->isInstantiationDependent() ||
5174 SimdlenLength->containsUnexpandedParameterPack())
5175 return false;
5176 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5177 SafelenLength->isInstantiationDependent() ||
5178 SafelenLength->containsUnexpandedParameterPack())
5179 return false;
5180 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5181 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5182 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5183 // If both simdlen and safelen clauses are specified, the value of the
5184 // simdlen parameter must be less than or equal to the value of the safelen
5185 // parameter.
5186 if (SimdlenRes > SafelenRes) {
5187 S.Diag(SimdlenLength->getExprLoc(),
5188 diag::err_omp_wrong_simdlen_safelen_values)
5189 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5190 return true;
5191 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005192 }
5193 return false;
5194}
5195
Alexey Bataev4acb8592014-07-07 13:01:15 +00005196StmtResult Sema::ActOnOpenMPSimdDirective(
5197 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5198 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005199 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005200 if (!AStmt)
5201 return StmtError();
5202
5203 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005204 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005205 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5206 // define the nested loops number.
5207 unsigned NestedLoopCount = CheckOpenMPLoop(
5208 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5209 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005210 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005211 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005212
Alexander Musmana5f070a2014-10-01 06:03:56 +00005213 assert((CurContext->isDependentContext() || B.builtAll()) &&
5214 "omp simd loop exprs were not built");
5215
Alexander Musman3276a272015-03-21 10:12:56 +00005216 if (!CurContext->isDependentContext()) {
5217 // Finalize the clauses that need pre-built expressions for CodeGen.
5218 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005219 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005220 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005221 B.NumIterations, *this, CurScope,
5222 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005223 return StmtError();
5224 }
5225 }
5226
Kelvin Lic5609492016-07-15 04:39:07 +00005227 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005228 return StmtError();
5229
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005230 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005231 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5232 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005233}
5234
Alexey Bataev4acb8592014-07-07 13:01:15 +00005235StmtResult Sema::ActOnOpenMPForDirective(
5236 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5237 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005238 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005239 if (!AStmt)
5240 return StmtError();
5241
5242 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005243 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005244 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5245 // define the nested loops number.
5246 unsigned NestedLoopCount = CheckOpenMPLoop(
5247 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5248 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005249 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005250 return StmtError();
5251
Alexander Musmana5f070a2014-10-01 06:03:56 +00005252 assert((CurContext->isDependentContext() || B.builtAll()) &&
5253 "omp for loop exprs were not built");
5254
Alexey Bataev54acd402015-08-04 11:18:19 +00005255 if (!CurContext->isDependentContext()) {
5256 // Finalize the clauses that need pre-built expressions for CodeGen.
5257 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005258 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005259 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005260 B.NumIterations, *this, CurScope,
5261 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005262 return StmtError();
5263 }
5264 }
5265
Alexey Bataevf29276e2014-06-18 04:14:57 +00005266 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005267 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005268 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005269}
5270
Alexander Musmanf82886e2014-09-18 05:12:34 +00005271StmtResult Sema::ActOnOpenMPForSimdDirective(
5272 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5273 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005274 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005275 if (!AStmt)
5276 return StmtError();
5277
5278 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005279 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005280 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5281 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005282 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005283 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5284 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5285 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005286 if (NestedLoopCount == 0)
5287 return StmtError();
5288
Alexander Musmanc6388682014-12-15 07:07:06 +00005289 assert((CurContext->isDependentContext() || B.builtAll()) &&
5290 "omp for simd loop exprs were not built");
5291
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005292 if (!CurContext->isDependentContext()) {
5293 // Finalize the clauses that need pre-built expressions for CodeGen.
5294 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005295 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005296 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005297 B.NumIterations, *this, CurScope,
5298 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005299 return StmtError();
5300 }
5301 }
5302
Kelvin Lic5609492016-07-15 04:39:07 +00005303 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005304 return StmtError();
5305
Alexander Musmanf82886e2014-09-18 05:12:34 +00005306 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005307 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5308 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005309}
5310
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005311StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5312 Stmt *AStmt,
5313 SourceLocation StartLoc,
5314 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005315 if (!AStmt)
5316 return StmtError();
5317
5318 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005319 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005320 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005321 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005322 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005323 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005324 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005325 return StmtError();
5326 // All associated statements must be '#pragma omp section' except for
5327 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005328 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005329 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5330 if (SectionStmt)
5331 Diag(SectionStmt->getLocStart(),
5332 diag::err_omp_sections_substmt_not_section);
5333 return StmtError();
5334 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005335 cast<OMPSectionDirective>(SectionStmt)
5336 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005337 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005338 } else {
5339 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5340 return StmtError();
5341 }
5342
5343 getCurFunction()->setHasBranchProtectedScope();
5344
Alexey Bataev25e5b442015-09-15 12:52:43 +00005345 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5346 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005347}
5348
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005349StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5350 SourceLocation StartLoc,
5351 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005352 if (!AStmt)
5353 return StmtError();
5354
5355 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005356
5357 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005358 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005359
Alexey Bataev25e5b442015-09-15 12:52:43 +00005360 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5361 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005362}
5363
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005364StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5365 Stmt *AStmt,
5366 SourceLocation StartLoc,
5367 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005368 if (!AStmt)
5369 return StmtError();
5370
5371 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005372
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005373 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005374
Alexey Bataev3255bf32015-01-19 05:20:46 +00005375 // OpenMP [2.7.3, single Construct, Restrictions]
5376 // The copyprivate clause must not be used with the nowait clause.
5377 OMPClause *Nowait = nullptr;
5378 OMPClause *Copyprivate = nullptr;
5379 for (auto *Clause : Clauses) {
5380 if (Clause->getClauseKind() == OMPC_nowait)
5381 Nowait = Clause;
5382 else if (Clause->getClauseKind() == OMPC_copyprivate)
5383 Copyprivate = Clause;
5384 if (Copyprivate && Nowait) {
5385 Diag(Copyprivate->getLocStart(),
5386 diag::err_omp_single_copyprivate_with_nowait);
5387 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5388 return StmtError();
5389 }
5390 }
5391
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005392 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5393}
5394
Alexander Musman80c22892014-07-17 08:54:58 +00005395StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5396 SourceLocation StartLoc,
5397 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005398 if (!AStmt)
5399 return StmtError();
5400
5401 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005402
5403 getCurFunction()->setHasBranchProtectedScope();
5404
5405 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5406}
5407
Alexey Bataev28c75412015-12-15 08:19:24 +00005408StmtResult Sema::ActOnOpenMPCriticalDirective(
5409 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5410 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005411 if (!AStmt)
5412 return StmtError();
5413
5414 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005415
Alexey Bataev28c75412015-12-15 08:19:24 +00005416 bool ErrorFound = false;
5417 llvm::APSInt Hint;
5418 SourceLocation HintLoc;
5419 bool DependentHint = false;
5420 for (auto *C : Clauses) {
5421 if (C->getClauseKind() == OMPC_hint) {
5422 if (!DirName.getName()) {
5423 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5424 ErrorFound = true;
5425 }
5426 Expr *E = cast<OMPHintClause>(C)->getHint();
5427 if (E->isTypeDependent() || E->isValueDependent() ||
5428 E->isInstantiationDependent())
5429 DependentHint = true;
5430 else {
5431 Hint = E->EvaluateKnownConstInt(Context);
5432 HintLoc = C->getLocStart();
5433 }
5434 }
5435 }
5436 if (ErrorFound)
5437 return StmtError();
5438 auto Pair = DSAStack->getCriticalWithHint(DirName);
5439 if (Pair.first && DirName.getName() && !DependentHint) {
5440 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5441 Diag(StartLoc, diag::err_omp_critical_with_hint);
5442 if (HintLoc.isValid()) {
5443 Diag(HintLoc, diag::note_omp_critical_hint_here)
5444 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5445 } else
5446 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5447 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5448 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5449 << 1
5450 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5451 /*Radix=*/10, /*Signed=*/false);
5452 } else
5453 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5454 }
5455 }
5456
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005457 getCurFunction()->setHasBranchProtectedScope();
5458
Alexey Bataev28c75412015-12-15 08:19:24 +00005459 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5460 Clauses, AStmt);
5461 if (!Pair.first && DirName.getName() && !DependentHint)
5462 DSAStack->addCriticalWithHint(Dir, Hint);
5463 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005464}
5465
Alexey Bataev4acb8592014-07-07 13:01:15 +00005466StmtResult Sema::ActOnOpenMPParallelForDirective(
5467 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5468 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005469 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005470 if (!AStmt)
5471 return StmtError();
5472
Alexey Bataev4acb8592014-07-07 13:01:15 +00005473 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5474 // 1.2.2 OpenMP Language Terminology
5475 // Structured block - An executable statement with a single entry at the
5476 // top and a single exit at the bottom.
5477 // The point of exit cannot be a branch out of the structured block.
5478 // longjmp() and throw() must not violate the entry/exit criteria.
5479 CS->getCapturedDecl()->setNothrow();
5480
Alexander Musmanc6388682014-12-15 07:07:06 +00005481 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005482 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5483 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005484 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005485 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5486 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5487 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005488 if (NestedLoopCount == 0)
5489 return StmtError();
5490
Alexander Musmana5f070a2014-10-01 06:03:56 +00005491 assert((CurContext->isDependentContext() || B.builtAll()) &&
5492 "omp parallel for loop exprs were not built");
5493
Alexey Bataev54acd402015-08-04 11:18:19 +00005494 if (!CurContext->isDependentContext()) {
5495 // Finalize the clauses that need pre-built expressions for CodeGen.
5496 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005497 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005498 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005499 B.NumIterations, *this, CurScope,
5500 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005501 return StmtError();
5502 }
5503 }
5504
Alexey Bataev4acb8592014-07-07 13:01:15 +00005505 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005506 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005507 NestedLoopCount, Clauses, AStmt, B,
5508 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005509}
5510
Alexander Musmane4e893b2014-09-23 09:33:00 +00005511StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5512 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5513 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005514 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005515 if (!AStmt)
5516 return StmtError();
5517
Alexander Musmane4e893b2014-09-23 09:33:00 +00005518 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5519 // 1.2.2 OpenMP Language Terminology
5520 // Structured block - An executable statement with a single entry at the
5521 // top and a single exit at the bottom.
5522 // The point of exit cannot be a branch out of the structured block.
5523 // longjmp() and throw() must not violate the entry/exit criteria.
5524 CS->getCapturedDecl()->setNothrow();
5525
Alexander Musmanc6388682014-12-15 07:07:06 +00005526 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005527 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5528 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005529 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005530 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5531 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5532 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005533 if (NestedLoopCount == 0)
5534 return StmtError();
5535
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005536 if (!CurContext->isDependentContext()) {
5537 // Finalize the clauses that need pre-built expressions for CodeGen.
5538 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005539 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005540 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005541 B.NumIterations, *this, CurScope,
5542 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005543 return StmtError();
5544 }
5545 }
5546
Kelvin Lic5609492016-07-15 04:39:07 +00005547 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005548 return StmtError();
5549
Alexander Musmane4e893b2014-09-23 09:33:00 +00005550 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005551 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005552 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005553}
5554
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005555StmtResult
5556Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5557 Stmt *AStmt, SourceLocation StartLoc,
5558 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005559 if (!AStmt)
5560 return StmtError();
5561
5562 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005563 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005564 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005565 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005566 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005567 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005568 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005569 return StmtError();
5570 // All associated statements must be '#pragma omp section' except for
5571 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005572 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005573 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5574 if (SectionStmt)
5575 Diag(SectionStmt->getLocStart(),
5576 diag::err_omp_parallel_sections_substmt_not_section);
5577 return StmtError();
5578 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005579 cast<OMPSectionDirective>(SectionStmt)
5580 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005581 }
5582 } else {
5583 Diag(AStmt->getLocStart(),
5584 diag::err_omp_parallel_sections_not_compound_stmt);
5585 return StmtError();
5586 }
5587
5588 getCurFunction()->setHasBranchProtectedScope();
5589
Alexey Bataev25e5b442015-09-15 12:52:43 +00005590 return OMPParallelSectionsDirective::Create(
5591 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005592}
5593
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005594StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5595 Stmt *AStmt, SourceLocation StartLoc,
5596 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005597 if (!AStmt)
5598 return StmtError();
5599
David Majnemer9d168222016-08-05 17:44:54 +00005600 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005601 // 1.2.2 OpenMP Language Terminology
5602 // Structured block - An executable statement with a single entry at the
5603 // top and a single exit at the bottom.
5604 // The point of exit cannot be a branch out of the structured block.
5605 // longjmp() and throw() must not violate the entry/exit criteria.
5606 CS->getCapturedDecl()->setNothrow();
5607
5608 getCurFunction()->setHasBranchProtectedScope();
5609
Alexey Bataev25e5b442015-09-15 12:52:43 +00005610 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5611 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005612}
5613
Alexey Bataev68446b72014-07-18 07:47:19 +00005614StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5615 SourceLocation EndLoc) {
5616 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5617}
5618
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005619StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5620 SourceLocation EndLoc) {
5621 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5622}
5623
Alexey Bataev2df347a2014-07-18 10:17:07 +00005624StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5625 SourceLocation EndLoc) {
5626 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5627}
5628
Alexey Bataev169d96a2017-07-18 20:17:46 +00005629StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5630 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005631 SourceLocation StartLoc,
5632 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005633 if (!AStmt)
5634 return StmtError();
5635
5636 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005637
5638 getCurFunction()->setHasBranchProtectedScope();
5639
Alexey Bataev169d96a2017-07-18 20:17:46 +00005640 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005641 AStmt,
5642 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005643}
5644
Alexey Bataev6125da92014-07-21 11:26:11 +00005645StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5646 SourceLocation StartLoc,
5647 SourceLocation EndLoc) {
5648 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5649 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5650}
5651
Alexey Bataev346265e2015-09-25 10:37:12 +00005652StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5653 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005654 SourceLocation StartLoc,
5655 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005656 OMPClause *DependFound = nullptr;
5657 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005658 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005659 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005660 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005661 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005662 for (auto *C : Clauses) {
5663 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5664 DependFound = C;
5665 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5666 if (DependSourceClause) {
5667 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5668 << getOpenMPDirectiveName(OMPD_ordered)
5669 << getOpenMPClauseName(OMPC_depend) << 2;
5670 ErrorFound = true;
5671 } else
5672 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005673 if (DependSinkClause) {
5674 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5675 << 0;
5676 ErrorFound = true;
5677 }
5678 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5679 if (DependSourceClause) {
5680 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5681 << 1;
5682 ErrorFound = true;
5683 }
5684 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005685 }
5686 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005687 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005688 else if (C->getClauseKind() == OMPC_simd)
5689 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005690 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005691 if (!ErrorFound && !SC &&
5692 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005693 // OpenMP [2.8.1,simd Construct, Restrictions]
5694 // An ordered construct with the simd clause is the only OpenMP construct
5695 // that can appear in the simd region.
5696 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005697 ErrorFound = true;
5698 } else if (DependFound && (TC || SC)) {
5699 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5700 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5701 ErrorFound = true;
5702 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5703 Diag(DependFound->getLocStart(),
5704 diag::err_omp_ordered_directive_without_param);
5705 ErrorFound = true;
5706 } else if (TC || Clauses.empty()) {
5707 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5708 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5709 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5710 << (TC != nullptr);
5711 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5712 ErrorFound = true;
5713 }
5714 }
5715 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005716 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005717
5718 if (AStmt) {
5719 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5720
5721 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005722 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005723
5724 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005725}
5726
Alexey Bataev1d160b12015-03-13 12:27:31 +00005727namespace {
5728/// \brief Helper class for checking expression in 'omp atomic [update]'
5729/// construct.
5730class OpenMPAtomicUpdateChecker {
5731 /// \brief Error results for atomic update expressions.
5732 enum ExprAnalysisErrorCode {
5733 /// \brief A statement is not an expression statement.
5734 NotAnExpression,
5735 /// \brief Expression is not builtin binary or unary operation.
5736 NotABinaryOrUnaryExpression,
5737 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5738 NotAnUnaryIncDecExpression,
5739 /// \brief An expression is not of scalar type.
5740 NotAScalarType,
5741 /// \brief A binary operation is not an assignment operation.
5742 NotAnAssignmentOp,
5743 /// \brief RHS part of the binary operation is not a binary expression.
5744 NotABinaryExpression,
5745 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5746 /// expression.
5747 NotABinaryOperator,
5748 /// \brief RHS binary operation does not have reference to the updated LHS
5749 /// part.
5750 NotAnUpdateExpression,
5751 /// \brief No errors is found.
5752 NoError
5753 };
5754 /// \brief Reference to Sema.
5755 Sema &SemaRef;
5756 /// \brief A location for note diagnostics (when error is found).
5757 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005758 /// \brief 'x' lvalue part of the source atomic expression.
5759 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005760 /// \brief 'expr' rvalue part of the source atomic expression.
5761 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005762 /// \brief Helper expression of the form
5763 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5764 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5765 Expr *UpdateExpr;
5766 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5767 /// important for non-associative operations.
5768 bool IsXLHSInRHSPart;
5769 BinaryOperatorKind Op;
5770 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005771 /// \brief true if the source expression is a postfix unary operation, false
5772 /// if it is a prefix unary operation.
5773 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005774
5775public:
5776 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005777 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005778 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005779 /// \brief Check specified statement that it is suitable for 'atomic update'
5780 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005781 /// expression. If DiagId and NoteId == 0, then only check is performed
5782 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005783 /// \param DiagId Diagnostic which should be emitted if error is found.
5784 /// \param NoteId Diagnostic note for the main error message.
5785 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005786 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005787 /// \brief Return the 'x' lvalue part of the source atomic expression.
5788 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005789 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5790 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005791 /// \brief Return the update expression used in calculation of the updated
5792 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5793 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5794 Expr *getUpdateExpr() const { return UpdateExpr; }
5795 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5796 /// false otherwise.
5797 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5798
Alexey Bataevb78ca832015-04-01 03:33:17 +00005799 /// \brief true if the source expression is a postfix unary operation, false
5800 /// if it is a prefix unary operation.
5801 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5802
Alexey Bataev1d160b12015-03-13 12:27:31 +00005803private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005804 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5805 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005806};
5807} // namespace
5808
5809bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5810 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5811 ExprAnalysisErrorCode ErrorFound = NoError;
5812 SourceLocation ErrorLoc, NoteLoc;
5813 SourceRange ErrorRange, NoteRange;
5814 // Allowed constructs are:
5815 // x = x binop expr;
5816 // x = expr binop x;
5817 if (AtomicBinOp->getOpcode() == BO_Assign) {
5818 X = AtomicBinOp->getLHS();
5819 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5820 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5821 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5822 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5823 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005824 Op = AtomicInnerBinOp->getOpcode();
5825 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005826 auto *LHS = AtomicInnerBinOp->getLHS();
5827 auto *RHS = AtomicInnerBinOp->getRHS();
5828 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5829 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5830 /*Canonical=*/true);
5831 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5832 /*Canonical=*/true);
5833 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5834 /*Canonical=*/true);
5835 if (XId == LHSId) {
5836 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005837 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005838 } else if (XId == RHSId) {
5839 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005840 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005841 } else {
5842 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5843 ErrorRange = AtomicInnerBinOp->getSourceRange();
5844 NoteLoc = X->getExprLoc();
5845 NoteRange = X->getSourceRange();
5846 ErrorFound = NotAnUpdateExpression;
5847 }
5848 } else {
5849 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5850 ErrorRange = AtomicInnerBinOp->getSourceRange();
5851 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5852 NoteRange = SourceRange(NoteLoc, NoteLoc);
5853 ErrorFound = NotABinaryOperator;
5854 }
5855 } else {
5856 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5857 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5858 ErrorFound = NotABinaryExpression;
5859 }
5860 } else {
5861 ErrorLoc = AtomicBinOp->getExprLoc();
5862 ErrorRange = AtomicBinOp->getSourceRange();
5863 NoteLoc = AtomicBinOp->getOperatorLoc();
5864 NoteRange = SourceRange(NoteLoc, NoteLoc);
5865 ErrorFound = NotAnAssignmentOp;
5866 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005867 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005868 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5869 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5870 return true;
5871 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005872 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005873 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005874}
5875
5876bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5877 unsigned NoteId) {
5878 ExprAnalysisErrorCode ErrorFound = NoError;
5879 SourceLocation ErrorLoc, NoteLoc;
5880 SourceRange ErrorRange, NoteRange;
5881 // Allowed constructs are:
5882 // x++;
5883 // x--;
5884 // ++x;
5885 // --x;
5886 // x binop= expr;
5887 // x = x binop expr;
5888 // x = expr binop x;
5889 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5890 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5891 if (AtomicBody->getType()->isScalarType() ||
5892 AtomicBody->isInstantiationDependent()) {
5893 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5894 AtomicBody->IgnoreParenImpCasts())) {
5895 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005896 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005897 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005898 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005899 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005900 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005901 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005902 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5903 AtomicBody->IgnoreParenImpCasts())) {
5904 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005905 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005906 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005907 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5908 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005909 // Check for Unary Operation
5910 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005911 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005912 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5913 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005914 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005915 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5916 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005917 } else {
5918 ErrorFound = NotAnUnaryIncDecExpression;
5919 ErrorLoc = AtomicUnaryOp->getExprLoc();
5920 ErrorRange = AtomicUnaryOp->getSourceRange();
5921 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5922 NoteRange = SourceRange(NoteLoc, NoteLoc);
5923 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005924 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005925 ErrorFound = NotABinaryOrUnaryExpression;
5926 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5927 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5928 }
5929 } else {
5930 ErrorFound = NotAScalarType;
5931 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5932 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5933 }
5934 } else {
5935 ErrorFound = NotAnExpression;
5936 NoteLoc = ErrorLoc = S->getLocStart();
5937 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5938 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005939 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005940 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5941 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5942 return true;
5943 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005944 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005945 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005946 // Build an update expression of form 'OpaqueValueExpr(x) binop
5947 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5948 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5949 auto *OVEX = new (SemaRef.getASTContext())
5950 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5951 auto *OVEExpr = new (SemaRef.getASTContext())
5952 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5953 auto Update =
5954 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5955 IsXLHSInRHSPart ? OVEExpr : OVEX);
5956 if (Update.isInvalid())
5957 return true;
5958 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5959 Sema::AA_Casting);
5960 if (Update.isInvalid())
5961 return true;
5962 UpdateExpr = Update.get();
5963 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005964 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005965}
5966
Alexey Bataev0162e452014-07-22 10:10:35 +00005967StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5968 Stmt *AStmt,
5969 SourceLocation StartLoc,
5970 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005971 if (!AStmt)
5972 return StmtError();
5973
David Majnemer9d168222016-08-05 17:44:54 +00005974 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005975 // 1.2.2 OpenMP Language Terminology
5976 // Structured block - An executable statement with a single entry at the
5977 // top and a single exit at the bottom.
5978 // The point of exit cannot be a branch out of the structured block.
5979 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005980 OpenMPClauseKind AtomicKind = OMPC_unknown;
5981 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005982 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005983 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005984 C->getClauseKind() == OMPC_update ||
5985 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005986 if (AtomicKind != OMPC_unknown) {
5987 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5988 << SourceRange(C->getLocStart(), C->getLocEnd());
5989 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5990 << getOpenMPClauseName(AtomicKind);
5991 } else {
5992 AtomicKind = C->getClauseKind();
5993 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005994 }
5995 }
5996 }
Alexey Bataev62cec442014-11-18 10:14:22 +00005997
Alexey Bataev459dec02014-07-24 06:46:57 +00005998 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00005999 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6000 Body = EWC->getSubExpr();
6001
Alexey Bataev62cec442014-11-18 10:14:22 +00006002 Expr *X = nullptr;
6003 Expr *V = nullptr;
6004 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006005 Expr *UE = nullptr;
6006 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006007 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006008 // OpenMP [2.12.6, atomic Construct]
6009 // In the next expressions:
6010 // * x and v (as applicable) are both l-value expressions with scalar type.
6011 // * During the execution of an atomic region, multiple syntactic
6012 // occurrences of x must designate the same storage location.
6013 // * Neither of v and expr (as applicable) may access the storage location
6014 // designated by x.
6015 // * Neither of x and expr (as applicable) may access the storage location
6016 // designated by v.
6017 // * expr is an expression with scalar type.
6018 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6019 // * binop, binop=, ++, and -- are not overloaded operators.
6020 // * The expression x binop expr must be numerically equivalent to x binop
6021 // (expr). This requirement is satisfied if the operators in expr have
6022 // precedence greater than binop, or by using parentheses around expr or
6023 // subexpressions of expr.
6024 // * The expression expr binop x must be numerically equivalent to (expr)
6025 // binop x. This requirement is satisfied if the operators in expr have
6026 // precedence equal to or greater than binop, or by using parentheses around
6027 // expr or subexpressions of expr.
6028 // * For forms that allow multiple occurrences of x, the number of times
6029 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006030 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006031 enum {
6032 NotAnExpression,
6033 NotAnAssignmentOp,
6034 NotAScalarType,
6035 NotAnLValue,
6036 NoError
6037 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006038 SourceLocation ErrorLoc, NoteLoc;
6039 SourceRange ErrorRange, NoteRange;
6040 // If clause is read:
6041 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00006042 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6043 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006044 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6045 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6046 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6047 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6048 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6049 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6050 if (!X->isLValue() || !V->isLValue()) {
6051 auto NotLValueExpr = X->isLValue() ? V : X;
6052 ErrorFound = NotAnLValue;
6053 ErrorLoc = AtomicBinOp->getExprLoc();
6054 ErrorRange = AtomicBinOp->getSourceRange();
6055 NoteLoc = NotLValueExpr->getExprLoc();
6056 NoteRange = NotLValueExpr->getSourceRange();
6057 }
6058 } else if (!X->isInstantiationDependent() ||
6059 !V->isInstantiationDependent()) {
6060 auto NotScalarExpr =
6061 (X->isInstantiationDependent() || X->getType()->isScalarType())
6062 ? V
6063 : X;
6064 ErrorFound = NotAScalarType;
6065 ErrorLoc = AtomicBinOp->getExprLoc();
6066 ErrorRange = AtomicBinOp->getSourceRange();
6067 NoteLoc = NotScalarExpr->getExprLoc();
6068 NoteRange = NotScalarExpr->getSourceRange();
6069 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006070 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00006071 ErrorFound = NotAnAssignmentOp;
6072 ErrorLoc = AtomicBody->getExprLoc();
6073 ErrorRange = AtomicBody->getSourceRange();
6074 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6075 : AtomicBody->getExprLoc();
6076 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6077 : AtomicBody->getSourceRange();
6078 }
6079 } else {
6080 ErrorFound = NotAnExpression;
6081 NoteLoc = ErrorLoc = Body->getLocStart();
6082 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006083 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006084 if (ErrorFound != NoError) {
6085 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6086 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006087 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6088 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00006089 return StmtError();
6090 } else if (CurContext->isDependentContext())
6091 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00006092 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006093 enum {
6094 NotAnExpression,
6095 NotAnAssignmentOp,
6096 NotAScalarType,
6097 NotAnLValue,
6098 NoError
6099 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006100 SourceLocation ErrorLoc, NoteLoc;
6101 SourceRange ErrorRange, NoteRange;
6102 // If clause is write:
6103 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00006104 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6105 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006106 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6107 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00006108 X = AtomicBinOp->getLHS();
6109 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00006110 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6111 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6112 if (!X->isLValue()) {
6113 ErrorFound = NotAnLValue;
6114 ErrorLoc = AtomicBinOp->getExprLoc();
6115 ErrorRange = AtomicBinOp->getSourceRange();
6116 NoteLoc = X->getExprLoc();
6117 NoteRange = X->getSourceRange();
6118 }
6119 } else if (!X->isInstantiationDependent() ||
6120 !E->isInstantiationDependent()) {
6121 auto NotScalarExpr =
6122 (X->isInstantiationDependent() || X->getType()->isScalarType())
6123 ? E
6124 : X;
6125 ErrorFound = NotAScalarType;
6126 ErrorLoc = AtomicBinOp->getExprLoc();
6127 ErrorRange = AtomicBinOp->getSourceRange();
6128 NoteLoc = NotScalarExpr->getExprLoc();
6129 NoteRange = NotScalarExpr->getSourceRange();
6130 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006131 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00006132 ErrorFound = NotAnAssignmentOp;
6133 ErrorLoc = AtomicBody->getExprLoc();
6134 ErrorRange = AtomicBody->getSourceRange();
6135 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6136 : AtomicBody->getExprLoc();
6137 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6138 : AtomicBody->getSourceRange();
6139 }
6140 } else {
6141 ErrorFound = NotAnExpression;
6142 NoteLoc = ErrorLoc = Body->getLocStart();
6143 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006144 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006145 if (ErrorFound != NoError) {
6146 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6147 << ErrorRange;
6148 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6149 << NoteRange;
6150 return StmtError();
6151 } else if (CurContext->isDependentContext())
6152 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006153 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006154 // If clause is update:
6155 // x++;
6156 // x--;
6157 // ++x;
6158 // --x;
6159 // x binop= expr;
6160 // x = x binop expr;
6161 // x = expr binop x;
6162 OpenMPAtomicUpdateChecker Checker(*this);
6163 if (Checker.checkStatement(
6164 Body, (AtomicKind == OMPC_update)
6165 ? diag::err_omp_atomic_update_not_expression_statement
6166 : diag::err_omp_atomic_not_expression_statement,
6167 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006168 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006169 if (!CurContext->isDependentContext()) {
6170 E = Checker.getExpr();
6171 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006172 UE = Checker.getUpdateExpr();
6173 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006174 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006175 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006176 enum {
6177 NotAnAssignmentOp,
6178 NotACompoundStatement,
6179 NotTwoSubstatements,
6180 NotASpecificExpression,
6181 NoError
6182 } ErrorFound = NoError;
6183 SourceLocation ErrorLoc, NoteLoc;
6184 SourceRange ErrorRange, NoteRange;
6185 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6186 // If clause is a capture:
6187 // v = x++;
6188 // v = x--;
6189 // v = ++x;
6190 // v = --x;
6191 // v = x binop= expr;
6192 // v = x = x binop expr;
6193 // v = x = expr binop x;
6194 auto *AtomicBinOp =
6195 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6196 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6197 V = AtomicBinOp->getLHS();
6198 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6199 OpenMPAtomicUpdateChecker Checker(*this);
6200 if (Checker.checkStatement(
6201 Body, diag::err_omp_atomic_capture_not_expression_statement,
6202 diag::note_omp_atomic_update))
6203 return StmtError();
6204 E = Checker.getExpr();
6205 X = Checker.getX();
6206 UE = Checker.getUpdateExpr();
6207 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6208 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006209 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006210 ErrorLoc = AtomicBody->getExprLoc();
6211 ErrorRange = AtomicBody->getSourceRange();
6212 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6213 : AtomicBody->getExprLoc();
6214 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6215 : AtomicBody->getSourceRange();
6216 ErrorFound = NotAnAssignmentOp;
6217 }
6218 if (ErrorFound != NoError) {
6219 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6220 << ErrorRange;
6221 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6222 return StmtError();
6223 } else if (CurContext->isDependentContext()) {
6224 UE = V = E = X = nullptr;
6225 }
6226 } else {
6227 // If clause is a capture:
6228 // { v = x; x = expr; }
6229 // { v = x; x++; }
6230 // { v = x; x--; }
6231 // { v = x; ++x; }
6232 // { v = x; --x; }
6233 // { v = x; x binop= expr; }
6234 // { v = x; x = x binop expr; }
6235 // { v = x; x = expr binop x; }
6236 // { x++; v = x; }
6237 // { x--; v = x; }
6238 // { ++x; v = x; }
6239 // { --x; v = x; }
6240 // { x binop= expr; v = x; }
6241 // { x = x binop expr; v = x; }
6242 // { x = expr binop x; v = x; }
6243 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6244 // Check that this is { expr1; expr2; }
6245 if (CS->size() == 2) {
6246 auto *First = CS->body_front();
6247 auto *Second = CS->body_back();
6248 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6249 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6250 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6251 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6252 // Need to find what subexpression is 'v' and what is 'x'.
6253 OpenMPAtomicUpdateChecker Checker(*this);
6254 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6255 BinaryOperator *BinOp = nullptr;
6256 if (IsUpdateExprFound) {
6257 BinOp = dyn_cast<BinaryOperator>(First);
6258 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6259 }
6260 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6261 // { v = x; x++; }
6262 // { v = x; x--; }
6263 // { v = x; ++x; }
6264 // { v = x; --x; }
6265 // { v = x; x binop= expr; }
6266 // { v = x; x = x binop expr; }
6267 // { v = x; x = expr binop x; }
6268 // Check that the first expression has form v = x.
6269 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6270 llvm::FoldingSetNodeID XId, PossibleXId;
6271 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6272 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6273 IsUpdateExprFound = XId == PossibleXId;
6274 if (IsUpdateExprFound) {
6275 V = BinOp->getLHS();
6276 X = Checker.getX();
6277 E = Checker.getExpr();
6278 UE = Checker.getUpdateExpr();
6279 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006280 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006281 }
6282 }
6283 if (!IsUpdateExprFound) {
6284 IsUpdateExprFound = !Checker.checkStatement(First);
6285 BinOp = nullptr;
6286 if (IsUpdateExprFound) {
6287 BinOp = dyn_cast<BinaryOperator>(Second);
6288 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6289 }
6290 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6291 // { x++; v = x; }
6292 // { x--; v = x; }
6293 // { ++x; v = x; }
6294 // { --x; v = x; }
6295 // { x binop= expr; v = x; }
6296 // { x = x binop expr; v = x; }
6297 // { x = expr binop x; v = x; }
6298 // Check that the second expression has form v = x.
6299 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6300 llvm::FoldingSetNodeID XId, PossibleXId;
6301 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6302 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6303 IsUpdateExprFound = XId == PossibleXId;
6304 if (IsUpdateExprFound) {
6305 V = BinOp->getLHS();
6306 X = Checker.getX();
6307 E = Checker.getExpr();
6308 UE = Checker.getUpdateExpr();
6309 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006310 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006311 }
6312 }
6313 }
6314 if (!IsUpdateExprFound) {
6315 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006316 auto *FirstExpr = dyn_cast<Expr>(First);
6317 auto *SecondExpr = dyn_cast<Expr>(Second);
6318 if (!FirstExpr || !SecondExpr ||
6319 !(FirstExpr->isInstantiationDependent() ||
6320 SecondExpr->isInstantiationDependent())) {
6321 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6322 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006323 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006324 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6325 : First->getLocStart();
6326 NoteRange = ErrorRange = FirstBinOp
6327 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006328 : SourceRange(ErrorLoc, ErrorLoc);
6329 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006330 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6331 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6332 ErrorFound = NotAnAssignmentOp;
6333 NoteLoc = ErrorLoc = SecondBinOp
6334 ? SecondBinOp->getOperatorLoc()
6335 : Second->getLocStart();
6336 NoteRange = ErrorRange =
6337 SecondBinOp ? SecondBinOp->getSourceRange()
6338 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006339 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006340 auto *PossibleXRHSInFirst =
6341 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6342 auto *PossibleXLHSInSecond =
6343 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6344 llvm::FoldingSetNodeID X1Id, X2Id;
6345 PossibleXRHSInFirst->Profile(X1Id, Context,
6346 /*Canonical=*/true);
6347 PossibleXLHSInSecond->Profile(X2Id, Context,
6348 /*Canonical=*/true);
6349 IsUpdateExprFound = X1Id == X2Id;
6350 if (IsUpdateExprFound) {
6351 V = FirstBinOp->getLHS();
6352 X = SecondBinOp->getLHS();
6353 E = SecondBinOp->getRHS();
6354 UE = nullptr;
6355 IsXLHSInRHSPart = false;
6356 IsPostfixUpdate = true;
6357 } else {
6358 ErrorFound = NotASpecificExpression;
6359 ErrorLoc = FirstBinOp->getExprLoc();
6360 ErrorRange = FirstBinOp->getSourceRange();
6361 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6362 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6363 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006364 }
6365 }
6366 }
6367 }
6368 } else {
6369 NoteLoc = ErrorLoc = Body->getLocStart();
6370 NoteRange = ErrorRange =
6371 SourceRange(Body->getLocStart(), Body->getLocStart());
6372 ErrorFound = NotTwoSubstatements;
6373 }
6374 } else {
6375 NoteLoc = ErrorLoc = Body->getLocStart();
6376 NoteRange = ErrorRange =
6377 SourceRange(Body->getLocStart(), Body->getLocStart());
6378 ErrorFound = NotACompoundStatement;
6379 }
6380 if (ErrorFound != NoError) {
6381 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6382 << ErrorRange;
6383 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6384 return StmtError();
6385 } else if (CurContext->isDependentContext()) {
6386 UE = V = E = X = nullptr;
6387 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006388 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006389 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006390
6391 getCurFunction()->setHasBranchProtectedScope();
6392
Alexey Bataev62cec442014-11-18 10:14:22 +00006393 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006394 X, V, E, UE, IsXLHSInRHSPart,
6395 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006396}
6397
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006398StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6399 Stmt *AStmt,
6400 SourceLocation StartLoc,
6401 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006402 if (!AStmt)
6403 return StmtError();
6404
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006405 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6406 // 1.2.2 OpenMP Language Terminology
6407 // Structured block - An executable statement with a single entry at the
6408 // top and a single exit at the bottom.
6409 // The point of exit cannot be a branch out of the structured block.
6410 // longjmp() and throw() must not violate the entry/exit criteria.
6411 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00006412 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
6413 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6414 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6415 // 1.2.2 OpenMP Language Terminology
6416 // Structured block - An executable statement with a single entry at the
6417 // top and a single exit at the bottom.
6418 // The point of exit cannot be a branch out of the structured block.
6419 // longjmp() and throw() must not violate the entry/exit criteria.
6420 CS->getCapturedDecl()->setNothrow();
6421 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006422
Alexey Bataev13314bf2014-10-09 04:18:56 +00006423 // OpenMP [2.16, Nesting of Regions]
6424 // If specified, a teams construct must be contained within a target
6425 // construct. That target construct must contain no statements or directives
6426 // outside of the teams construct.
6427 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00006428 Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006429 bool OMPTeamsFound = true;
6430 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6431 auto I = CS->body_begin();
6432 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00006433 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006434 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6435 OMPTeamsFound = false;
6436 break;
6437 }
6438 ++I;
6439 }
6440 assert(I != CS->body_end() && "Not found statement");
6441 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006442 } else {
6443 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6444 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006445 }
6446 if (!OMPTeamsFound) {
6447 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6448 Diag(DSAStack->getInnerTeamsRegionLoc(),
6449 diag::note_omp_nested_teams_construct_here);
6450 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6451 << isa<OMPExecutableDirective>(S);
6452 return StmtError();
6453 }
6454 }
6455
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006456 getCurFunction()->setHasBranchProtectedScope();
6457
6458 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6459}
6460
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006461StmtResult
6462Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6463 Stmt *AStmt, SourceLocation StartLoc,
6464 SourceLocation EndLoc) {
6465 if (!AStmt)
6466 return StmtError();
6467
6468 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
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();
Alexey Bataev8451efa2018-01-15 19:06:12 +00006475 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
6476 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6477 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6478 // 1.2.2 OpenMP Language Terminology
6479 // Structured block - An executable statement with a single entry at the
6480 // top and a single exit at the bottom.
6481 // The point of exit cannot be a branch out of the structured block.
6482 // longjmp() and throw() must not violate the entry/exit criteria.
6483 CS->getCapturedDecl()->setNothrow();
6484 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006485
6486 getCurFunction()->setHasBranchProtectedScope();
6487
6488 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6489 AStmt);
6490}
6491
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006492StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6493 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6494 SourceLocation EndLoc,
6495 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6496 if (!AStmt)
6497 return StmtError();
6498
6499 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6500 // 1.2.2 OpenMP Language Terminology
6501 // Structured block - An executable statement with a single entry at the
6502 // top and a single exit at the bottom.
6503 // The point of exit cannot be a branch out of the structured block.
6504 // longjmp() and throw() must not violate the entry/exit criteria.
6505 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006506 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6507 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6508 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6509 // 1.2.2 OpenMP Language Terminology
6510 // Structured block - An executable statement with a single entry at the
6511 // top and a single exit at the bottom.
6512 // The point of exit cannot be a branch out of the structured block.
6513 // longjmp() and throw() must not violate the entry/exit criteria.
6514 CS->getCapturedDecl()->setNothrow();
6515 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006516
6517 OMPLoopDirective::HelperExprs B;
6518 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6519 // define the nested loops number.
6520 unsigned NestedLoopCount =
6521 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006522 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006523 VarsWithImplicitDSA, B);
6524 if (NestedLoopCount == 0)
6525 return StmtError();
6526
6527 assert((CurContext->isDependentContext() || B.builtAll()) &&
6528 "omp target parallel for loop exprs were not built");
6529
6530 if (!CurContext->isDependentContext()) {
6531 // Finalize the clauses that need pre-built expressions for CodeGen.
6532 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006533 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006534 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006535 B.NumIterations, *this, CurScope,
6536 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006537 return StmtError();
6538 }
6539 }
6540
6541 getCurFunction()->setHasBranchProtectedScope();
6542 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6543 NestedLoopCount, Clauses, AStmt,
6544 B, DSAStack->isCancelRegion());
6545}
6546
Alexey Bataev95b64a92017-05-30 16:00:04 +00006547/// Check for existence of a map clause in the list of clauses.
6548static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6549 const OpenMPClauseKind K) {
6550 return llvm::any_of(
6551 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6552}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006553
Alexey Bataev95b64a92017-05-30 16:00:04 +00006554template <typename... Params>
6555static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6556 const Params... ClauseTypes) {
6557 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006558}
6559
Michael Wong65f367f2015-07-21 13:44:28 +00006560StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6561 Stmt *AStmt,
6562 SourceLocation StartLoc,
6563 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006564 if (!AStmt)
6565 return StmtError();
6566
6567 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6568
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006569 // OpenMP [2.10.1, Restrictions, p. 97]
6570 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006571 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6572 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6573 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006574 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006575 return StmtError();
6576 }
6577
Michael Wong65f367f2015-07-21 13:44:28 +00006578 getCurFunction()->setHasBranchProtectedScope();
6579
6580 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6581 AStmt);
6582}
6583
Samuel Antaodf67fc42016-01-19 19:15:56 +00006584StmtResult
6585Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6586 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006587 SourceLocation EndLoc, Stmt *AStmt) {
6588 if (!AStmt)
6589 return StmtError();
6590
6591 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6592 // 1.2.2 OpenMP Language Terminology
6593 // Structured block - An executable statement with a single entry at the
6594 // top and a single exit at the bottom.
6595 // The point of exit cannot be a branch out of the structured block.
6596 // longjmp() and throw() must not violate the entry/exit criteria.
6597 CS->getCapturedDecl()->setNothrow();
6598 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
6599 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6600 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6601 // 1.2.2 OpenMP Language Terminology
6602 // Structured block - An executable statement with a single entry at the
6603 // top and a single exit at the bottom.
6604 // The point of exit cannot be a branch out of the structured block.
6605 // longjmp() and throw() must not violate the entry/exit criteria.
6606 CS->getCapturedDecl()->setNothrow();
6607 }
6608
Samuel Antaodf67fc42016-01-19 19:15:56 +00006609 // OpenMP [2.10.2, Restrictions, p. 99]
6610 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006611 if (!hasClauses(Clauses, OMPC_map)) {
6612 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6613 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006614 return StmtError();
6615 }
6616
Alexey Bataev7828b252017-11-21 17:08:48 +00006617 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6618 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006619}
6620
Samuel Antao72590762016-01-19 20:04:50 +00006621StmtResult
6622Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6623 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006624 SourceLocation EndLoc, Stmt *AStmt) {
6625 if (!AStmt)
6626 return StmtError();
6627
6628 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6629 // 1.2.2 OpenMP Language Terminology
6630 // Structured block - An executable statement with a single entry at the
6631 // top and a single exit at the bottom.
6632 // The point of exit cannot be a branch out of the structured block.
6633 // longjmp() and throw() must not violate the entry/exit criteria.
6634 CS->getCapturedDecl()->setNothrow();
6635 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
6636 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6637 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6638 // 1.2.2 OpenMP Language Terminology
6639 // Structured block - An executable statement with a single entry at the
6640 // top and a single exit at the bottom.
6641 // The point of exit cannot be a branch out of the structured block.
6642 // longjmp() and throw() must not violate the entry/exit criteria.
6643 CS->getCapturedDecl()->setNothrow();
6644 }
6645
Samuel Antao72590762016-01-19 20:04:50 +00006646 // OpenMP [2.10.3, Restrictions, p. 102]
6647 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006648 if (!hasClauses(Clauses, OMPC_map)) {
6649 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6650 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006651 return StmtError();
6652 }
6653
Alexey Bataev7828b252017-11-21 17:08:48 +00006654 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6655 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00006656}
6657
Samuel Antao686c70c2016-05-26 17:30:50 +00006658StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6659 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006660 SourceLocation EndLoc,
6661 Stmt *AStmt) {
6662 if (!AStmt)
6663 return StmtError();
6664
6665 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6666 // 1.2.2 OpenMP Language Terminology
6667 // Structured block - An executable statement with a single entry at the
6668 // top and a single exit at the bottom.
6669 // The point of exit cannot be a branch out of the structured block.
6670 // longjmp() and throw() must not violate the entry/exit criteria.
6671 CS->getCapturedDecl()->setNothrow();
6672 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
6673 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6674 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6675 // 1.2.2 OpenMP Language Terminology
6676 // Structured block - An executable statement with a single entry at the
6677 // top and a single exit at the bottom.
6678 // The point of exit cannot be a branch out of the structured block.
6679 // longjmp() and throw() must not violate the entry/exit criteria.
6680 CS->getCapturedDecl()->setNothrow();
6681 }
6682
Alexey Bataev95b64a92017-05-30 16:00:04 +00006683 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006684 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6685 return StmtError();
6686 }
Alexey Bataev7828b252017-11-21 17:08:48 +00006687 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
6688 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00006689}
6690
Alexey Bataev13314bf2014-10-09 04:18:56 +00006691StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6692 Stmt *AStmt, SourceLocation StartLoc,
6693 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006694 if (!AStmt)
6695 return StmtError();
6696
Alexey Bataev13314bf2014-10-09 04:18:56 +00006697 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6698 // 1.2.2 OpenMP Language Terminology
6699 // Structured block - An executable statement with a single entry at the
6700 // top and a single exit at the bottom.
6701 // The point of exit cannot be a branch out of the structured block.
6702 // longjmp() and throw() must not violate the entry/exit criteria.
6703 CS->getCapturedDecl()->setNothrow();
6704
6705 getCurFunction()->setHasBranchProtectedScope();
6706
Alexey Bataevceabd412017-11-30 18:01:54 +00006707 DSAStack->setParentTeamsRegionLoc(StartLoc);
6708
Alexey Bataev13314bf2014-10-09 04:18:56 +00006709 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6710}
6711
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006712StmtResult
6713Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6714 SourceLocation EndLoc,
6715 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006716 if (DSAStack->isParentNowaitRegion()) {
6717 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6718 return StmtError();
6719 }
6720 if (DSAStack->isParentOrderedRegion()) {
6721 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6722 return StmtError();
6723 }
6724 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6725 CancelRegion);
6726}
6727
Alexey Bataev87933c72015-09-18 08:07:34 +00006728StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6729 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006730 SourceLocation EndLoc,
6731 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006732 if (DSAStack->isParentNowaitRegion()) {
6733 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6734 return StmtError();
6735 }
6736 if (DSAStack->isParentOrderedRegion()) {
6737 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6738 return StmtError();
6739 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006740 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006741 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6742 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006743}
6744
Alexey Bataev382967a2015-12-08 12:06:20 +00006745static bool checkGrainsizeNumTasksClauses(Sema &S,
6746 ArrayRef<OMPClause *> Clauses) {
6747 OMPClause *PrevClause = nullptr;
6748 bool ErrorFound = false;
6749 for (auto *C : Clauses) {
6750 if (C->getClauseKind() == OMPC_grainsize ||
6751 C->getClauseKind() == OMPC_num_tasks) {
6752 if (!PrevClause)
6753 PrevClause = C;
6754 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6755 S.Diag(C->getLocStart(),
6756 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6757 << getOpenMPClauseName(C->getClauseKind())
6758 << getOpenMPClauseName(PrevClause->getClauseKind());
6759 S.Diag(PrevClause->getLocStart(),
6760 diag::note_omp_previous_grainsize_num_tasks)
6761 << getOpenMPClauseName(PrevClause->getClauseKind());
6762 ErrorFound = true;
6763 }
6764 }
6765 }
6766 return ErrorFound;
6767}
6768
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006769static bool checkReductionClauseWithNogroup(Sema &S,
6770 ArrayRef<OMPClause *> Clauses) {
6771 OMPClause *ReductionClause = nullptr;
6772 OMPClause *NogroupClause = nullptr;
6773 for (auto *C : Clauses) {
6774 if (C->getClauseKind() == OMPC_reduction) {
6775 ReductionClause = C;
6776 if (NogroupClause)
6777 break;
6778 continue;
6779 }
6780 if (C->getClauseKind() == OMPC_nogroup) {
6781 NogroupClause = C;
6782 if (ReductionClause)
6783 break;
6784 continue;
6785 }
6786 }
6787 if (ReductionClause && NogroupClause) {
6788 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6789 << SourceRange(NogroupClause->getLocStart(),
6790 NogroupClause->getLocEnd());
6791 return true;
6792 }
6793 return false;
6794}
6795
Alexey Bataev49f6e782015-12-01 04:18:41 +00006796StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6797 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6798 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006799 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006800 if (!AStmt)
6801 return StmtError();
6802
6803 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6804 OMPLoopDirective::HelperExprs B;
6805 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6806 // define the nested loops number.
6807 unsigned NestedLoopCount =
6808 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006809 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006810 VarsWithImplicitDSA, B);
6811 if (NestedLoopCount == 0)
6812 return StmtError();
6813
6814 assert((CurContext->isDependentContext() || B.builtAll()) &&
6815 "omp for loop exprs were not built");
6816
Alexey Bataev382967a2015-12-08 12:06:20 +00006817 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6818 // The grainsize clause and num_tasks clause are mutually exclusive and may
6819 // not appear on the same taskloop directive.
6820 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6821 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006822 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6823 // If a reduction clause is present on the taskloop directive, the nogroup
6824 // clause must not be specified.
6825 if (checkReductionClauseWithNogroup(*this, Clauses))
6826 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006827
Alexey Bataev49f6e782015-12-01 04:18:41 +00006828 getCurFunction()->setHasBranchProtectedScope();
6829 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6830 NestedLoopCount, Clauses, AStmt, B);
6831}
6832
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006833StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6834 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6835 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006836 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006837 if (!AStmt)
6838 return StmtError();
6839
6840 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6841 OMPLoopDirective::HelperExprs B;
6842 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6843 // define the nested loops number.
6844 unsigned NestedLoopCount =
6845 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6846 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6847 VarsWithImplicitDSA, B);
6848 if (NestedLoopCount == 0)
6849 return StmtError();
6850
6851 assert((CurContext->isDependentContext() || B.builtAll()) &&
6852 "omp for loop exprs were not built");
6853
Alexey Bataev5a3af132016-03-29 08:58:54 +00006854 if (!CurContext->isDependentContext()) {
6855 // Finalize the clauses that need pre-built expressions for CodeGen.
6856 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006857 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006858 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006859 B.NumIterations, *this, CurScope,
6860 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006861 return StmtError();
6862 }
6863 }
6864
Alexey Bataev382967a2015-12-08 12:06:20 +00006865 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6866 // The grainsize clause and num_tasks clause are mutually exclusive and may
6867 // not appear on the same taskloop directive.
6868 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6869 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006870 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6871 // If a reduction clause is present on the taskloop directive, the nogroup
6872 // clause must not be specified.
6873 if (checkReductionClauseWithNogroup(*this, Clauses))
6874 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00006875 if (checkSimdlenSafelenSpecified(*this, Clauses))
6876 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006877
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006878 getCurFunction()->setHasBranchProtectedScope();
6879 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6880 NestedLoopCount, Clauses, AStmt, B);
6881}
6882
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006883StmtResult Sema::ActOnOpenMPDistributeDirective(
6884 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6885 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006886 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006887 if (!AStmt)
6888 return StmtError();
6889
6890 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6891 OMPLoopDirective::HelperExprs B;
6892 // In presence of clause 'collapse' with number of loops, it will
6893 // define the nested loops number.
6894 unsigned NestedLoopCount =
6895 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6896 nullptr /*ordered not a clause on distribute*/, AStmt,
6897 *this, *DSAStack, VarsWithImplicitDSA, B);
6898 if (NestedLoopCount == 0)
6899 return StmtError();
6900
6901 assert((CurContext->isDependentContext() || B.builtAll()) &&
6902 "omp for loop exprs were not built");
6903
6904 getCurFunction()->setHasBranchProtectedScope();
6905 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6906 NestedLoopCount, Clauses, AStmt, B);
6907}
6908
Carlo Bertolli9925f152016-06-27 14:55:37 +00006909StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6910 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6911 SourceLocation EndLoc,
6912 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6913 if (!AStmt)
6914 return StmtError();
6915
6916 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6917 // 1.2.2 OpenMP Language Terminology
6918 // Structured block - An executable statement with a single entry at the
6919 // top and a single exit at the bottom.
6920 // The point of exit cannot be a branch out of the structured block.
6921 // longjmp() and throw() must not violate the entry/exit criteria.
6922 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00006923 for (int ThisCaptureLevel =
6924 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
6925 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6926 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6927 // 1.2.2 OpenMP Language Terminology
6928 // Structured block - An executable statement with a single entry at the
6929 // top and a single exit at the bottom.
6930 // The point of exit cannot be a branch out of the structured block.
6931 // longjmp() and throw() must not violate the entry/exit criteria.
6932 CS->getCapturedDecl()->setNothrow();
6933 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00006934
6935 OMPLoopDirective::HelperExprs B;
6936 // In presence of clause 'collapse' with number of loops, it will
6937 // define the nested loops number.
6938 unsigned NestedLoopCount = CheckOpenMPLoop(
6939 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00006940 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00006941 VarsWithImplicitDSA, B);
6942 if (NestedLoopCount == 0)
6943 return StmtError();
6944
6945 assert((CurContext->isDependentContext() || B.builtAll()) &&
6946 "omp for loop exprs were not built");
6947
6948 getCurFunction()->setHasBranchProtectedScope();
6949 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00006950 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
6951 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00006952}
6953
Kelvin Li4a39add2016-07-05 05:00:15 +00006954StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6955 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6956 SourceLocation EndLoc,
6957 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6958 if (!AStmt)
6959 return StmtError();
6960
6961 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6962 // 1.2.2 OpenMP Language Terminology
6963 // Structured block - An executable statement with a single entry at the
6964 // top and a single exit at the bottom.
6965 // The point of exit cannot be a branch out of the structured block.
6966 // longjmp() and throw() must not violate the entry/exit criteria.
6967 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00006968 for (int ThisCaptureLevel =
6969 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
6970 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6971 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6972 // 1.2.2 OpenMP Language Terminology
6973 // Structured block - An executable statement with a single entry at the
6974 // top and a single exit at the bottom.
6975 // The point of exit cannot be a branch out of the structured block.
6976 // longjmp() and throw() must not violate the entry/exit criteria.
6977 CS->getCapturedDecl()->setNothrow();
6978 }
Kelvin Li4a39add2016-07-05 05:00:15 +00006979
6980 OMPLoopDirective::HelperExprs B;
6981 // In presence of clause 'collapse' with number of loops, it will
6982 // define the nested loops number.
6983 unsigned NestedLoopCount = CheckOpenMPLoop(
6984 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00006985 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00006986 VarsWithImplicitDSA, B);
6987 if (NestedLoopCount == 0)
6988 return StmtError();
6989
6990 assert((CurContext->isDependentContext() || B.builtAll()) &&
6991 "omp for loop exprs were not built");
6992
Alexey Bataev438388c2017-11-22 18:34:02 +00006993 if (!CurContext->isDependentContext()) {
6994 // Finalize the clauses that need pre-built expressions for CodeGen.
6995 for (auto C : Clauses) {
6996 if (auto *LC = dyn_cast<OMPLinearClause>(C))
6997 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
6998 B.NumIterations, *this, CurScope,
6999 DSAStack))
7000 return StmtError();
7001 }
7002 }
7003
Kelvin Lic5609492016-07-15 04:39:07 +00007004 if (checkSimdlenSafelenSpecified(*this, Clauses))
7005 return StmtError();
7006
Kelvin Li4a39add2016-07-05 05:00:15 +00007007 getCurFunction()->setHasBranchProtectedScope();
7008 return OMPDistributeParallelForSimdDirective::Create(
7009 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7010}
7011
Kelvin Li787f3fc2016-07-06 04:45:38 +00007012StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7013 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7014 SourceLocation EndLoc,
7015 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7016 if (!AStmt)
7017 return StmtError();
7018
7019 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7020 // 1.2.2 OpenMP Language Terminology
7021 // Structured block - An executable statement with a single entry at the
7022 // top and a single exit at the bottom.
7023 // The point of exit cannot be a branch out of the structured block.
7024 // longjmp() and throw() must not violate the entry/exit criteria.
7025 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00007026 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7027 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7028 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7029 // 1.2.2 OpenMP Language Terminology
7030 // Structured block - An executable statement with a single entry at the
7031 // top and a single exit at the bottom.
7032 // The point of exit cannot be a branch out of the structured block.
7033 // longjmp() and throw() must not violate the entry/exit criteria.
7034 CS->getCapturedDecl()->setNothrow();
7035 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007036
7037 OMPLoopDirective::HelperExprs B;
7038 // In presence of clause 'collapse' with number of loops, it will
7039 // define the nested loops number.
7040 unsigned NestedLoopCount =
7041 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007042 nullptr /*ordered not a clause on distribute*/, CS, *this,
7043 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007044 if (NestedLoopCount == 0)
7045 return StmtError();
7046
7047 assert((CurContext->isDependentContext() || B.builtAll()) &&
7048 "omp for loop exprs were not built");
7049
Alexey Bataev438388c2017-11-22 18:34:02 +00007050 if (!CurContext->isDependentContext()) {
7051 // Finalize the clauses that need pre-built expressions for CodeGen.
7052 for (auto C : Clauses) {
7053 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7054 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7055 B.NumIterations, *this, CurScope,
7056 DSAStack))
7057 return StmtError();
7058 }
7059 }
7060
Kelvin Lic5609492016-07-15 04:39:07 +00007061 if (checkSimdlenSafelenSpecified(*this, Clauses))
7062 return StmtError();
7063
Kelvin Li787f3fc2016-07-06 04:45:38 +00007064 getCurFunction()->setHasBranchProtectedScope();
7065 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7066 NestedLoopCount, Clauses, AStmt, B);
7067}
7068
Kelvin Lia579b912016-07-14 02:54:56 +00007069StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7070 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7071 SourceLocation EndLoc,
7072 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7073 if (!AStmt)
7074 return StmtError();
7075
7076 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7077 // 1.2.2 OpenMP Language Terminology
7078 // Structured block - An executable statement with a single entry at the
7079 // top and a single exit at the bottom.
7080 // The point of exit cannot be a branch out of the structured block.
7081 // longjmp() and throw() must not violate the entry/exit criteria.
7082 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007083 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7084 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7085 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7086 // 1.2.2 OpenMP Language Terminology
7087 // Structured block - An executable statement with a single entry at the
7088 // top and a single exit at the bottom.
7089 // The point of exit cannot be a branch out of the structured block.
7090 // longjmp() and throw() must not violate the entry/exit criteria.
7091 CS->getCapturedDecl()->setNothrow();
7092 }
Kelvin Lia579b912016-07-14 02:54:56 +00007093
7094 OMPLoopDirective::HelperExprs B;
7095 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7096 // define the nested loops number.
7097 unsigned NestedLoopCount = CheckOpenMPLoop(
7098 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007099 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00007100 VarsWithImplicitDSA, B);
7101 if (NestedLoopCount == 0)
7102 return StmtError();
7103
7104 assert((CurContext->isDependentContext() || B.builtAll()) &&
7105 "omp target parallel for simd loop exprs were not built");
7106
7107 if (!CurContext->isDependentContext()) {
7108 // Finalize the clauses that need pre-built expressions for CodeGen.
7109 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007110 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00007111 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7112 B.NumIterations, *this, CurScope,
7113 DSAStack))
7114 return StmtError();
7115 }
7116 }
Kelvin Lic5609492016-07-15 04:39:07 +00007117 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00007118 return StmtError();
7119
7120 getCurFunction()->setHasBranchProtectedScope();
7121 return OMPTargetParallelForSimdDirective::Create(
7122 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7123}
7124
Kelvin Li986330c2016-07-20 22:57:10 +00007125StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7126 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7127 SourceLocation EndLoc,
7128 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7129 if (!AStmt)
7130 return StmtError();
7131
7132 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7133 // 1.2.2 OpenMP Language Terminology
7134 // Structured block - An executable statement with a single entry at the
7135 // top and a single exit at the bottom.
7136 // The point of exit cannot be a branch out of the structured block.
7137 // longjmp() and throw() must not violate the entry/exit criteria.
7138 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00007139 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7140 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7141 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7142 // 1.2.2 OpenMP Language Terminology
7143 // Structured block - An executable statement with a single entry at the
7144 // top and a single exit at the bottom.
7145 // The point of exit cannot be a branch out of the structured block.
7146 // longjmp() and throw() must not violate the entry/exit criteria.
7147 CS->getCapturedDecl()->setNothrow();
7148 }
7149
Kelvin Li986330c2016-07-20 22:57:10 +00007150 OMPLoopDirective::HelperExprs B;
7151 // In presence of clause 'collapse' with number of loops, it will define the
7152 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00007153 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00007154 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00007155 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00007156 VarsWithImplicitDSA, B);
7157 if (NestedLoopCount == 0)
7158 return StmtError();
7159
7160 assert((CurContext->isDependentContext() || B.builtAll()) &&
7161 "omp target simd loop exprs were not built");
7162
7163 if (!CurContext->isDependentContext()) {
7164 // Finalize the clauses that need pre-built expressions for CodeGen.
7165 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007166 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00007167 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7168 B.NumIterations, *this, CurScope,
7169 DSAStack))
7170 return StmtError();
7171 }
7172 }
7173
7174 if (checkSimdlenSafelenSpecified(*this, Clauses))
7175 return StmtError();
7176
7177 getCurFunction()->setHasBranchProtectedScope();
7178 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7179 NestedLoopCount, Clauses, AStmt, B);
7180}
7181
Kelvin Li02532872016-08-05 14:37:37 +00007182StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7183 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7184 SourceLocation EndLoc,
7185 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7186 if (!AStmt)
7187 return StmtError();
7188
7189 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7190 // 1.2.2 OpenMP Language Terminology
7191 // Structured block - An executable statement with a single entry at the
7192 // top and a single exit at the bottom.
7193 // The point of exit cannot be a branch out of the structured block.
7194 // longjmp() and throw() must not violate the entry/exit criteria.
7195 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007196 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7197 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7198 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7199 // 1.2.2 OpenMP Language Terminology
7200 // Structured block - An executable statement with a single entry at the
7201 // top and a single exit at the bottom.
7202 // The point of exit cannot be a branch out of the structured block.
7203 // longjmp() and throw() must not violate the entry/exit criteria.
7204 CS->getCapturedDecl()->setNothrow();
7205 }
Kelvin Li02532872016-08-05 14:37:37 +00007206
7207 OMPLoopDirective::HelperExprs B;
7208 // In presence of clause 'collapse' with number of loops, it will
7209 // define the nested loops number.
7210 unsigned NestedLoopCount =
7211 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007212 nullptr /*ordered not a clause on distribute*/, CS, *this,
7213 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00007214 if (NestedLoopCount == 0)
7215 return StmtError();
7216
7217 assert((CurContext->isDependentContext() || B.builtAll()) &&
7218 "omp teams distribute loop exprs were not built");
7219
7220 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007221
7222 DSAStack->setParentTeamsRegionLoc(StartLoc);
7223
David Majnemer9d168222016-08-05 17:44:54 +00007224 return OMPTeamsDistributeDirective::Create(
7225 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00007226}
7227
Kelvin Li4e325f72016-10-25 12:50:55 +00007228StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7229 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7230 SourceLocation EndLoc,
7231 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7232 if (!AStmt)
7233 return StmtError();
7234
7235 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7236 // 1.2.2 OpenMP Language Terminology
7237 // Structured block - An executable statement with a single entry at the
7238 // top and a single exit at the bottom.
7239 // The point of exit cannot be a branch out of the structured block.
7240 // longjmp() and throw() must not violate the entry/exit criteria.
7241 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00007242 for (int ThisCaptureLevel =
7243 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7244 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7245 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7246 // 1.2.2 OpenMP Language Terminology
7247 // Structured block - An executable statement with a single entry at the
7248 // top and a single exit at the bottom.
7249 // The point of exit cannot be a branch out of the structured block.
7250 // longjmp() and throw() must not violate the entry/exit criteria.
7251 CS->getCapturedDecl()->setNothrow();
7252 }
7253
Kelvin Li4e325f72016-10-25 12:50:55 +00007254
7255 OMPLoopDirective::HelperExprs B;
7256 // In presence of clause 'collapse' with number of loops, it will
7257 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00007258 unsigned NestedLoopCount = CheckOpenMPLoop(
7259 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00007260 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00007261 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00007262
7263 if (NestedLoopCount == 0)
7264 return StmtError();
7265
7266 assert((CurContext->isDependentContext() || B.builtAll()) &&
7267 "omp teams distribute simd loop exprs were not built");
7268
7269 if (!CurContext->isDependentContext()) {
7270 // Finalize the clauses that need pre-built expressions for CodeGen.
7271 for (auto C : Clauses) {
7272 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7273 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7274 B.NumIterations, *this, CurScope,
7275 DSAStack))
7276 return StmtError();
7277 }
7278 }
7279
7280 if (checkSimdlenSafelenSpecified(*this, Clauses))
7281 return StmtError();
7282
7283 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007284
7285 DSAStack->setParentTeamsRegionLoc(StartLoc);
7286
Kelvin Li4e325f72016-10-25 12:50:55 +00007287 return OMPTeamsDistributeSimdDirective::Create(
7288 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7289}
7290
Kelvin Li579e41c2016-11-30 23:51:03 +00007291StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7292 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7293 SourceLocation EndLoc,
7294 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7295 if (!AStmt)
7296 return StmtError();
7297
7298 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7299 // 1.2.2 OpenMP Language Terminology
7300 // Structured block - An executable statement with a single entry at the
7301 // top and a single exit at the bottom.
7302 // The point of exit cannot be a branch out of the structured block.
7303 // longjmp() and throw() must not violate the entry/exit criteria.
7304 CS->getCapturedDecl()->setNothrow();
7305
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007306 for (int ThisCaptureLevel =
7307 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7308 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7309 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7310 // 1.2.2 OpenMP Language Terminology
7311 // Structured block - An executable statement with a single entry at the
7312 // top and a single exit at the bottom.
7313 // The point of exit cannot be a branch out of the structured block.
7314 // longjmp() and throw() must not violate the entry/exit criteria.
7315 CS->getCapturedDecl()->setNothrow();
7316 }
7317
Kelvin Li579e41c2016-11-30 23:51:03 +00007318 OMPLoopDirective::HelperExprs B;
7319 // In presence of clause 'collapse' with number of loops, it will
7320 // define the nested loops number.
7321 auto NestedLoopCount = CheckOpenMPLoop(
7322 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007323 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00007324 VarsWithImplicitDSA, B);
7325
7326 if (NestedLoopCount == 0)
7327 return StmtError();
7328
7329 assert((CurContext->isDependentContext() || B.builtAll()) &&
7330 "omp for loop exprs were not built");
7331
7332 if (!CurContext->isDependentContext()) {
7333 // Finalize the clauses that need pre-built expressions for CodeGen.
7334 for (auto C : Clauses) {
7335 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7336 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7337 B.NumIterations, *this, CurScope,
7338 DSAStack))
7339 return StmtError();
7340 }
7341 }
7342
7343 if (checkSimdlenSafelenSpecified(*this, Clauses))
7344 return StmtError();
7345
7346 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007347
7348 DSAStack->setParentTeamsRegionLoc(StartLoc);
7349
Kelvin Li579e41c2016-11-30 23:51:03 +00007350 return OMPTeamsDistributeParallelForSimdDirective::Create(
7351 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7352}
7353
Kelvin Li7ade93f2016-12-09 03:24:30 +00007354StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7355 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7356 SourceLocation EndLoc,
7357 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7358 if (!AStmt)
7359 return StmtError();
7360
7361 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7362 // 1.2.2 OpenMP Language Terminology
7363 // Structured block - An executable statement with a single entry at the
7364 // top and a single exit at the bottom.
7365 // The point of exit cannot be a branch out of the structured block.
7366 // longjmp() and throw() must not violate the entry/exit criteria.
7367 CS->getCapturedDecl()->setNothrow();
7368
Carlo Bertolli62fae152017-11-20 20:46:39 +00007369 for (int ThisCaptureLevel =
7370 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7371 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7372 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7373 // 1.2.2 OpenMP Language Terminology
7374 // Structured block - An executable statement with a single entry at the
7375 // top and a single exit at the bottom.
7376 // The point of exit cannot be a branch out of the structured block.
7377 // longjmp() and throw() must not violate the entry/exit criteria.
7378 CS->getCapturedDecl()->setNothrow();
7379 }
7380
Kelvin Li7ade93f2016-12-09 03:24:30 +00007381 OMPLoopDirective::HelperExprs B;
7382 // In presence of clause 'collapse' with number of loops, it will
7383 // define the nested loops number.
7384 unsigned NestedLoopCount = CheckOpenMPLoop(
7385 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00007386 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00007387 VarsWithImplicitDSA, B);
7388
7389 if (NestedLoopCount == 0)
7390 return StmtError();
7391
7392 assert((CurContext->isDependentContext() || B.builtAll()) &&
7393 "omp for loop exprs were not built");
7394
Kelvin Li7ade93f2016-12-09 03:24:30 +00007395 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007396
7397 DSAStack->setParentTeamsRegionLoc(StartLoc);
7398
Kelvin Li7ade93f2016-12-09 03:24:30 +00007399 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007400 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7401 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00007402}
7403
Kelvin Libf594a52016-12-17 05:48:59 +00007404StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7405 Stmt *AStmt,
7406 SourceLocation StartLoc,
7407 SourceLocation EndLoc) {
7408 if (!AStmt)
7409 return StmtError();
7410
7411 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7412 // 1.2.2 OpenMP Language Terminology
7413 // Structured block - An executable statement with a single entry at the
7414 // top and a single exit at the bottom.
7415 // The point of exit cannot be a branch out of the structured block.
7416 // longjmp() and throw() must not violate the entry/exit criteria.
7417 CS->getCapturedDecl()->setNothrow();
7418
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00007419 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7420 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7421 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7422 // 1.2.2 OpenMP Language Terminology
7423 // Structured block - An executable statement with a single entry at the
7424 // top and a single exit at the bottom.
7425 // The point of exit cannot be a branch out of the structured block.
7426 // longjmp() and throw() must not violate the entry/exit criteria.
7427 CS->getCapturedDecl()->setNothrow();
7428 }
Kelvin Libf594a52016-12-17 05:48:59 +00007429 getCurFunction()->setHasBranchProtectedScope();
7430
7431 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7432 AStmt);
7433}
7434
Kelvin Li83c451e2016-12-25 04:52:54 +00007435StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7436 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7437 SourceLocation EndLoc,
7438 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7439 if (!AStmt)
7440 return StmtError();
7441
7442 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7443 // 1.2.2 OpenMP Language Terminology
7444 // Structured block - An executable statement with a single entry at the
7445 // top and a single exit at the bottom.
7446 // The point of exit cannot be a branch out of the structured block.
7447 // longjmp() and throw() must not violate the entry/exit criteria.
7448 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007449 for (int ThisCaptureLevel =
7450 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
7451 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7452 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7453 // 1.2.2 OpenMP Language Terminology
7454 // Structured block - An executable statement with a single entry at the
7455 // top and a single exit at the bottom.
7456 // The point of exit cannot be a branch out of the structured block.
7457 // longjmp() and throw() must not violate the entry/exit criteria.
7458 CS->getCapturedDecl()->setNothrow();
7459 }
Kelvin Li83c451e2016-12-25 04:52:54 +00007460
7461 OMPLoopDirective::HelperExprs B;
7462 // In presence of clause 'collapse' with number of loops, it will
7463 // define the nested loops number.
7464 auto NestedLoopCount = CheckOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007465 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
7466 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00007467 VarsWithImplicitDSA, B);
7468 if (NestedLoopCount == 0)
7469 return StmtError();
7470
7471 assert((CurContext->isDependentContext() || B.builtAll()) &&
7472 "omp target teams distribute loop exprs were not built");
7473
7474 getCurFunction()->setHasBranchProtectedScope();
7475 return OMPTargetTeamsDistributeDirective::Create(
7476 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7477}
7478
Kelvin Li80e8f562016-12-29 22:16:30 +00007479StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7480 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7481 SourceLocation EndLoc,
7482 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7483 if (!AStmt)
7484 return StmtError();
7485
7486 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7487 // 1.2.2 OpenMP Language Terminology
7488 // Structured block - An executable statement with a single entry at the
7489 // top and a single exit at the bottom.
7490 // The point of exit cannot be a branch out of the structured block.
7491 // longjmp() and throw() must not violate the entry/exit criteria.
7492 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00007493 for (int ThisCaptureLevel =
7494 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
7495 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7496 CS = cast<CapturedStmt>(CS->getCapturedStmt());
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();
7503 }
7504
Kelvin Li80e8f562016-12-29 22:16:30 +00007505 OMPLoopDirective::HelperExprs B;
7506 // In presence of clause 'collapse' with number of loops, it will
7507 // define the nested loops number.
7508 auto NestedLoopCount = CheckOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00007509 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7510 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00007511 VarsWithImplicitDSA, B);
7512 if (NestedLoopCount == 0)
7513 return StmtError();
7514
7515 assert((CurContext->isDependentContext() || B.builtAll()) &&
7516 "omp target teams distribute parallel for loop exprs were not built");
7517
Alexey Bataev647dd842018-01-15 20:59:40 +00007518 if (!CurContext->isDependentContext()) {
7519 // Finalize the clauses that need pre-built expressions for CodeGen.
7520 for (auto C : Clauses) {
7521 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7522 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7523 B.NumIterations, *this, CurScope,
7524 DSAStack))
7525 return StmtError();
7526 }
7527 }
7528
Kelvin Li80e8f562016-12-29 22:16:30 +00007529 getCurFunction()->setHasBranchProtectedScope();
7530 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00007531 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7532 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00007533}
7534
Kelvin Li1851df52017-01-03 05:23:48 +00007535StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7536 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7537 SourceLocation EndLoc,
7538 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7539 if (!AStmt)
7540 return StmtError();
7541
7542 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7543 // 1.2.2 OpenMP Language Terminology
7544 // Structured block - An executable statement with a single entry at the
7545 // top and a single exit at the bottom.
7546 // The point of exit cannot be a branch out of the structured block.
7547 // longjmp() and throw() must not violate the entry/exit criteria.
7548 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00007549 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
7550 OMPD_target_teams_distribute_parallel_for_simd);
7551 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7552 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7553 // 1.2.2 OpenMP Language Terminology
7554 // Structured block - An executable statement with a single entry at the
7555 // top and a single exit at the bottom.
7556 // The point of exit cannot be a branch out of the structured block.
7557 // longjmp() and throw() must not violate the entry/exit criteria.
7558 CS->getCapturedDecl()->setNothrow();
7559 }
Kelvin Li1851df52017-01-03 05:23:48 +00007560
7561 OMPLoopDirective::HelperExprs B;
7562 // In presence of clause 'collapse' with number of loops, it will
7563 // define the nested loops number.
Alexey Bataev647dd842018-01-15 20:59:40 +00007564 auto NestedLoopCount =
7565 CheckOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
7566 getCollapseNumberExpr(Clauses),
7567 nullptr /*ordered not a clause on distribute*/, CS, *this,
7568 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00007569 if (NestedLoopCount == 0)
7570 return StmtError();
7571
7572 assert((CurContext->isDependentContext() || B.builtAll()) &&
7573 "omp target teams distribute parallel for simd loop exprs were not "
7574 "built");
7575
7576 if (!CurContext->isDependentContext()) {
7577 // Finalize the clauses that need pre-built expressions for CodeGen.
7578 for (auto C : Clauses) {
7579 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7580 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7581 B.NumIterations, *this, CurScope,
7582 DSAStack))
7583 return StmtError();
7584 }
7585 }
7586
Alexey Bataev438388c2017-11-22 18:34:02 +00007587 if (checkSimdlenSafelenSpecified(*this, Clauses))
7588 return StmtError();
7589
Kelvin Li1851df52017-01-03 05:23:48 +00007590 getCurFunction()->setHasBranchProtectedScope();
7591 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7592 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7593}
7594
Kelvin Lida681182017-01-10 18:08:18 +00007595StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7596 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7597 SourceLocation EndLoc,
7598 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7599 if (!AStmt)
7600 return StmtError();
7601
7602 auto *CS = cast<CapturedStmt>(AStmt);
7603 // 1.2.2 OpenMP Language Terminology
7604 // Structured block - An executable statement with a single entry at the
7605 // top and a single exit at the bottom.
7606 // The point of exit cannot be a branch out of the structured block.
7607 // longjmp() and throw() must not violate the entry/exit criteria.
7608 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007609 for (int ThisCaptureLevel =
7610 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
7611 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7612 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7613 // 1.2.2 OpenMP Language Terminology
7614 // Structured block - An executable statement with a single entry at the
7615 // top and a single exit at the bottom.
7616 // The point of exit cannot be a branch out of the structured block.
7617 // longjmp() and throw() must not violate the entry/exit criteria.
7618 CS->getCapturedDecl()->setNothrow();
7619 }
Kelvin Lida681182017-01-10 18:08:18 +00007620
7621 OMPLoopDirective::HelperExprs B;
7622 // In presence of clause 'collapse' with number of loops, it will
7623 // define the nested loops number.
7624 auto NestedLoopCount = CheckOpenMPLoop(
7625 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007626 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00007627 VarsWithImplicitDSA, B);
7628 if (NestedLoopCount == 0)
7629 return StmtError();
7630
7631 assert((CurContext->isDependentContext() || B.builtAll()) &&
7632 "omp target teams distribute simd loop exprs were not built");
7633
Alexey Bataev438388c2017-11-22 18:34:02 +00007634 if (!CurContext->isDependentContext()) {
7635 // Finalize the clauses that need pre-built expressions for CodeGen.
7636 for (auto C : Clauses) {
7637 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7638 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7639 B.NumIterations, *this, CurScope,
7640 DSAStack))
7641 return StmtError();
7642 }
7643 }
7644
7645 if (checkSimdlenSafelenSpecified(*this, Clauses))
7646 return StmtError();
7647
Kelvin Lida681182017-01-10 18:08:18 +00007648 getCurFunction()->setHasBranchProtectedScope();
7649 return OMPTargetTeamsDistributeSimdDirective::Create(
7650 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7651}
7652
Alexey Bataeved09d242014-05-28 05:53:51 +00007653OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007654 SourceLocation StartLoc,
7655 SourceLocation LParenLoc,
7656 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007657 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007658 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00007659 case OMPC_final:
7660 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7661 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007662 case OMPC_num_threads:
7663 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7664 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007665 case OMPC_safelen:
7666 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7667 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007668 case OMPC_simdlen:
7669 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7670 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007671 case OMPC_collapse:
7672 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7673 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007674 case OMPC_ordered:
7675 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7676 break;
Michael Wonge710d542015-08-07 16:16:36 +00007677 case OMPC_device:
7678 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7679 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007680 case OMPC_num_teams:
7681 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7682 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007683 case OMPC_thread_limit:
7684 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7685 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007686 case OMPC_priority:
7687 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7688 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007689 case OMPC_grainsize:
7690 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7691 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007692 case OMPC_num_tasks:
7693 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7694 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007695 case OMPC_hint:
7696 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7697 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007698 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007699 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007700 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007701 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007702 case OMPC_private:
7703 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007704 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007705 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007706 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007707 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007708 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007709 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007710 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007711 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007712 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007713 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007714 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007715 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007716 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007717 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007718 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007719 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007720 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007721 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007722 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007723 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007724 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007725 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007726 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007727 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007728 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007729 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007730 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007731 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007732 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007733 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007734 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007735 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007736 llvm_unreachable("Clause is not allowed.");
7737 }
7738 return Res;
7739}
7740
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007741// An OpenMP directive such as 'target parallel' has two captured regions:
7742// for the 'target' and 'parallel' respectively. This function returns
7743// the region in which to capture expressions associated with a clause.
7744// A return value of OMPD_unknown signifies that the expression should not
7745// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007746static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7747 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7748 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007749 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007750 switch (CKind) {
7751 case OMPC_if:
7752 switch (DKind) {
7753 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007754 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007755 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007756 // If this clause applies to the nested 'parallel' region, capture within
7757 // the 'target' region, otherwise do not capture.
7758 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7759 CaptureRegion = OMPD_target;
7760 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00007761 case OMPD_target_teams_distribute_parallel_for:
7762 case OMPD_target_teams_distribute_parallel_for_simd:
7763 // If this clause applies to the nested 'parallel' region, capture within
7764 // the 'teams' region, otherwise do not capture.
7765 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7766 CaptureRegion = OMPD_teams;
7767 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007768 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007769 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007770 CaptureRegion = OMPD_teams;
7771 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007772 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00007773 case OMPD_target_enter_data:
7774 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007775 CaptureRegion = OMPD_task;
7776 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007777 case OMPD_cancel:
7778 case OMPD_parallel:
7779 case OMPD_parallel_sections:
7780 case OMPD_parallel_for:
7781 case OMPD_parallel_for_simd:
7782 case OMPD_target:
7783 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007784 case OMPD_target_teams:
7785 case OMPD_target_teams_distribute:
7786 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007787 case OMPD_distribute_parallel_for:
7788 case OMPD_distribute_parallel_for_simd:
7789 case OMPD_task:
7790 case OMPD_taskloop:
7791 case OMPD_taskloop_simd:
7792 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007793 // Do not capture if-clause expressions.
7794 break;
7795 case OMPD_threadprivate:
7796 case OMPD_taskyield:
7797 case OMPD_barrier:
7798 case OMPD_taskwait:
7799 case OMPD_cancellation_point:
7800 case OMPD_flush:
7801 case OMPD_declare_reduction:
7802 case OMPD_declare_simd:
7803 case OMPD_declare_target:
7804 case OMPD_end_declare_target:
7805 case OMPD_teams:
7806 case OMPD_simd:
7807 case OMPD_for:
7808 case OMPD_for_simd:
7809 case OMPD_sections:
7810 case OMPD_section:
7811 case OMPD_single:
7812 case OMPD_master:
7813 case OMPD_critical:
7814 case OMPD_taskgroup:
7815 case OMPD_distribute:
7816 case OMPD_ordered:
7817 case OMPD_atomic:
7818 case OMPD_distribute_simd:
7819 case OMPD_teams_distribute:
7820 case OMPD_teams_distribute_simd:
7821 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7822 case OMPD_unknown:
7823 llvm_unreachable("Unknown OpenMP directive");
7824 }
7825 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007826 case OMPC_num_threads:
7827 switch (DKind) {
7828 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007829 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007830 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007831 CaptureRegion = OMPD_target;
7832 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007833 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007834 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00007835 case OMPD_target_teams_distribute_parallel_for:
7836 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007837 CaptureRegion = OMPD_teams;
7838 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007839 case OMPD_parallel:
7840 case OMPD_parallel_sections:
7841 case OMPD_parallel_for:
7842 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007843 case OMPD_distribute_parallel_for:
7844 case OMPD_distribute_parallel_for_simd:
7845 // Do not capture num_threads-clause expressions.
7846 break;
7847 case OMPD_target_data:
7848 case OMPD_target_enter_data:
7849 case OMPD_target_exit_data:
7850 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007851 case OMPD_target:
7852 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007853 case OMPD_target_teams:
7854 case OMPD_target_teams_distribute:
7855 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007856 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007857 case OMPD_task:
7858 case OMPD_taskloop:
7859 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007860 case OMPD_threadprivate:
7861 case OMPD_taskyield:
7862 case OMPD_barrier:
7863 case OMPD_taskwait:
7864 case OMPD_cancellation_point:
7865 case OMPD_flush:
7866 case OMPD_declare_reduction:
7867 case OMPD_declare_simd:
7868 case OMPD_declare_target:
7869 case OMPD_end_declare_target:
7870 case OMPD_teams:
7871 case OMPD_simd:
7872 case OMPD_for:
7873 case OMPD_for_simd:
7874 case OMPD_sections:
7875 case OMPD_section:
7876 case OMPD_single:
7877 case OMPD_master:
7878 case OMPD_critical:
7879 case OMPD_taskgroup:
7880 case OMPD_distribute:
7881 case OMPD_ordered:
7882 case OMPD_atomic:
7883 case OMPD_distribute_simd:
7884 case OMPD_teams_distribute:
7885 case OMPD_teams_distribute_simd:
7886 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7887 case OMPD_unknown:
7888 llvm_unreachable("Unknown OpenMP directive");
7889 }
7890 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007891 case OMPC_num_teams:
7892 switch (DKind) {
7893 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007894 case OMPD_target_teams_distribute:
7895 case OMPD_target_teams_distribute_simd:
7896 case OMPD_target_teams_distribute_parallel_for:
7897 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007898 CaptureRegion = OMPD_target;
7899 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007900 case OMPD_teams_distribute_parallel_for:
7901 case OMPD_teams_distribute_parallel_for_simd:
7902 case OMPD_teams:
7903 case OMPD_teams_distribute:
7904 case OMPD_teams_distribute_simd:
7905 // Do not capture num_teams-clause expressions.
7906 break;
7907 case OMPD_distribute_parallel_for:
7908 case OMPD_distribute_parallel_for_simd:
7909 case OMPD_task:
7910 case OMPD_taskloop:
7911 case OMPD_taskloop_simd:
7912 case OMPD_target_data:
7913 case OMPD_target_enter_data:
7914 case OMPD_target_exit_data:
7915 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007916 case OMPD_cancel:
7917 case OMPD_parallel:
7918 case OMPD_parallel_sections:
7919 case OMPD_parallel_for:
7920 case OMPD_parallel_for_simd:
7921 case OMPD_target:
7922 case OMPD_target_simd:
7923 case OMPD_target_parallel:
7924 case OMPD_target_parallel_for:
7925 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007926 case OMPD_threadprivate:
7927 case OMPD_taskyield:
7928 case OMPD_barrier:
7929 case OMPD_taskwait:
7930 case OMPD_cancellation_point:
7931 case OMPD_flush:
7932 case OMPD_declare_reduction:
7933 case OMPD_declare_simd:
7934 case OMPD_declare_target:
7935 case OMPD_end_declare_target:
7936 case OMPD_simd:
7937 case OMPD_for:
7938 case OMPD_for_simd:
7939 case OMPD_sections:
7940 case OMPD_section:
7941 case OMPD_single:
7942 case OMPD_master:
7943 case OMPD_critical:
7944 case OMPD_taskgroup:
7945 case OMPD_distribute:
7946 case OMPD_ordered:
7947 case OMPD_atomic:
7948 case OMPD_distribute_simd:
7949 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7950 case OMPD_unknown:
7951 llvm_unreachable("Unknown OpenMP directive");
7952 }
7953 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007954 case OMPC_thread_limit:
7955 switch (DKind) {
7956 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007957 case OMPD_target_teams_distribute:
7958 case OMPD_target_teams_distribute_simd:
7959 case OMPD_target_teams_distribute_parallel_for:
7960 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007961 CaptureRegion = OMPD_target;
7962 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007963 case OMPD_teams_distribute_parallel_for:
7964 case OMPD_teams_distribute_parallel_for_simd:
7965 case OMPD_teams:
7966 case OMPD_teams_distribute:
7967 case OMPD_teams_distribute_simd:
7968 // Do not capture thread_limit-clause expressions.
7969 break;
7970 case OMPD_distribute_parallel_for:
7971 case OMPD_distribute_parallel_for_simd:
7972 case OMPD_task:
7973 case OMPD_taskloop:
7974 case OMPD_taskloop_simd:
7975 case OMPD_target_data:
7976 case OMPD_target_enter_data:
7977 case OMPD_target_exit_data:
7978 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007979 case OMPD_cancel:
7980 case OMPD_parallel:
7981 case OMPD_parallel_sections:
7982 case OMPD_parallel_for:
7983 case OMPD_parallel_for_simd:
7984 case OMPD_target:
7985 case OMPD_target_simd:
7986 case OMPD_target_parallel:
7987 case OMPD_target_parallel_for:
7988 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007989 case OMPD_threadprivate:
7990 case OMPD_taskyield:
7991 case OMPD_barrier:
7992 case OMPD_taskwait:
7993 case OMPD_cancellation_point:
7994 case OMPD_flush:
7995 case OMPD_declare_reduction:
7996 case OMPD_declare_simd:
7997 case OMPD_declare_target:
7998 case OMPD_end_declare_target:
7999 case OMPD_simd:
8000 case OMPD_for:
8001 case OMPD_for_simd:
8002 case OMPD_sections:
8003 case OMPD_section:
8004 case OMPD_single:
8005 case OMPD_master:
8006 case OMPD_critical:
8007 case OMPD_taskgroup:
8008 case OMPD_distribute:
8009 case OMPD_ordered:
8010 case OMPD_atomic:
8011 case OMPD_distribute_simd:
8012 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8013 case OMPD_unknown:
8014 llvm_unreachable("Unknown OpenMP directive");
8015 }
8016 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008017 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008018 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008019 case OMPD_parallel_for:
8020 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008021 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008022 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008023 case OMPD_teams_distribute_parallel_for:
8024 case OMPD_teams_distribute_parallel_for_simd:
8025 case OMPD_target_parallel_for:
8026 case OMPD_target_parallel_for_simd:
8027 case OMPD_target_teams_distribute_parallel_for:
8028 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008029 CaptureRegion = OMPD_parallel;
8030 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008031 case OMPD_for:
8032 case OMPD_for_simd:
8033 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008034 break;
8035 case OMPD_task:
8036 case OMPD_taskloop:
8037 case OMPD_taskloop_simd:
8038 case OMPD_target_data:
8039 case OMPD_target_enter_data:
8040 case OMPD_target_exit_data:
8041 case OMPD_target_update:
8042 case OMPD_teams:
8043 case OMPD_teams_distribute:
8044 case OMPD_teams_distribute_simd:
8045 case OMPD_target_teams_distribute:
8046 case OMPD_target_teams_distribute_simd:
8047 case OMPD_target:
8048 case OMPD_target_simd:
8049 case OMPD_target_parallel:
8050 case OMPD_cancel:
8051 case OMPD_parallel:
8052 case OMPD_parallel_sections:
8053 case OMPD_threadprivate:
8054 case OMPD_taskyield:
8055 case OMPD_barrier:
8056 case OMPD_taskwait:
8057 case OMPD_cancellation_point:
8058 case OMPD_flush:
8059 case OMPD_declare_reduction:
8060 case OMPD_declare_simd:
8061 case OMPD_declare_target:
8062 case OMPD_end_declare_target:
8063 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008064 case OMPD_sections:
8065 case OMPD_section:
8066 case OMPD_single:
8067 case OMPD_master:
8068 case OMPD_critical:
8069 case OMPD_taskgroup:
8070 case OMPD_distribute:
8071 case OMPD_ordered:
8072 case OMPD_atomic:
8073 case OMPD_distribute_simd:
8074 case OMPD_target_teams:
8075 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8076 case OMPD_unknown:
8077 llvm_unreachable("Unknown OpenMP directive");
8078 }
8079 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008080 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008081 switch (DKind) {
8082 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008083 case OMPD_teams_distribute_parallel_for_simd:
8084 case OMPD_teams_distribute:
8085 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008086 case OMPD_target_teams_distribute_parallel_for:
8087 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008088 case OMPD_target_teams_distribute:
8089 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008090 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008091 break;
8092 case OMPD_distribute_parallel_for:
8093 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008094 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008095 case OMPD_distribute_simd:
8096 // Do not capture thread_limit-clause expressions.
8097 break;
8098 case OMPD_parallel_for:
8099 case OMPD_parallel_for_simd:
8100 case OMPD_target_parallel_for_simd:
8101 case OMPD_target_parallel_for:
8102 case OMPD_task:
8103 case OMPD_taskloop:
8104 case OMPD_taskloop_simd:
8105 case OMPD_target_data:
8106 case OMPD_target_enter_data:
8107 case OMPD_target_exit_data:
8108 case OMPD_target_update:
8109 case OMPD_teams:
8110 case OMPD_target:
8111 case OMPD_target_simd:
8112 case OMPD_target_parallel:
8113 case OMPD_cancel:
8114 case OMPD_parallel:
8115 case OMPD_parallel_sections:
8116 case OMPD_threadprivate:
8117 case OMPD_taskyield:
8118 case OMPD_barrier:
8119 case OMPD_taskwait:
8120 case OMPD_cancellation_point:
8121 case OMPD_flush:
8122 case OMPD_declare_reduction:
8123 case OMPD_declare_simd:
8124 case OMPD_declare_target:
8125 case OMPD_end_declare_target:
8126 case OMPD_simd:
8127 case OMPD_for:
8128 case OMPD_for_simd:
8129 case OMPD_sections:
8130 case OMPD_section:
8131 case OMPD_single:
8132 case OMPD_master:
8133 case OMPD_critical:
8134 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008135 case OMPD_ordered:
8136 case OMPD_atomic:
8137 case OMPD_target_teams:
8138 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8139 case OMPD_unknown:
8140 llvm_unreachable("Unknown OpenMP directive");
8141 }
8142 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008143 case OMPC_device:
8144 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008145 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008146 case OMPD_target_enter_data:
8147 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00008148 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00008149 case OMPD_target_simd:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008150 CaptureRegion = OMPD_task;
8151 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008152 case OMPD_target_teams:
8153 case OMPD_target_teams_distribute:
8154 case OMPD_target_teams_distribute_simd:
8155 case OMPD_target_teams_distribute_parallel_for:
8156 case OMPD_target_teams_distribute_parallel_for_simd:
8157 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008158 case OMPD_target_parallel:
8159 case OMPD_target_parallel_for:
8160 case OMPD_target_parallel_for_simd:
8161 // Do not capture device-clause expressions.
8162 break;
8163 case OMPD_teams_distribute_parallel_for:
8164 case OMPD_teams_distribute_parallel_for_simd:
8165 case OMPD_teams:
8166 case OMPD_teams_distribute:
8167 case OMPD_teams_distribute_simd:
8168 case OMPD_distribute_parallel_for:
8169 case OMPD_distribute_parallel_for_simd:
8170 case OMPD_task:
8171 case OMPD_taskloop:
8172 case OMPD_taskloop_simd:
8173 case OMPD_cancel:
8174 case OMPD_parallel:
8175 case OMPD_parallel_sections:
8176 case OMPD_parallel_for:
8177 case OMPD_parallel_for_simd:
8178 case OMPD_threadprivate:
8179 case OMPD_taskyield:
8180 case OMPD_barrier:
8181 case OMPD_taskwait:
8182 case OMPD_cancellation_point:
8183 case OMPD_flush:
8184 case OMPD_declare_reduction:
8185 case OMPD_declare_simd:
8186 case OMPD_declare_target:
8187 case OMPD_end_declare_target:
8188 case OMPD_simd:
8189 case OMPD_for:
8190 case OMPD_for_simd:
8191 case OMPD_sections:
8192 case OMPD_section:
8193 case OMPD_single:
8194 case OMPD_master:
8195 case OMPD_critical:
8196 case OMPD_taskgroup:
8197 case OMPD_distribute:
8198 case OMPD_ordered:
8199 case OMPD_atomic:
8200 case OMPD_distribute_simd:
8201 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8202 case OMPD_unknown:
8203 llvm_unreachable("Unknown OpenMP directive");
8204 }
8205 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008206 case OMPC_firstprivate:
8207 case OMPC_lastprivate:
8208 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008209 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008210 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008211 case OMPC_linear:
8212 case OMPC_default:
8213 case OMPC_proc_bind:
8214 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008215 case OMPC_safelen:
8216 case OMPC_simdlen:
8217 case OMPC_collapse:
8218 case OMPC_private:
8219 case OMPC_shared:
8220 case OMPC_aligned:
8221 case OMPC_copyin:
8222 case OMPC_copyprivate:
8223 case OMPC_ordered:
8224 case OMPC_nowait:
8225 case OMPC_untied:
8226 case OMPC_mergeable:
8227 case OMPC_threadprivate:
8228 case OMPC_flush:
8229 case OMPC_read:
8230 case OMPC_write:
8231 case OMPC_update:
8232 case OMPC_capture:
8233 case OMPC_seq_cst:
8234 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008235 case OMPC_threads:
8236 case OMPC_simd:
8237 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008238 case OMPC_priority:
8239 case OMPC_grainsize:
8240 case OMPC_nogroup:
8241 case OMPC_num_tasks:
8242 case OMPC_hint:
8243 case OMPC_defaultmap:
8244 case OMPC_unknown:
8245 case OMPC_uniform:
8246 case OMPC_to:
8247 case OMPC_from:
8248 case OMPC_use_device_ptr:
8249 case OMPC_is_device_ptr:
8250 llvm_unreachable("Unexpected OpenMP clause.");
8251 }
8252 return CaptureRegion;
8253}
8254
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008255OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8256 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008257 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008258 SourceLocation NameModifierLoc,
8259 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008260 SourceLocation EndLoc) {
8261 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008262 Stmt *HelperValStmt = nullptr;
8263 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008264 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8265 !Condition->isInstantiationDependent() &&
8266 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008267 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008268 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008269 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008270
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008271 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008272
8273 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8274 CaptureRegion =
8275 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00008276 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008277 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008278 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8279 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8280 HelperValStmt = buildPreInits(Context, Captures);
8281 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008282 }
8283
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008284 return new (Context)
8285 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8286 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008287}
8288
Alexey Bataev3778b602014-07-17 07:32:53 +00008289OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8290 SourceLocation StartLoc,
8291 SourceLocation LParenLoc,
8292 SourceLocation EndLoc) {
8293 Expr *ValExpr = Condition;
8294 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8295 !Condition->isInstantiationDependent() &&
8296 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008297 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00008298 if (Val.isInvalid())
8299 return nullptr;
8300
Richard Smith03a4aa32016-06-23 19:02:52 +00008301 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00008302 }
8303
8304 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8305}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008306ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8307 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00008308 if (!Op)
8309 return ExprError();
8310
8311 class IntConvertDiagnoser : public ICEConvertDiagnoser {
8312 public:
8313 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00008314 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00008315 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8316 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008317 return S.Diag(Loc, diag::err_omp_not_integral) << T;
8318 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008319 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8320 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008321 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8322 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008323 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8324 QualType T,
8325 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008326 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8327 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008328 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8329 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008330 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008331 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008332 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008333 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8334 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008335 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8336 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008337 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8338 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008339 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008340 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008341 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008342 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8343 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008344 llvm_unreachable("conversion functions are permitted");
8345 }
8346 } ConvertDiagnoser;
8347 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8348}
8349
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008350static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00008351 OpenMPClauseKind CKind,
8352 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008353 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8354 !ValExpr->isInstantiationDependent()) {
8355 SourceLocation Loc = ValExpr->getExprLoc();
8356 ExprResult Value =
8357 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8358 if (Value.isInvalid())
8359 return false;
8360
8361 ValExpr = Value.get();
8362 // The expression must evaluate to a non-negative integer value.
8363 llvm::APSInt Result;
8364 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00008365 Result.isSigned() &&
8366 !((!StrictlyPositive && Result.isNonNegative()) ||
8367 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008368 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008369 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8370 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008371 return false;
8372 }
8373 }
8374 return true;
8375}
8376
Alexey Bataev568a8332014-03-06 06:15:19 +00008377OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8378 SourceLocation StartLoc,
8379 SourceLocation LParenLoc,
8380 SourceLocation EndLoc) {
8381 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008382 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008383
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008384 // OpenMP [2.5, Restrictions]
8385 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00008386 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8387 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008388 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008389
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008390 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00008391 OpenMPDirectiveKind CaptureRegion =
8392 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8393 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008394 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008395 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8396 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8397 HelperValStmt = buildPreInits(Context, Captures);
8398 }
8399
8400 return new (Context) OMPNumThreadsClause(
8401 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00008402}
8403
Alexey Bataev62c87d22014-03-21 04:51:18 +00008404ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008405 OpenMPClauseKind CKind,
8406 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008407 if (!E)
8408 return ExprError();
8409 if (E->isValueDependent() || E->isTypeDependent() ||
8410 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008411 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008412 llvm::APSInt Result;
8413 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8414 if (ICE.isInvalid())
8415 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008416 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8417 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008418 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008419 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8420 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00008421 return ExprError();
8422 }
Alexander Musman09184fe2014-09-30 05:29:28 +00008423 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8424 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8425 << E->getSourceRange();
8426 return ExprError();
8427 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008428 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8429 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00008430 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008431 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00008432 return ICE;
8433}
8434
8435OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8436 SourceLocation LParenLoc,
8437 SourceLocation EndLoc) {
8438 // OpenMP [2.8.1, simd construct, Description]
8439 // The parameter of the safelen clause must be a constant
8440 // positive integer expression.
8441 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8442 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008443 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008444 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008445 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00008446}
8447
Alexey Bataev66b15b52015-08-21 11:14:16 +00008448OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8449 SourceLocation LParenLoc,
8450 SourceLocation EndLoc) {
8451 // OpenMP [2.8.1, simd construct, Description]
8452 // The parameter of the simdlen clause must be a constant
8453 // positive integer expression.
8454 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8455 if (Simdlen.isInvalid())
8456 return nullptr;
8457 return new (Context)
8458 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8459}
8460
Alexander Musman64d33f12014-06-04 07:53:32 +00008461OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8462 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00008463 SourceLocation LParenLoc,
8464 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00008465 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008466 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00008467 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008468 // The parameter of the collapse clause must be a constant
8469 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00008470 ExprResult NumForLoopsResult =
8471 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8472 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00008473 return nullptr;
8474 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00008475 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00008476}
8477
Alexey Bataev10e775f2015-07-30 11:36:16 +00008478OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8479 SourceLocation EndLoc,
8480 SourceLocation LParenLoc,
8481 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00008482 // OpenMP [2.7.1, loop construct, Description]
8483 // OpenMP [2.8.1, simd construct, Description]
8484 // OpenMP [2.9.6, distribute construct, Description]
8485 // The parameter of the ordered clause must be a constant
8486 // positive integer expression if any.
8487 if (NumForLoops && LParenLoc.isValid()) {
8488 ExprResult NumForLoopsResult =
8489 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8490 if (NumForLoopsResult.isInvalid())
8491 return nullptr;
8492 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00008493 } else
8494 NumForLoops = nullptr;
8495 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00008496 return new (Context)
8497 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
8498}
8499
Alexey Bataeved09d242014-05-28 05:53:51 +00008500OMPClause *Sema::ActOnOpenMPSimpleClause(
8501 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8502 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008503 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008504 switch (Kind) {
8505 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008506 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00008507 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8508 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008509 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008510 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00008511 Res = ActOnOpenMPProcBindClause(
8512 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8513 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008514 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008515 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008516 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008517 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008518 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008519 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008520 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008521 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008522 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008523 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008524 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008525 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008526 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008527 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008528 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008529 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008530 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008531 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008532 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008533 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008534 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008535 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008536 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008537 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008538 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008539 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008540 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008541 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008542 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008543 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008544 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008545 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008546 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008547 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008548 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008549 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008550 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008551 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008552 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008553 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008554 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008555 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008556 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008557 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008558 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008559 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008560 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008561 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008562 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008563 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008564 llvm_unreachable("Clause is not allowed.");
8565 }
8566 return Res;
8567}
8568
Alexey Bataev6402bca2015-12-28 07:25:51 +00008569static std::string
8570getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8571 ArrayRef<unsigned> Exclude = llvm::None) {
8572 std::string Values;
8573 unsigned Bound = Last >= 2 ? Last - 2 : 0;
8574 unsigned Skipped = Exclude.size();
8575 auto S = Exclude.begin(), E = Exclude.end();
8576 for (unsigned i = First; i < Last; ++i) {
8577 if (std::find(S, E, i) != E) {
8578 --Skipped;
8579 continue;
8580 }
8581 Values += "'";
8582 Values += getOpenMPSimpleClauseTypeName(K, i);
8583 Values += "'";
8584 if (i == Bound - Skipped)
8585 Values += " or ";
8586 else if (i != Bound + 1 - Skipped)
8587 Values += ", ";
8588 }
8589 return Values;
8590}
8591
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008592OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8593 SourceLocation KindKwLoc,
8594 SourceLocation StartLoc,
8595 SourceLocation LParenLoc,
8596 SourceLocation EndLoc) {
8597 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00008598 static_assert(OMPC_DEFAULT_unknown > 0,
8599 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008600 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008601 << getListOfPossibleValues(OMPC_default, /*First=*/0,
8602 /*Last=*/OMPC_DEFAULT_unknown)
8603 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008604 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008605 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00008606 switch (Kind) {
8607 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008608 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008609 break;
8610 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008611 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008612 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008613 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008614 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00008615 break;
8616 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008617 return new (Context)
8618 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008619}
8620
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008621OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8622 SourceLocation KindKwLoc,
8623 SourceLocation StartLoc,
8624 SourceLocation LParenLoc,
8625 SourceLocation EndLoc) {
8626 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008627 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008628 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8629 /*Last=*/OMPC_PROC_BIND_unknown)
8630 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008631 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008632 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008633 return new (Context)
8634 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008635}
8636
Alexey Bataev56dafe82014-06-20 07:16:17 +00008637OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008638 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008639 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008640 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008641 SourceLocation EndLoc) {
8642 OMPClause *Res = nullptr;
8643 switch (Kind) {
8644 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008645 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8646 assert(Argument.size() == NumberOfElements &&
8647 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008648 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008649 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8650 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8651 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8652 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8653 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008654 break;
8655 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008656 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8657 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8658 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8659 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008660 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00008661 case OMPC_dist_schedule:
8662 Res = ActOnOpenMPDistScheduleClause(
8663 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8664 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8665 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008666 case OMPC_defaultmap:
8667 enum { Modifier, DefaultmapKind };
8668 Res = ActOnOpenMPDefaultmapClause(
8669 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8670 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00008671 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8672 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008673 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00008674 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008675 case OMPC_num_threads:
8676 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008677 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008678 case OMPC_collapse:
8679 case OMPC_default:
8680 case OMPC_proc_bind:
8681 case OMPC_private:
8682 case OMPC_firstprivate:
8683 case OMPC_lastprivate:
8684 case OMPC_shared:
8685 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008686 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008687 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008688 case OMPC_linear:
8689 case OMPC_aligned:
8690 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008691 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008692 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008693 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008694 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008695 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008696 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008697 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008698 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008699 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008700 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008701 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008702 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008703 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008704 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008705 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008706 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008707 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008708 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008709 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008710 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008711 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008712 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008713 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008714 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008715 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008716 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008717 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008718 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008719 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008720 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008721 llvm_unreachable("Clause is not allowed.");
8722 }
8723 return Res;
8724}
8725
Alexey Bataev6402bca2015-12-28 07:25:51 +00008726static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8727 OpenMPScheduleClauseModifier M2,
8728 SourceLocation M1Loc, SourceLocation M2Loc) {
8729 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8730 SmallVector<unsigned, 2> Excluded;
8731 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8732 Excluded.push_back(M2);
8733 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8734 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8735 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8736 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8737 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8738 << getListOfPossibleValues(OMPC_schedule,
8739 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8740 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8741 Excluded)
8742 << getOpenMPClauseName(OMPC_schedule);
8743 return true;
8744 }
8745 return false;
8746}
8747
Alexey Bataev56dafe82014-06-20 07:16:17 +00008748OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008749 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008750 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008751 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8752 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8753 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8754 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8755 return nullptr;
8756 // OpenMP, 2.7.1, Loop Construct, Restrictions
8757 // Either the monotonic modifier or the nonmonotonic modifier can be specified
8758 // but not both.
8759 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8760 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8761 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8762 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8763 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8764 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8765 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8766 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8767 return nullptr;
8768 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008769 if (Kind == OMPC_SCHEDULE_unknown) {
8770 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00008771 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8772 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8773 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8774 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8775 Exclude);
8776 } else {
8777 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8778 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008779 }
8780 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8781 << Values << getOpenMPClauseName(OMPC_schedule);
8782 return nullptr;
8783 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00008784 // OpenMP, 2.7.1, Loop Construct, Restrictions
8785 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8786 // schedule(guided).
8787 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8788 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8789 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8790 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8791 diag::err_omp_schedule_nonmonotonic_static);
8792 return nullptr;
8793 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008794 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00008795 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00008796 if (ChunkSize) {
8797 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8798 !ChunkSize->isInstantiationDependent() &&
8799 !ChunkSize->containsUnexpandedParameterPack()) {
8800 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8801 ExprResult Val =
8802 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8803 if (Val.isInvalid())
8804 return nullptr;
8805
8806 ValExpr = Val.get();
8807
8808 // OpenMP [2.7.1, Restrictions]
8809 // chunk_size must be a loop invariant integer expression with a positive
8810 // value.
8811 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00008812 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8813 if (Result.isSigned() && !Result.isStrictlyPositive()) {
8814 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008815 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00008816 return nullptr;
8817 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00008818 } else if (getOpenMPCaptureRegionForClause(
8819 DSAStack->getCurrentDirective(), OMPC_schedule) !=
8820 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00008821 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008822 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008823 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8824 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8825 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008826 }
8827 }
8828 }
8829
Alexey Bataev6402bca2015-12-28 07:25:51 +00008830 return new (Context)
8831 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00008832 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008833}
8834
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008835OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8836 SourceLocation StartLoc,
8837 SourceLocation EndLoc) {
8838 OMPClause *Res = nullptr;
8839 switch (Kind) {
8840 case OMPC_ordered:
8841 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8842 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00008843 case OMPC_nowait:
8844 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8845 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008846 case OMPC_untied:
8847 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8848 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008849 case OMPC_mergeable:
8850 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8851 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008852 case OMPC_read:
8853 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8854 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00008855 case OMPC_write:
8856 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8857 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008858 case OMPC_update:
8859 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8860 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00008861 case OMPC_capture:
8862 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8863 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008864 case OMPC_seq_cst:
8865 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8866 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008867 case OMPC_threads:
8868 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8869 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008870 case OMPC_simd:
8871 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8872 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008873 case OMPC_nogroup:
8874 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8875 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008876 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008877 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008878 case OMPC_num_threads:
8879 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008880 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008881 case OMPC_collapse:
8882 case OMPC_schedule:
8883 case OMPC_private:
8884 case OMPC_firstprivate:
8885 case OMPC_lastprivate:
8886 case OMPC_shared:
8887 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008888 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008889 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008890 case OMPC_linear:
8891 case OMPC_aligned:
8892 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008893 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008894 case OMPC_default:
8895 case OMPC_proc_bind:
8896 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008897 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008898 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008899 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008900 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008901 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008902 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008903 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008904 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00008905 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008906 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008907 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008908 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008909 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008910 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008911 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008912 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008913 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008914 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008915 llvm_unreachable("Clause is not allowed.");
8916 }
8917 return Res;
8918}
8919
Alexey Bataev236070f2014-06-20 11:19:47 +00008920OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8921 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008922 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00008923 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8924}
8925
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008926OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8927 SourceLocation EndLoc) {
8928 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8929}
8930
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008931OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8932 SourceLocation EndLoc) {
8933 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8934}
8935
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008936OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8937 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008938 return new (Context) OMPReadClause(StartLoc, EndLoc);
8939}
8940
Alexey Bataevdea47612014-07-23 07:46:59 +00008941OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
8942 SourceLocation EndLoc) {
8943 return new (Context) OMPWriteClause(StartLoc, EndLoc);
8944}
8945
Alexey Bataev67a4f222014-07-23 10:25:33 +00008946OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8947 SourceLocation EndLoc) {
8948 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8949}
8950
Alexey Bataev459dec02014-07-24 06:46:57 +00008951OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8952 SourceLocation EndLoc) {
8953 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8954}
8955
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008956OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8957 SourceLocation EndLoc) {
8958 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8959}
8960
Alexey Bataev346265e2015-09-25 10:37:12 +00008961OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8962 SourceLocation EndLoc) {
8963 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8964}
8965
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008966OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8967 SourceLocation EndLoc) {
8968 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8969}
8970
Alexey Bataevb825de12015-12-07 10:51:44 +00008971OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8972 SourceLocation EndLoc) {
8973 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8974}
8975
Alexey Bataevc5e02582014-06-16 07:08:35 +00008976OMPClause *Sema::ActOnOpenMPVarListClause(
8977 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8978 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8979 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008980 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00008981 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8982 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8983 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008984 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008985 switch (Kind) {
8986 case OMPC_private:
8987 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8988 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008989 case OMPC_firstprivate:
8990 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8991 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008992 case OMPC_lastprivate:
8993 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8994 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00008995 case OMPC_shared:
8996 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
8997 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00008998 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00008999 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9000 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009001 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00009002 case OMPC_task_reduction:
9003 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9004 EndLoc, ReductionIdScopeSpec,
9005 ReductionId);
9006 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00009007 case OMPC_in_reduction:
9008 Res =
9009 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9010 EndLoc, ReductionIdScopeSpec, ReductionId);
9011 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00009012 case OMPC_linear:
9013 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009014 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00009015 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009016 case OMPC_aligned:
9017 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9018 ColonLoc, EndLoc);
9019 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009020 case OMPC_copyin:
9021 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9022 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009023 case OMPC_copyprivate:
9024 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9025 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00009026 case OMPC_flush:
9027 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9028 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009029 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00009030 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009031 StartLoc, LParenLoc, EndLoc);
9032 break;
9033 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00009034 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
9035 DepLinMapLoc, ColonLoc, VarList, StartLoc,
9036 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009037 break;
Samuel Antao661c0902016-05-26 17:39:58 +00009038 case OMPC_to:
9039 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
9040 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00009041 case OMPC_from:
9042 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
9043 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00009044 case OMPC_use_device_ptr:
9045 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9046 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00009047 case OMPC_is_device_ptr:
9048 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9049 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009050 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009051 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009052 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009053 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009054 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009055 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009056 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009057 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009058 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009059 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009060 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009061 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009062 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009063 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009064 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009065 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009066 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009067 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009068 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00009069 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009070 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009071 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009072 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009073 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009074 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009075 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009076 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009077 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009078 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009079 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009080 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009081 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009082 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009083 llvm_unreachable("Clause is not allowed.");
9084 }
9085 return Res;
9086}
9087
Alexey Bataev90c228f2016-02-08 09:29:13 +00009088ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00009089 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00009090 ExprResult Res = BuildDeclRefExpr(
9091 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9092 if (!Res.isUsable())
9093 return ExprError();
9094 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9095 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9096 if (!Res.isUsable())
9097 return ExprError();
9098 }
9099 if (VK != VK_LValue && Res.get()->isGLValue()) {
9100 Res = DefaultLvalueConversion(Res.get());
9101 if (!Res.isUsable())
9102 return ExprError();
9103 }
9104 return Res;
9105}
9106
Alexey Bataev60da77e2016-02-29 05:54:20 +00009107static std::pair<ValueDecl *, bool>
9108getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9109 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009110 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9111 RefExpr->containsUnexpandedParameterPack())
9112 return std::make_pair(nullptr, true);
9113
Alexey Bataevd985eda2016-02-10 11:29:16 +00009114 // OpenMP [3.1, C/C++]
9115 // A list item is a variable name.
9116 // OpenMP [2.9.3.3, Restrictions, p.1]
9117 // A variable that is part of another variable (as an array or
9118 // structure element) cannot appear in a private clause.
9119 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009120 enum {
9121 NoArrayExpr = -1,
9122 ArraySubscript = 0,
9123 OMPArraySection = 1
9124 } IsArrayExpr = NoArrayExpr;
9125 if (AllowArraySection) {
9126 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
9127 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
9128 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9129 Base = TempASE->getBase()->IgnoreParenImpCasts();
9130 RefExpr = Base;
9131 IsArrayExpr = ArraySubscript;
9132 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
9133 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
9134 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9135 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9136 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9137 Base = TempASE->getBase()->IgnoreParenImpCasts();
9138 RefExpr = Base;
9139 IsArrayExpr = OMPArraySection;
9140 }
9141 }
9142 ELoc = RefExpr->getExprLoc();
9143 ERange = RefExpr->getSourceRange();
9144 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009145 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9146 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9147 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9148 (S.getCurrentThisType().isNull() || !ME ||
9149 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9150 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009151 if (IsArrayExpr != NoArrayExpr)
9152 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9153 << ERange;
9154 else {
9155 S.Diag(ELoc,
9156 AllowArraySection
9157 ? diag::err_omp_expected_var_name_member_expr_or_array_item
9158 : diag::err_omp_expected_var_name_member_expr)
9159 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9160 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009161 return std::make_pair(nullptr, false);
9162 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009163 return std::make_pair(
9164 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009165}
9166
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009167OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9168 SourceLocation StartLoc,
9169 SourceLocation LParenLoc,
9170 SourceLocation EndLoc) {
9171 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00009172 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00009173 for (auto &RefExpr : VarList) {
9174 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009175 SourceLocation ELoc;
9176 SourceRange ERange;
9177 Expr *SimpleRefExpr = RefExpr;
9178 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009179 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009180 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009181 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009182 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009183 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009184 ValueDecl *D = Res.first;
9185 if (!D)
9186 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009187
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009188 QualType Type = D->getType();
9189 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009190
9191 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9192 // A variable that appears in a private clause must not have an incomplete
9193 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009194 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009195 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009196 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009197
Alexey Bataev758e55e2013-09-06 18:03:48 +00009198 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9199 // in a Construct]
9200 // Variables with the predetermined data-sharing attributes may not be
9201 // listed in data-sharing attributes clauses, except for the cases
9202 // listed below. For these exceptions only, listing a predetermined
9203 // variable in a data-sharing attribute clause is allowed and overrides
9204 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009205 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009206 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009207 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9208 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009209 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009210 continue;
9211 }
9212
Kelvin Libf594a52016-12-17 05:48:59 +00009213 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009214 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009215 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00009216 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009217 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9218 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00009219 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009220 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009221 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009222 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009223 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009224 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009225 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009226 continue;
9227 }
9228
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009229 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9230 // A list item cannot appear in both a map clause and a data-sharing
9231 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00009232 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Alexey Bataev647dd842018-01-15 20:59:40 +00009233 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00009234 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00009235 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00009236 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00009237 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00009238 CurrDir == OMPD_target_parallel_for_simd ||
9239 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00009240 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009241 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009242 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009243 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9244 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9245 ConflictKind = WhereFoundClauseKind;
9246 return true;
9247 })) {
9248 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009249 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00009250 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00009251 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009252 ReportOriginalDSA(*this, DSAStack, D, DVar);
9253 continue;
9254 }
9255 }
9256
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009257 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9258 // A variable of class type (or array thereof) that appears in a private
9259 // clause requires an accessible, unambiguous default constructor for the
9260 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00009261 // Generate helper private variable and initialize it with the default
9262 // value. The address of the original variable is replaced by the address of
9263 // the new private variable in CodeGen. This new variable is not added to
9264 // IdResolver, so the code in the OpenMP region uses original variable for
9265 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009266 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009267 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9268 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00009269 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009270 if (VDPrivate->isInvalidDecl())
9271 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009272 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009273 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009274
Alexey Bataev90c228f2016-02-08 09:29:13 +00009275 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009276 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009277 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00009278 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009279 Vars.push_back((VD || CurContext->isDependentContext())
9280 ? RefExpr->IgnoreParens()
9281 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009282 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009283 }
9284
Alexey Bataeved09d242014-05-28 05:53:51 +00009285 if (Vars.empty())
9286 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009287
Alexey Bataev03b340a2014-10-21 03:16:40 +00009288 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9289 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009290}
9291
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009292namespace {
9293class DiagsUninitializedSeveretyRAII {
9294private:
9295 DiagnosticsEngine &Diags;
9296 SourceLocation SavedLoc;
9297 bool IsIgnored;
9298
9299public:
9300 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9301 bool IsIgnored)
9302 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9303 if (!IsIgnored) {
9304 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9305 /*Map*/ diag::Severity::Ignored, Loc);
9306 }
9307 }
9308 ~DiagsUninitializedSeveretyRAII() {
9309 if (!IsIgnored)
9310 Diags.popMappings(SavedLoc);
9311 }
9312};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009313}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009314
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009315OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9316 SourceLocation StartLoc,
9317 SourceLocation LParenLoc,
9318 SourceLocation EndLoc) {
9319 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009320 SmallVector<Expr *, 8> PrivateCopies;
9321 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00009322 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009323 bool IsImplicitClause =
9324 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
9325 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
9326
Alexey Bataeved09d242014-05-28 05:53:51 +00009327 for (auto &RefExpr : VarList) {
9328 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009329 SourceLocation ELoc;
9330 SourceRange ERange;
9331 Expr *SimpleRefExpr = RefExpr;
9332 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009333 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009334 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009335 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009336 PrivateCopies.push_back(nullptr);
9337 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009338 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009339 ValueDecl *D = Res.first;
9340 if (!D)
9341 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009342
Alexey Bataev60da77e2016-02-29 05:54:20 +00009343 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009344 QualType Type = D->getType();
9345 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009346
9347 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9348 // A variable that appears in a private clause must not have an incomplete
9349 // type or a reference type.
9350 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00009351 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009352 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009353 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009354
9355 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9356 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00009357 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009358 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009359 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009360
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009361 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00009362 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009363 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009364 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009365 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009366 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009367 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009368 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9369 // A list item that specifies a given variable may not appear in more
9370 // than one clause on the same directive, except that a variable may be
9371 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009372 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9373 // A list item may appear in a firstprivate or lastprivate clause but not
9374 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009375 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +00009376 (isOpenMPDistributeDirective(CurrDir) ||
9377 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009378 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009379 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009380 << getOpenMPClauseName(DVar.CKind)
9381 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009382 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009383 continue;
9384 }
9385
9386 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9387 // in a Construct]
9388 // Variables with the predetermined data-sharing attributes may not be
9389 // listed in data-sharing attributes clauses, except for the cases
9390 // listed below. For these exceptions only, listing a predetermined
9391 // variable in a data-sharing attribute clause is allowed and overrides
9392 // the variable's predetermined data-sharing attributes.
9393 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9394 // in a Construct, C/C++, p.2]
9395 // Variables with const-qualified type having no mutable member may be
9396 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00009397 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009398 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9399 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009400 << getOpenMPClauseName(DVar.CKind)
9401 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009402 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009403 continue;
9404 }
9405
9406 // OpenMP [2.9.3.4, Restrictions, p.2]
9407 // A list item that is private within a parallel region must not appear
9408 // in a firstprivate clause on a worksharing construct if any of the
9409 // worksharing regions arising from the worksharing construct ever bind
9410 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009411 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9412 // A list item that is private within a teams region must not appear in a
9413 // firstprivate clause on a distribute construct if any of the distribute
9414 // regions arising from the distribute construct ever bind to any of the
9415 // teams regions arising from the teams construct.
9416 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9417 // A list item that appears in a reduction clause of a teams construct
9418 // must not appear in a firstprivate clause on a distribute construct if
9419 // any of the distribute regions arising from the distribute construct
9420 // ever bind to any of the teams regions arising from the teams construct.
9421 if ((isOpenMPWorksharingDirective(CurrDir) ||
9422 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009423 !isOpenMPParallelDirective(CurrDir) &&
9424 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009425 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009426 if (DVar.CKind != OMPC_shared &&
9427 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009428 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009429 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00009430 Diag(ELoc, diag::err_omp_required_access)
9431 << getOpenMPClauseName(OMPC_firstprivate)
9432 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009433 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009434 continue;
9435 }
9436 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009437 // OpenMP [2.9.3.4, Restrictions, p.3]
9438 // A list item that appears in a reduction clause of a parallel construct
9439 // must not appear in a firstprivate clause on a worksharing or task
9440 // construct if any of the worksharing or task regions arising from the
9441 // worksharing or task construct ever bind to any of the parallel regions
9442 // arising from the parallel construct.
9443 // OpenMP [2.9.3.4, Restrictions, p.4]
9444 // A list item that appears in a reduction clause in worksharing
9445 // construct must not appear in a firstprivate clause in a task construct
9446 // encountered during execution of any of the worksharing regions arising
9447 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00009448 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009449 DVar = DSAStack->hasInnermostDSA(
9450 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
9451 [](OpenMPDirectiveKind K) -> bool {
9452 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009453 isOpenMPWorksharingDirective(K) ||
9454 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009455 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009456 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009457 if (DVar.CKind == OMPC_reduction &&
9458 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009459 isOpenMPWorksharingDirective(DVar.DKind) ||
9460 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009461 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
9462 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009463 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009464 continue;
9465 }
9466 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009467
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009468 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9469 // A list item cannot appear in both a map clause and a data-sharing
9470 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +00009471 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +00009472 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009473 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009474 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009475 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9476 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9477 ConflictKind = WhereFoundClauseKind;
9478 return true;
9479 })) {
9480 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009481 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00009482 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009483 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9484 ReportOriginalDSA(*this, DSAStack, D, DVar);
9485 continue;
9486 }
9487 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009488 }
9489
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009490 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009491 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00009492 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009493 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9494 << getOpenMPClauseName(OMPC_firstprivate) << Type
9495 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9496 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009497 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009498 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009499 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009500 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00009501 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009502 continue;
9503 }
9504
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009505 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009506 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9507 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009508 // Generate helper private variable and initialize it with the value of the
9509 // original variable. The address of the original variable is replaced by
9510 // the address of the new private variable in the CodeGen. This new variable
9511 // is not added to IdResolver, so the code in the OpenMP region uses
9512 // original variable for proper diagnostics and variable capturing.
9513 Expr *VDInitRefExpr = nullptr;
9514 // For arrays generate initializer for single element and replace it by the
9515 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009516 if (Type->isArrayType()) {
9517 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009518 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009519 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009520 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009521 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009522 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009523 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00009524 InitializedEntity Entity =
9525 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009526 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9527
9528 InitializationSequence InitSeq(*this, Entity, Kind, Init);
9529 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9530 if (Result.isInvalid())
9531 VDPrivate->setInvalidDecl();
9532 else
9533 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009534 // Remove temp variable declaration.
9535 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009536 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009537 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9538 ".firstprivate.temp");
9539 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9540 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00009541 AddInitializerToDecl(VDPrivate,
9542 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009543 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009544 }
9545 if (VDPrivate->isInvalidDecl()) {
9546 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009547 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009548 diag::note_omp_task_predetermined_firstprivate_here);
9549 }
9550 continue;
9551 }
9552 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009553 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00009554 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
9555 RefExpr->getExprLoc());
9556 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009557 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009558 if (TopDVar.CKind == OMPC_lastprivate)
9559 Ref = TopDVar.PrivateCopy;
9560 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009561 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00009562 if (!IsOpenMPCapturedDecl(D))
9563 ExprCaptures.push_back(Ref->getDecl());
9564 }
Alexey Bataev417089f2016-02-17 13:19:37 +00009565 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009566 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009567 Vars.push_back((VD || CurContext->isDependentContext())
9568 ? RefExpr->IgnoreParens()
9569 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009570 PrivateCopies.push_back(VDPrivateRefExpr);
9571 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009572 }
9573
Alexey Bataeved09d242014-05-28 05:53:51 +00009574 if (Vars.empty())
9575 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009576
9577 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009578 Vars, PrivateCopies, Inits,
9579 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009580}
9581
Alexander Musman1bb328c2014-06-04 13:06:39 +00009582OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9583 SourceLocation StartLoc,
9584 SourceLocation LParenLoc,
9585 SourceLocation EndLoc) {
9586 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00009587 SmallVector<Expr *, 8> SrcExprs;
9588 SmallVector<Expr *, 8> DstExprs;
9589 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00009590 SmallVector<Decl *, 4> ExprCaptures;
9591 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009592 for (auto &RefExpr : VarList) {
9593 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009594 SourceLocation ELoc;
9595 SourceRange ERange;
9596 Expr *SimpleRefExpr = RefExpr;
9597 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009598 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00009599 // It will be analyzed later.
9600 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00009601 SrcExprs.push_back(nullptr);
9602 DstExprs.push_back(nullptr);
9603 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009604 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009605 ValueDecl *D = Res.first;
9606 if (!D)
9607 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009608
Alexey Bataev74caaf22016-02-20 04:09:36 +00009609 QualType Type = D->getType();
9610 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009611
9612 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9613 // A variable that appears in a lastprivate clause must not have an
9614 // incomplete type or a reference type.
9615 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00009616 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00009617 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009618 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009619
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009620 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009621 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9622 // in a Construct]
9623 // Variables with the predetermined data-sharing attributes may not be
9624 // listed in data-sharing attributes clauses, except for the cases
9625 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009626 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9627 // A list item may appear in a firstprivate or lastprivate clause but not
9628 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009629 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009630 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +00009631 (isOpenMPDistributeDirective(CurrDir) ||
9632 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00009633 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9634 Diag(ELoc, diag::err_omp_wrong_dsa)
9635 << getOpenMPClauseName(DVar.CKind)
9636 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009637 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009638 continue;
9639 }
9640
Alexey Bataevf29276e2014-06-18 04:14:57 +00009641 // OpenMP [2.14.3.5, Restrictions, p.2]
9642 // A list item that is private within a parallel region, or that appears in
9643 // the reduction clause of a parallel construct, must not appear in a
9644 // lastprivate clause on a worksharing construct if any of the corresponding
9645 // worksharing regions ever binds to any of the corresponding parallel
9646 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00009647 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00009648 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009649 !isOpenMPParallelDirective(CurrDir) &&
9650 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00009651 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009652 if (DVar.CKind != OMPC_shared) {
9653 Diag(ELoc, diag::err_omp_required_access)
9654 << getOpenMPClauseName(OMPC_lastprivate)
9655 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009656 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009657 continue;
9658 }
9659 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009660
Alexander Musman1bb328c2014-06-04 13:06:39 +00009661 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00009662 // A variable of class type (or array thereof) that appears in a
9663 // lastprivate clause requires an accessible, unambiguous default
9664 // constructor for the class type, unless the list item is also specified
9665 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00009666 // A variable of class type (or array thereof) that appears in a
9667 // lastprivate clause requires an accessible, unambiguous copy assignment
9668 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00009669 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009670 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009671 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009672 D->hasAttrs() ? &D->getAttrs() : nullptr);
9673 auto *PseudoSrcExpr =
9674 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009675 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009676 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009677 D->hasAttrs() ? &D->getAttrs() : nullptr);
9678 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009679 // For arrays generate assignment operation for single element and replace
9680 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009681 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00009682 PseudoDstExpr, PseudoSrcExpr);
9683 if (AssignmentOp.isInvalid())
9684 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00009685 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00009686 /*DiscardedValue=*/true);
9687 if (AssignmentOp.isInvalid())
9688 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009689
Alexey Bataev74caaf22016-02-20 04:09:36 +00009690 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009691 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009692 if (TopDVar.CKind == OMPC_firstprivate)
9693 Ref = TopDVar.PrivateCopy;
9694 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009695 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009696 if (!IsOpenMPCapturedDecl(D))
9697 ExprCaptures.push_back(Ref->getDecl());
9698 }
9699 if (TopDVar.CKind == OMPC_firstprivate ||
9700 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009701 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009702 ExprResult RefRes = DefaultLvalueConversion(Ref);
9703 if (!RefRes.isUsable())
9704 continue;
9705 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009706 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9707 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009708 if (!PostUpdateRes.isUsable())
9709 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009710 ExprPostUpdates.push_back(
9711 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009712 }
9713 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009714 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009715 Vars.push_back((VD || CurContext->isDependentContext())
9716 ? RefExpr->IgnoreParens()
9717 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00009718 SrcExprs.push_back(PseudoSrcExpr);
9719 DstExprs.push_back(PseudoDstExpr);
9720 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00009721 }
9722
9723 if (Vars.empty())
9724 return nullptr;
9725
9726 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00009727 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009728 buildPreInits(Context, ExprCaptures),
9729 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00009730}
9731
Alexey Bataev758e55e2013-09-06 18:03:48 +00009732OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9733 SourceLocation StartLoc,
9734 SourceLocation LParenLoc,
9735 SourceLocation EndLoc) {
9736 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00009737 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009738 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009739 SourceLocation ELoc;
9740 SourceRange ERange;
9741 Expr *SimpleRefExpr = RefExpr;
9742 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009743 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00009744 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009745 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009746 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009747 ValueDecl *D = Res.first;
9748 if (!D)
9749 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009750
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009751 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009752 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9753 // in a Construct]
9754 // Variables with the predetermined data-sharing attributes may not be
9755 // listed in data-sharing attributes clauses, except for the cases
9756 // listed below. For these exceptions only, listing a predetermined
9757 // variable in a data-sharing attribute clause is allowed and overrides
9758 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009759 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00009760 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9761 DVar.RefExpr) {
9762 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9763 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009764 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009765 continue;
9766 }
9767
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009768 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009769 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009770 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009771 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009772 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9773 ? RefExpr->IgnoreParens()
9774 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009775 }
9776
Alexey Bataeved09d242014-05-28 05:53:51 +00009777 if (Vars.empty())
9778 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009779
9780 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9781}
9782
Alexey Bataevc5e02582014-06-16 07:08:35 +00009783namespace {
9784class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9785 DSAStackTy *Stack;
9786
9787public:
9788 bool VisitDeclRefExpr(DeclRefExpr *E) {
9789 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009790 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009791 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9792 return false;
9793 if (DVar.CKind != OMPC_unknown)
9794 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009795 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9796 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009797 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009798 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009799 return true;
9800 return false;
9801 }
9802 return false;
9803 }
9804 bool VisitStmt(Stmt *S) {
9805 for (auto Child : S->children()) {
9806 if (Child && Visit(Child))
9807 return true;
9808 }
9809 return false;
9810 }
Alexey Bataev23b69422014-06-18 07:08:49 +00009811 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009812};
Alexey Bataev23b69422014-06-18 07:08:49 +00009813} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00009814
Alexey Bataev60da77e2016-02-29 05:54:20 +00009815namespace {
9816// Transform MemberExpression for specified FieldDecl of current class to
9817// DeclRefExpr to specified OMPCapturedExprDecl.
9818class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9819 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9820 ValueDecl *Field;
9821 DeclRefExpr *CapturedExpr;
9822
9823public:
9824 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9825 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9826
9827 ExprResult TransformMemberExpr(MemberExpr *E) {
9828 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9829 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00009830 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009831 return CapturedExpr;
9832 }
9833 return BaseTransform::TransformMemberExpr(E);
9834 }
9835 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9836};
9837} // namespace
9838
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009839template <typename T>
9840static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9841 const llvm::function_ref<T(ValueDecl *)> &Gen) {
9842 for (auto &Set : Lookups) {
9843 for (auto *D : Set) {
9844 if (auto Res = Gen(cast<ValueDecl>(D)))
9845 return Res;
9846 }
9847 }
9848 return T();
9849}
9850
9851static ExprResult
9852buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9853 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9854 const DeclarationNameInfo &ReductionId, QualType Ty,
9855 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9856 if (ReductionIdScopeSpec.isInvalid())
9857 return ExprError();
9858 SmallVector<UnresolvedSet<8>, 4> Lookups;
9859 if (S) {
9860 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9861 Lookup.suppressDiagnostics();
9862 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9863 auto *D = Lookup.getRepresentativeDecl();
9864 do {
9865 S = S->getParent();
9866 } while (S && !S->isDeclScope(D));
9867 if (S)
9868 S = S->getParent();
9869 Lookups.push_back(UnresolvedSet<8>());
9870 Lookups.back().append(Lookup.begin(), Lookup.end());
9871 Lookup.clear();
9872 }
9873 } else if (auto *ULE =
9874 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9875 Lookups.push_back(UnresolvedSet<8>());
9876 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00009877 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009878 if (D == PrevD)
9879 Lookups.push_back(UnresolvedSet<8>());
9880 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9881 Lookups.back().addDecl(DRD);
9882 PrevD = D;
9883 }
9884 }
Alexey Bataevfdc20352017-08-25 15:43:55 +00009885 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9886 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009887 Ty->containsUnexpandedParameterPack() ||
9888 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9889 return !D->isInvalidDecl() &&
9890 (D->getType()->isDependentType() ||
9891 D->getType()->isInstantiationDependentType() ||
9892 D->getType()->containsUnexpandedParameterPack());
9893 })) {
9894 UnresolvedSet<8> ResSet;
9895 for (auto &Set : Lookups) {
9896 ResSet.append(Set.begin(), Set.end());
9897 // The last item marks the end of all declarations at the specified scope.
9898 ResSet.addDecl(Set[Set.size() - 1]);
9899 }
9900 return UnresolvedLookupExpr::Create(
9901 SemaRef.Context, /*NamingClass=*/nullptr,
9902 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9903 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9904 }
9905 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9906 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9907 if (!D->isInvalidDecl() &&
9908 SemaRef.Context.hasSameType(D->getType(), Ty))
9909 return D;
9910 return nullptr;
9911 }))
9912 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9913 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9914 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9915 if (!D->isInvalidDecl() &&
9916 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9917 !Ty.isMoreQualifiedThan(D->getType()))
9918 return D;
9919 return nullptr;
9920 })) {
9921 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9922 /*DetectVirtual=*/false);
9923 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9924 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9925 VD->getType().getUnqualifiedType()))) {
9926 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9927 /*DiagID=*/0) !=
9928 Sema::AR_inaccessible) {
9929 SemaRef.BuildBasePathArray(Paths, BasePath);
9930 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9931 }
9932 }
9933 }
9934 }
9935 if (ReductionIdScopeSpec.isSet()) {
9936 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9937 return ExprError();
9938 }
9939 return ExprEmpty();
9940}
9941
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009942namespace {
9943/// Data for the reduction-based clauses.
9944struct ReductionData {
9945 /// List of original reduction items.
9946 SmallVector<Expr *, 8> Vars;
9947 /// List of private copies of the reduction items.
9948 SmallVector<Expr *, 8> Privates;
9949 /// LHS expressions for the reduction_op expressions.
9950 SmallVector<Expr *, 8> LHSs;
9951 /// RHS expressions for the reduction_op expressions.
9952 SmallVector<Expr *, 8> RHSs;
9953 /// Reduction operation expression.
9954 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +00009955 /// Taskgroup descriptors for the corresponding reduction items in
9956 /// in_reduction clauses.
9957 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009958 /// List of captures for clause.
9959 SmallVector<Decl *, 4> ExprCaptures;
9960 /// List of postupdate expressions.
9961 SmallVector<Expr *, 4> ExprPostUpdates;
9962 ReductionData() = delete;
9963 /// Reserves required memory for the reduction data.
9964 ReductionData(unsigned Size) {
9965 Vars.reserve(Size);
9966 Privates.reserve(Size);
9967 LHSs.reserve(Size);
9968 RHSs.reserve(Size);
9969 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +00009970 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009971 ExprCaptures.reserve(Size);
9972 ExprPostUpdates.reserve(Size);
9973 }
9974 /// Stores reduction item and reduction operation only (required for dependent
9975 /// reduction item).
9976 void push(Expr *Item, Expr *ReductionOp) {
9977 Vars.emplace_back(Item);
9978 Privates.emplace_back(nullptr);
9979 LHSs.emplace_back(nullptr);
9980 RHSs.emplace_back(nullptr);
9981 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009982 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009983 }
9984 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +00009985 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
9986 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009987 Vars.emplace_back(Item);
9988 Privates.emplace_back(Private);
9989 LHSs.emplace_back(LHS);
9990 RHSs.emplace_back(RHS);
9991 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009992 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009993 }
9994};
9995} // namespace
9996
Jonas Hahnfeld4525c822017-10-23 19:01:35 +00009997static bool CheckOMPArraySectionConstantForReduction(
9998 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
9999 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
10000 const Expr *Length = OASE->getLength();
10001 if (Length == nullptr) {
10002 // For array sections of the form [1:] or [:], we would need to analyze
10003 // the lower bound...
10004 if (OASE->getColonLoc().isValid())
10005 return false;
10006
10007 // This is an array subscript which has implicit length 1!
10008 SingleElement = true;
10009 ArraySizes.push_back(llvm::APSInt::get(1));
10010 } else {
10011 llvm::APSInt ConstantLengthValue;
10012 if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
10013 return false;
10014
10015 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
10016 ArraySizes.push_back(ConstantLengthValue);
10017 }
10018
10019 // Get the base of this array section and walk up from there.
10020 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10021
10022 // We require length = 1 for all array sections except the right-most to
10023 // guarantee that the memory region is contiguous and has no holes in it.
10024 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10025 Length = TempOASE->getLength();
10026 if (Length == nullptr) {
10027 // For array sections of the form [1:] or [:], we would need to analyze
10028 // the lower bound...
10029 if (OASE->getColonLoc().isValid())
10030 return false;
10031
10032 // This is an array subscript which has implicit length 1!
10033 ArraySizes.push_back(llvm::APSInt::get(1));
10034 } else {
10035 llvm::APSInt ConstantLengthValue;
10036 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
10037 ConstantLengthValue.getSExtValue() != 1)
10038 return false;
10039
10040 ArraySizes.push_back(ConstantLengthValue);
10041 }
10042 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10043 }
10044
10045 // If we have a single element, we don't need to add the implicit lengths.
10046 if (!SingleElement) {
10047 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10048 // Has implicit length 1!
10049 ArraySizes.push_back(llvm::APSInt::get(1));
10050 Base = TempASE->getBase()->IgnoreParenImpCasts();
10051 }
10052 }
10053
10054 // This array section can be privatized as a single value or as a constant
10055 // sized array.
10056 return true;
10057}
10058
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010059static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000010060 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10061 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10062 SourceLocation ColonLoc, SourceLocation EndLoc,
10063 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010064 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010065 auto DN = ReductionId.getName();
10066 auto OOK = DN.getCXXOverloadedOperator();
10067 BinaryOperatorKind BOK = BO_Comma;
10068
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010069 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010070 // OpenMP [2.14.3.6, reduction clause]
10071 // C
10072 // reduction-identifier is either an identifier or one of the following
10073 // operators: +, -, *, &, |, ^, && and ||
10074 // C++
10075 // reduction-identifier is either an id-expression or one of the following
10076 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000010077 switch (OOK) {
10078 case OO_Plus:
10079 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010080 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010081 break;
10082 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010083 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010084 break;
10085 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010086 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010087 break;
10088 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010089 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010090 break;
10091 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010092 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010093 break;
10094 case OO_AmpAmp:
10095 BOK = BO_LAnd;
10096 break;
10097 case OO_PipePipe:
10098 BOK = BO_LOr;
10099 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010100 case OO_New:
10101 case OO_Delete:
10102 case OO_Array_New:
10103 case OO_Array_Delete:
10104 case OO_Slash:
10105 case OO_Percent:
10106 case OO_Tilde:
10107 case OO_Exclaim:
10108 case OO_Equal:
10109 case OO_Less:
10110 case OO_Greater:
10111 case OO_LessEqual:
10112 case OO_GreaterEqual:
10113 case OO_PlusEqual:
10114 case OO_MinusEqual:
10115 case OO_StarEqual:
10116 case OO_SlashEqual:
10117 case OO_PercentEqual:
10118 case OO_CaretEqual:
10119 case OO_AmpEqual:
10120 case OO_PipeEqual:
10121 case OO_LessLess:
10122 case OO_GreaterGreater:
10123 case OO_LessLessEqual:
10124 case OO_GreaterGreaterEqual:
10125 case OO_EqualEqual:
10126 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000010127 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010128 case OO_PlusPlus:
10129 case OO_MinusMinus:
10130 case OO_Comma:
10131 case OO_ArrowStar:
10132 case OO_Arrow:
10133 case OO_Call:
10134 case OO_Subscript:
10135 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000010136 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010137 case NUM_OVERLOADED_OPERATORS:
10138 llvm_unreachable("Unexpected reduction identifier");
10139 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010140 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010141 if (II->isStr("max"))
10142 BOK = BO_GT;
10143 else if (II->isStr("min"))
10144 BOK = BO_LT;
10145 }
10146 break;
10147 }
10148 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010149 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000010150 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010151 else
10152 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000010153 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000010154
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010155 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
10156 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010157 for (auto RefExpr : VarList) {
10158 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000010159 // OpenMP [2.1, C/C++]
10160 // A list item is a variable or array section, subject to the restrictions
10161 // specified in Section 2.4 on page 42 and in each of the sections
10162 // describing clauses and directives for which a list appears.
10163 // OpenMP [2.14.3.3, Restrictions, p.1]
10164 // A variable that is part of another variable (as an array or
10165 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010166 if (!FirstIter && IR != ER)
10167 ++IR;
10168 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010169 SourceLocation ELoc;
10170 SourceRange ERange;
10171 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010172 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000010173 /*AllowArraySection=*/true);
10174 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010175 // Try to find 'declare reduction' corresponding construct before using
10176 // builtin/overloaded operators.
10177 QualType Type = Context.DependentTy;
10178 CXXCastPath BasePath;
10179 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010180 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010181 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010182 Expr *ReductionOp = nullptr;
10183 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010184 (DeclareReductionRef.isUnset() ||
10185 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010186 ReductionOp = DeclareReductionRef.get();
10187 // It will be analyzed later.
10188 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010189 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010190 ValueDecl *D = Res.first;
10191 if (!D)
10192 continue;
10193
Alexey Bataev88202be2017-07-27 13:20:36 +000010194 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000010195 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010196 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
10197 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
10198 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +000010199 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010200 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +000010201 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
10202 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
10203 Type = ATy->getElementType();
10204 else
10205 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000010206 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010207 } else
10208 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
10209 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000010210
Alexey Bataevc5e02582014-06-16 07:08:35 +000010211 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10212 // A variable that appears in a private clause must not have an incomplete
10213 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010214 if (S.RequireCompleteType(ELoc, Type,
10215 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010216 continue;
10217 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000010218 // A list item that appears in a reduction clause must not be
10219 // const-qualified.
10220 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010221 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010222 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010223 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10224 VarDecl::DeclarationOnly;
10225 S.Diag(D->getLocation(),
10226 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010227 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +000010228 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010229 continue;
10230 }
10231 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
10232 // If a list-item is a reference type then it must bind to the same object
10233 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +000010234 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +000010235 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +000010236 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010237 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +000010238 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010239 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
10240 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010241 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +000010242 continue;
10243 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010244 }
10245 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010246
Alexey Bataevc5e02582014-06-16 07:08:35 +000010247 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10248 // in a Construct]
10249 // Variables with the predetermined data-sharing attributes may not be
10250 // listed in data-sharing attributes clauses, except for the cases
10251 // listed below. For these exceptions only, listing a predetermined
10252 // variable in a data-sharing attribute clause is allowed and overrides
10253 // the variable's predetermined data-sharing attributes.
10254 // OpenMP [2.14.3.6, Restrictions, p.3]
10255 // Any number of reduction clauses can be specified on the directive,
10256 // but a list item can appear only once in the reduction clauses for that
10257 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +000010258 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010259 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010260 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010261 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010262 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010263 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010264 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010265 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010266 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010267 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010268 << getOpenMPClauseName(DVar.CKind)
10269 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010270 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010271 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010272 }
10273
10274 // OpenMP [2.14.3.6, Restrictions, p.1]
10275 // A list item that appears in a reduction clause of a worksharing
10276 // construct must be shared in the parallel regions to which any of the
10277 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010278 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010279 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010280 !isOpenMPParallelDirective(CurrDir) &&
10281 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010282 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010283 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010284 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010285 << getOpenMPClauseName(OMPC_reduction)
10286 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010287 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010288 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000010289 }
10290 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010291
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010292 // Try to find 'declare reduction' corresponding construct before using
10293 // builtin/overloaded operators.
10294 CXXCastPath BasePath;
10295 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010296 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010297 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10298 if (DeclareReductionRef.isInvalid())
10299 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010300 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010301 (DeclareReductionRef.isUnset() ||
10302 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010303 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010304 continue;
10305 }
10306 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
10307 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010308 S.Diag(ReductionId.getLocStart(),
10309 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010310 << Type << ReductionIdRange;
10311 continue;
10312 }
10313
10314 // OpenMP [2.14.3.6, reduction clause, Restrictions]
10315 // The type of a list item that appears in a reduction clause must be valid
10316 // for the reduction-identifier. For a max or min reduction in C, the type
10317 // of the list item must be an allowed arithmetic data type: char, int,
10318 // float, double, or _Bool, possibly modified with long, short, signed, or
10319 // unsigned. For a max or min reduction in C++, the type of the list item
10320 // must be an allowed arithmetic data type: char, wchar_t, int, float,
10321 // double, or bool, possibly modified with long, short, signed, or unsigned.
10322 if (DeclareReductionRef.isUnset()) {
10323 if ((BOK == BO_GT || BOK == BO_LT) &&
10324 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010325 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
10326 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010327 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010328 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010329 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10330 VarDecl::DeclarationOnly;
10331 S.Diag(D->getLocation(),
10332 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010333 << D;
10334 }
10335 continue;
10336 }
10337 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010338 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010339 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
10340 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010341 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010342 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10343 VarDecl::DeclarationOnly;
10344 S.Diag(D->getLocation(),
10345 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010346 << D;
10347 }
10348 continue;
10349 }
10350 }
10351
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010352 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010353 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +000010354 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010355 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010356 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010357 auto PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010358
10359 // Try if we can determine constant lengths for all array sections and avoid
10360 // the VLA.
10361 bool ConstantLengthOASE = false;
10362 if (OASE) {
10363 bool SingleElement;
10364 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
10365 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
10366 Context, OASE, SingleElement, ArraySizes);
10367
10368 // If we don't have a single element, we must emit a constant array type.
10369 if (ConstantLengthOASE && !SingleElement) {
10370 for (auto &Size : ArraySizes) {
10371 PrivateTy = Context.getConstantArrayType(
10372 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
10373 }
10374 }
10375 }
10376
10377 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000010378 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000010379 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000010380 if (!Context.getTargetInfo().isVLASupported() &&
10381 S.shouldDiagnoseTargetSupportFromOpenMP()) {
10382 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
10383 S.Diag(ELoc, diag::note_vla_unsupported);
10384 continue;
10385 }
David Majnemer9d168222016-08-05 17:44:54 +000010386 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010387 // Create pseudo array type for private copy. The size for this array will
10388 // be generated during codegen.
10389 // For array subscripts or single variables Private Ty is the same as Type
10390 // (type of the variable or single array element).
10391 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010392 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000010393 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010394 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000010395 } else if (!ASE && !OASE &&
10396 Context.getAsArrayType(D->getType().getNonReferenceType()))
10397 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010398 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010399 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010400 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010401 // Add initializer for private variable.
10402 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010403 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
10404 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010405 if (DeclareReductionRef.isUsable()) {
10406 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
10407 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
10408 if (DRD->getInitializer()) {
10409 Init = DRDRef;
10410 RHSVD->setInit(DRDRef);
10411 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010412 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010413 } else {
10414 switch (BOK) {
10415 case BO_Add:
10416 case BO_Xor:
10417 case BO_Or:
10418 case BO_LOr:
10419 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
10420 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010421 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010422 break;
10423 case BO_Mul:
10424 case BO_LAnd:
10425 if (Type->isScalarType() || Type->isAnyComplexType()) {
10426 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010427 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000010428 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010429 break;
10430 case BO_And: {
10431 // '&' reduction op - initializer is '~0'.
10432 QualType OrigType = Type;
10433 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
10434 Type = ComplexTy->getElementType();
10435 if (Type->isRealFloatingType()) {
10436 llvm::APFloat InitValue =
10437 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
10438 /*isIEEE=*/true);
10439 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10440 Type, ELoc);
10441 } else if (Type->isScalarType()) {
10442 auto Size = Context.getTypeSize(Type);
10443 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
10444 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
10445 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10446 }
10447 if (Init && OrigType->isAnyComplexType()) {
10448 // Init = 0xFFFF + 0xFFFFi;
10449 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010450 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010451 }
10452 Type = OrigType;
10453 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010454 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010455 case BO_LT:
10456 case BO_GT: {
10457 // 'min' reduction op - initializer is 'Largest representable number in
10458 // the reduction list item type'.
10459 // 'max' reduction op - initializer is 'Least representable number in
10460 // the reduction list item type'.
10461 if (Type->isIntegerType() || Type->isPointerType()) {
10462 bool IsSigned = Type->hasSignedIntegerRepresentation();
10463 auto Size = Context.getTypeSize(Type);
10464 QualType IntTy =
10465 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
10466 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010467 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
10468 : llvm::APInt::getMinValue(Size)
10469 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
10470 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010471 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10472 if (Type->isPointerType()) {
10473 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010474 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000010475 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010476 if (CastExpr.isInvalid())
10477 continue;
10478 Init = CastExpr.get();
10479 }
10480 } else if (Type->isRealFloatingType()) {
10481 llvm::APFloat InitValue = llvm::APFloat::getLargest(
10482 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
10483 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10484 Type, ELoc);
10485 }
10486 break;
10487 }
10488 case BO_PtrMemD:
10489 case BO_PtrMemI:
10490 case BO_MulAssign:
10491 case BO_Div:
10492 case BO_Rem:
10493 case BO_Sub:
10494 case BO_Shl:
10495 case BO_Shr:
10496 case BO_LE:
10497 case BO_GE:
10498 case BO_EQ:
10499 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000010500 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010501 case BO_AndAssign:
10502 case BO_XorAssign:
10503 case BO_OrAssign:
10504 case BO_Assign:
10505 case BO_AddAssign:
10506 case BO_SubAssign:
10507 case BO_DivAssign:
10508 case BO_RemAssign:
10509 case BO_ShlAssign:
10510 case BO_ShrAssign:
10511 case BO_Comma:
10512 llvm_unreachable("Unexpected reduction operation");
10513 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010514 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010515 if (Init && DeclareReductionRef.isUnset())
10516 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
10517 else if (!Init)
10518 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010519 if (RHSVD->isInvalidDecl())
10520 continue;
10521 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010522 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
10523 << Type << ReductionIdRange;
10524 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10525 VarDecl::DeclarationOnly;
10526 S.Diag(D->getLocation(),
10527 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010528 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010529 continue;
10530 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010531 // Store initializer for single element in private copy. Will be used during
10532 // codegen.
10533 PrivateVD->setInit(RHSVD->getInit());
10534 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010535 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010536 ExprResult ReductionOp;
10537 if (DeclareReductionRef.isUsable()) {
10538 QualType RedTy = DeclareReductionRef.get()->getType();
10539 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010540 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
10541 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010542 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010543 LHS = S.DefaultLvalueConversion(LHS.get());
10544 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010545 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10546 CK_UncheckedDerivedToBase, LHS.get(),
10547 &BasePath, LHS.get()->getValueKind());
10548 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10549 CK_UncheckedDerivedToBase, RHS.get(),
10550 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010551 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010552 FunctionProtoType::ExtProtoInfo EPI;
10553 QualType Params[] = {PtrRedTy, PtrRedTy};
10554 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
10555 auto *OVE = new (Context) OpaqueValueExpr(
10556 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010557 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010558 Expr *Args[] = {LHS.get(), RHS.get()};
10559 ReductionOp = new (Context)
10560 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
10561 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010562 ReductionOp = S.BuildBinOp(
10563 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010564 if (ReductionOp.isUsable()) {
10565 if (BOK != BO_LT && BOK != BO_GT) {
10566 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010567 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10568 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010569 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000010570 auto *ConditionalOp = new (Context)
10571 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
10572 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010573 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010574 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10575 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010576 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010577 if (ReductionOp.isUsable())
10578 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010579 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010580 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010581 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010582 }
10583
Alexey Bataevfa312f32017-07-21 18:48:21 +000010584 // OpenMP [2.15.4.6, Restrictions, p.2]
10585 // A list item that appears in an in_reduction clause of a task construct
10586 // must appear in a task_reduction clause of a construct associated with a
10587 // taskgroup region that includes the participating task in its taskgroup
10588 // set. The construct associated with the innermost region that meets this
10589 // condition must specify the same reduction-identifier as the in_reduction
10590 // clause.
10591 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000010592 SourceRange ParentSR;
10593 BinaryOperatorKind ParentBOK;
10594 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000010595 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000010596 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010597 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10598 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010599 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010600 Stack->getTopMostTaskgroupReductionData(
10601 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010602 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10603 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10604 if (!IsParentBOK && !IsParentReductionOp) {
10605 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10606 continue;
10607 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000010608 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10609 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10610 IsParentReductionOp) {
10611 bool EmitError = true;
10612 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10613 llvm::FoldingSetNodeID RedId, ParentRedId;
10614 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10615 DeclareReductionRef.get()->Profile(RedId, Context,
10616 /*Canonical=*/true);
10617 EmitError = RedId != ParentRedId;
10618 }
10619 if (EmitError) {
10620 S.Diag(ReductionId.getLocStart(),
10621 diag::err_omp_reduction_identifier_mismatch)
10622 << ReductionIdRange << RefExpr->getSourceRange();
10623 S.Diag(ParentSR.getBegin(),
10624 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000010625 << ParentSR
10626 << (IsParentBOK ? ParentBOKDSA.RefExpr
10627 : ParentReductionOpDSA.RefExpr)
10628 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000010629 continue;
10630 }
10631 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010632 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10633 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000010634 }
10635
Alexey Bataev60da77e2016-02-29 05:54:20 +000010636 DeclRefExpr *Ref = nullptr;
10637 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010638 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010639 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010640 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010641 VarsExpr =
10642 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10643 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000010644 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010645 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010646 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010647 if (!S.IsOpenMPCapturedDecl(D)) {
10648 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010649 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010650 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010651 if (!RefRes.isUsable())
10652 continue;
10653 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010654 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10655 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010656 if (!PostUpdateRes.isUsable())
10657 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010658 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10659 Stack->getCurrentDirective() == OMPD_taskgroup) {
10660 S.Diag(RefExpr->getExprLoc(),
10661 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000010662 << RefExpr->getSourceRange();
10663 continue;
10664 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010665 RD.ExprPostUpdates.emplace_back(
10666 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000010667 }
10668 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010669 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000010670 // All reduction items are still marked as reduction (to do not increase
10671 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010672 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010673 if (CurrDir == OMPD_taskgroup) {
10674 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010675 Stack->addTaskgroupReductionData(D, ReductionIdRange,
10676 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000010677 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010678 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010679 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010680 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10681 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010682 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010683 return RD.Vars.empty();
10684}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010685
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010686OMPClause *Sema::ActOnOpenMPReductionClause(
10687 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10688 SourceLocation ColonLoc, SourceLocation EndLoc,
10689 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10690 ArrayRef<Expr *> UnresolvedReductions) {
10691 ReductionData RD(VarList.size());
10692
Alexey Bataev169d96a2017-07-18 20:17:46 +000010693 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10694 StartLoc, LParenLoc, ColonLoc, EndLoc,
10695 ReductionIdScopeSpec, ReductionId,
10696 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010697 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000010698
Alexey Bataevc5e02582014-06-16 07:08:35 +000010699 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010700 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10701 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10702 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10703 buildPreInits(Context, RD.ExprCaptures),
10704 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000010705}
10706
Alexey Bataev169d96a2017-07-18 20:17:46 +000010707OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10708 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10709 SourceLocation ColonLoc, SourceLocation EndLoc,
10710 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10711 ArrayRef<Expr *> UnresolvedReductions) {
10712 ReductionData RD(VarList.size());
10713
10714 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
10715 VarList, StartLoc, LParenLoc, ColonLoc,
10716 EndLoc, ReductionIdScopeSpec, ReductionId,
10717 UnresolvedReductions, RD))
10718 return nullptr;
10719
10720 return OMPTaskReductionClause::Create(
10721 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10722 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10723 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10724 buildPreInits(Context, RD.ExprCaptures),
10725 buildPostUpdate(*this, RD.ExprPostUpdates));
10726}
10727
Alexey Bataevfa312f32017-07-21 18:48:21 +000010728OMPClause *Sema::ActOnOpenMPInReductionClause(
10729 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10730 SourceLocation ColonLoc, SourceLocation EndLoc,
10731 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10732 ArrayRef<Expr *> UnresolvedReductions) {
10733 ReductionData RD(VarList.size());
10734
10735 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10736 StartLoc, LParenLoc, ColonLoc, EndLoc,
10737 ReductionIdScopeSpec, ReductionId,
10738 UnresolvedReductions, RD))
10739 return nullptr;
10740
10741 return OMPInReductionClause::Create(
10742 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10743 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000010744 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000010745 buildPreInits(Context, RD.ExprCaptures),
10746 buildPostUpdate(*this, RD.ExprPostUpdates));
10747}
10748
Alexey Bataevecba70f2016-04-12 11:02:11 +000010749bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10750 SourceLocation LinLoc) {
10751 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10752 LinKind == OMPC_LINEAR_unknown) {
10753 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10754 return true;
10755 }
10756 return false;
10757}
10758
10759bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10760 OpenMPLinearClauseKind LinKind,
10761 QualType Type) {
10762 auto *VD = dyn_cast_or_null<VarDecl>(D);
10763 // A variable must not have an incomplete type or a reference type.
10764 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10765 return true;
10766 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10767 !Type->isReferenceType()) {
10768 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10769 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10770 return true;
10771 }
10772 Type = Type.getNonReferenceType();
10773
10774 // A list item must not be const-qualified.
10775 if (Type.isConstant(Context)) {
10776 Diag(ELoc, diag::err_omp_const_variable)
10777 << getOpenMPClauseName(OMPC_linear);
10778 if (D) {
10779 bool IsDecl =
10780 !VD ||
10781 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10782 Diag(D->getLocation(),
10783 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10784 << D;
10785 }
10786 return true;
10787 }
10788
10789 // A list item must be of integral or pointer type.
10790 Type = Type.getUnqualifiedType().getCanonicalType();
10791 const auto *Ty = Type.getTypePtrOrNull();
10792 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10793 !Ty->isPointerType())) {
10794 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10795 if (D) {
10796 bool IsDecl =
10797 !VD ||
10798 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10799 Diag(D->getLocation(),
10800 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10801 << D;
10802 }
10803 return true;
10804 }
10805 return false;
10806}
10807
Alexey Bataev182227b2015-08-20 10:54:39 +000010808OMPClause *Sema::ActOnOpenMPLinearClause(
10809 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10810 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10811 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010812 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010813 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000010814 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010815 SmallVector<Decl *, 4> ExprCaptures;
10816 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010817 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000010818 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +000010819 for (auto &RefExpr : VarList) {
10820 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010821 SourceLocation ELoc;
10822 SourceRange ERange;
10823 Expr *SimpleRefExpr = RefExpr;
10824 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10825 /*AllowArraySection=*/false);
10826 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010827 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010828 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010829 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000010830 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000010831 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010832 ValueDecl *D = Res.first;
10833 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000010834 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000010835
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010836 QualType Type = D->getType();
10837 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000010838
10839 // OpenMP [2.14.3.7, linear clause]
10840 // A list-item cannot appear in more than one linear clause.
10841 // A list-item that appears in a linear clause cannot appear in any
10842 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010843 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +000010844 if (DVar.RefExpr) {
10845 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10846 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010847 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000010848 continue;
10849 }
10850
Alexey Bataevecba70f2016-04-12 11:02:11 +000010851 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000010852 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010853 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000010854
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010855 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010856 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
10857 D->hasAttrs() ? &D->getAttrs() : nullptr);
10858 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010859 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010860 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010861 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010862 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010863 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000010864 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10865 if (!IsOpenMPCapturedDecl(D)) {
10866 ExprCaptures.push_back(Ref->getDecl());
10867 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10868 ExprResult RefRes = DefaultLvalueConversion(Ref);
10869 if (!RefRes.isUsable())
10870 continue;
10871 ExprResult PostUpdateRes =
10872 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10873 SimpleRefExpr, RefRes.get());
10874 if (!PostUpdateRes.isUsable())
10875 continue;
10876 ExprPostUpdates.push_back(
10877 IgnoredValueConversions(PostUpdateRes.get()).get());
10878 }
10879 }
10880 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010881 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010882 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010883 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010884 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010885 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010886 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010887 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10888
10889 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010890 Vars.push_back((VD || CurContext->isDependentContext())
10891 ? RefExpr->IgnoreParens()
10892 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010893 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000010894 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000010895 }
10896
10897 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010898 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010899
10900 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000010901 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010902 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
10903 !Step->isInstantiationDependent() &&
10904 !Step->containsUnexpandedParameterPack()) {
10905 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000010906 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000010907 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010908 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010909 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000010910
Alexander Musman3276a272015-03-21 10:12:56 +000010911 // Build var to save the step value.
10912 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010913 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000010914 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010915 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010916 ExprResult CalcStep =
10917 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010918 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +000010919
Alexander Musman8dba6642014-04-22 13:09:42 +000010920 // Warn about zero linear step (it would be probably better specified as
10921 // making corresponding variables 'const').
10922 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000010923 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
10924 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000010925 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
10926 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000010927 if (!IsConstant && CalcStep.isUsable()) {
10928 // Calculate the step beforehand instead of doing this on each iteration.
10929 // (This is not used if the number of iterations may be kfold-ed).
10930 CalcStepExpr = CalcStep.get();
10931 }
Alexander Musman8dba6642014-04-22 13:09:42 +000010932 }
10933
Alexey Bataev182227b2015-08-20 10:54:39 +000010934 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
10935 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010936 StepExpr, CalcStepExpr,
10937 buildPreInits(Context, ExprCaptures),
10938 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000010939}
10940
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010941static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
10942 Expr *NumIterations, Sema &SemaRef,
10943 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000010944 // Walk the vars and build update/final expressions for the CodeGen.
10945 SmallVector<Expr *, 8> Updates;
10946 SmallVector<Expr *, 8> Finals;
10947 Expr *Step = Clause.getStep();
10948 Expr *CalcStep = Clause.getCalcStep();
10949 // OpenMP [2.14.3.7, linear clause]
10950 // If linear-step is not specified it is assumed to be 1.
10951 if (Step == nullptr)
10952 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010953 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +000010954 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010955 }
Alexander Musman3276a272015-03-21 10:12:56 +000010956 bool HasErrors = false;
10957 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010958 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010959 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +000010960 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010961 SourceLocation ELoc;
10962 SourceRange ERange;
10963 Expr *SimpleRefExpr = RefExpr;
10964 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
10965 /*AllowArraySection=*/false);
10966 ValueDecl *D = Res.first;
10967 if (Res.second || !D) {
10968 Updates.push_back(nullptr);
10969 Finals.push_back(nullptr);
10970 HasErrors = true;
10971 continue;
10972 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010973 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000010974 // OpenMP [2.15.11, distribute simd Construct]
10975 // A list item may not appear in a linear clause, unless it is the loop
10976 // iteration variable.
10977 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
10978 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
10979 SemaRef.Diag(ELoc,
10980 diag::err_omp_linear_distribute_var_non_loop_iteration);
10981 Updates.push_back(nullptr);
10982 Finals.push_back(nullptr);
10983 HasErrors = true;
10984 continue;
10985 }
Alexander Musman3276a272015-03-21 10:12:56 +000010986 Expr *InitExpr = *CurInit;
10987
10988 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000010989 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010990 Expr *CapturedRef;
10991 if (LinKind == OMPC_LINEAR_uval)
10992 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
10993 else
10994 CapturedRef =
10995 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
10996 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
10997 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000010998
10999 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011000 ExprResult Update;
11001 if (!Info.first) {
11002 Update =
11003 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
11004 InitExpr, IV, Step, /* Subtract */ false);
11005 } else
11006 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011007 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
11008 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011009
11010 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011011 ExprResult Final;
11012 if (!Info.first) {
11013 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
11014 InitExpr, NumIterations, Step,
11015 /* Subtract */ false);
11016 } else
11017 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011018 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
11019 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011020
Alexander Musman3276a272015-03-21 10:12:56 +000011021 if (!Update.isUsable() || !Final.isUsable()) {
11022 Updates.push_back(nullptr);
11023 Finals.push_back(nullptr);
11024 HasErrors = true;
11025 } else {
11026 Updates.push_back(Update.get());
11027 Finals.push_back(Final.get());
11028 }
Richard Trieucc3949d2016-02-18 22:34:54 +000011029 ++CurInit;
11030 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000011031 }
11032 Clause.setUpdates(Updates);
11033 Clause.setFinals(Finals);
11034 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000011035}
11036
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011037OMPClause *Sema::ActOnOpenMPAlignedClause(
11038 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11039 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
11040
11041 SmallVector<Expr *, 8> Vars;
11042 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000011043 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11044 SourceLocation ELoc;
11045 SourceRange ERange;
11046 Expr *SimpleRefExpr = RefExpr;
11047 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11048 /*AllowArraySection=*/false);
11049 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011050 // It will be analyzed later.
11051 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011052 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000011053 ValueDecl *D = Res.first;
11054 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011055 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011056
Alexey Bataev1efd1662016-03-29 10:59:56 +000011057 QualType QType = D->getType();
11058 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011059
11060 // OpenMP [2.8.1, simd construct, Restrictions]
11061 // The type of list items appearing in the aligned clause must be
11062 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011063 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011064 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000011065 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011066 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011067 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011068 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000011069 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011070 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000011071 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011072 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011073 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011074 continue;
11075 }
11076
11077 // OpenMP [2.8.1, simd construct, Restrictions]
11078 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000011079 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000011080 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011081 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11082 << getOpenMPClauseName(OMPC_aligned);
11083 continue;
11084 }
11085
Alexey Bataev1efd1662016-03-29 10:59:56 +000011086 DeclRefExpr *Ref = nullptr;
11087 if (!VD && IsOpenMPCapturedDecl(D))
11088 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11089 Vars.push_back(DefaultFunctionArrayConversion(
11090 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11091 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011092 }
11093
11094 // OpenMP [2.8.1, simd construct, Description]
11095 // The parameter of the aligned clause, alignment, must be a constant
11096 // positive integer expression.
11097 // If no optional parameter is specified, implementation-defined default
11098 // alignments for SIMD instructions on the target platforms are assumed.
11099 if (Alignment != nullptr) {
11100 ExprResult AlignResult =
11101 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
11102 if (AlignResult.isInvalid())
11103 return nullptr;
11104 Alignment = AlignResult.get();
11105 }
11106 if (Vars.empty())
11107 return nullptr;
11108
11109 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
11110 EndLoc, Vars, Alignment);
11111}
11112
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011113OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11114 SourceLocation StartLoc,
11115 SourceLocation LParenLoc,
11116 SourceLocation EndLoc) {
11117 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011118 SmallVector<Expr *, 8> SrcExprs;
11119 SmallVector<Expr *, 8> DstExprs;
11120 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000011121 for (auto &RefExpr : VarList) {
11122 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
11123 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011124 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011125 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011126 SrcExprs.push_back(nullptr);
11127 DstExprs.push_back(nullptr);
11128 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011129 continue;
11130 }
11131
Alexey Bataeved09d242014-05-28 05:53:51 +000011132 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011133 // OpenMP [2.1, C/C++]
11134 // A list item is a variable name.
11135 // OpenMP [2.14.4.1, Restrictions, p.1]
11136 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000011137 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011138 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011139 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
11140 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011141 continue;
11142 }
11143
11144 Decl *D = DE->getDecl();
11145 VarDecl *VD = cast<VarDecl>(D);
11146
11147 QualType Type = VD->getType();
11148 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
11149 // It will be analyzed later.
11150 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011151 SrcExprs.push_back(nullptr);
11152 DstExprs.push_back(nullptr);
11153 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011154 continue;
11155 }
11156
11157 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
11158 // A list item that appears in a copyin clause must be threadprivate.
11159 if (!DSAStack->isThreadPrivate(VD)) {
11160 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000011161 << getOpenMPClauseName(OMPC_copyin)
11162 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011163 continue;
11164 }
11165
11166 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11167 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000011168 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011169 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011170 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000011171 auto *SrcVD =
11172 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
11173 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000011174 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011175 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
11176 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000011177 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
11178 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011179 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011180 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011181 // For arrays generate assignment operation for single element and replace
11182 // it by the original array element in CodeGen.
11183 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
11184 PseudoDstExpr, PseudoSrcExpr);
11185 if (AssignmentOp.isInvalid())
11186 continue;
11187 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
11188 /*DiscardedValue=*/true);
11189 if (AssignmentOp.isInvalid())
11190 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011191
11192 DSAStack->addDSA(VD, DE, OMPC_copyin);
11193 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011194 SrcExprs.push_back(PseudoSrcExpr);
11195 DstExprs.push_back(PseudoDstExpr);
11196 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011197 }
11198
Alexey Bataeved09d242014-05-28 05:53:51 +000011199 if (Vars.empty())
11200 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011201
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011202 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11203 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011204}
11205
Alexey Bataevbae9a792014-06-27 10:37:06 +000011206OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11207 SourceLocation StartLoc,
11208 SourceLocation LParenLoc,
11209 SourceLocation EndLoc) {
11210 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000011211 SmallVector<Expr *, 8> SrcExprs;
11212 SmallVector<Expr *, 8> DstExprs;
11213 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011214 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011215 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11216 SourceLocation ELoc;
11217 SourceRange ERange;
11218 Expr *SimpleRefExpr = RefExpr;
11219 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11220 /*AllowArraySection=*/false);
11221 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011222 // It will be analyzed later.
11223 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011224 SrcExprs.push_back(nullptr);
11225 DstExprs.push_back(nullptr);
11226 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011227 }
Alexey Bataeve122da12016-03-17 10:50:17 +000011228 ValueDecl *D = Res.first;
11229 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000011230 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011231
Alexey Bataeve122da12016-03-17 10:50:17 +000011232 QualType Type = D->getType();
11233 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011234
11235 // OpenMP [2.14.4.2, Restrictions, p.2]
11236 // A list item that appears in a copyprivate clause may not appear in a
11237 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000011238 if (!VD || !DSAStack->isThreadPrivate(VD)) {
11239 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011240 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
11241 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011242 Diag(ELoc, diag::err_omp_wrong_dsa)
11243 << getOpenMPClauseName(DVar.CKind)
11244 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000011245 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011246 continue;
11247 }
11248
11249 // OpenMP [2.11.4.2, Restrictions, p.1]
11250 // All list items that appear in a copyprivate clause must be either
11251 // threadprivate or private in the enclosing context.
11252 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011253 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011254 if (DVar.CKind == OMPC_shared) {
11255 Diag(ELoc, diag::err_omp_required_access)
11256 << getOpenMPClauseName(OMPC_copyprivate)
11257 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000011258 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011259 continue;
11260 }
11261 }
11262 }
11263
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011264 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011265 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011266 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011267 << getOpenMPClauseName(OMPC_copyprivate) << Type
11268 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011269 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000011270 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011271 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000011272 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011273 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000011274 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011275 continue;
11276 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011277
Alexey Bataevbae9a792014-06-27 10:37:06 +000011278 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11279 // A variable of class type (or array thereof) that appears in a
11280 // copyin clause requires an accessible, unambiguous copy assignment
11281 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011282 Type = Context.getBaseElementType(Type.getNonReferenceType())
11283 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000011284 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011285 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
11286 D->hasAttrs() ? &D->getAttrs() : nullptr);
11287 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000011288 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011289 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
11290 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000011291 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000011292 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011293 PseudoDstExpr, PseudoSrcExpr);
11294 if (AssignmentOp.isInvalid())
11295 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000011296 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011297 /*DiscardedValue=*/true);
11298 if (AssignmentOp.isInvalid())
11299 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011300
11301 // No need to mark vars as copyprivate, they are already threadprivate or
11302 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000011303 assert(VD || IsOpenMPCapturedDecl(D));
11304 Vars.push_back(
11305 VD ? RefExpr->IgnoreParens()
11306 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000011307 SrcExprs.push_back(PseudoSrcExpr);
11308 DstExprs.push_back(PseudoDstExpr);
11309 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000011310 }
11311
11312 if (Vars.empty())
11313 return nullptr;
11314
Alexey Bataeva63048e2015-03-23 06:18:07 +000011315 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11316 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011317}
11318
Alexey Bataev6125da92014-07-21 11:26:11 +000011319OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11320 SourceLocation StartLoc,
11321 SourceLocation LParenLoc,
11322 SourceLocation EndLoc) {
11323 if (VarList.empty())
11324 return nullptr;
11325
11326 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
11327}
Alexey Bataevdea47612014-07-23 07:46:59 +000011328
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011329OMPClause *
11330Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
11331 SourceLocation DepLoc, SourceLocation ColonLoc,
11332 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11333 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011334 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011335 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011336 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011337 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000011338 return nullptr;
11339 }
11340 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011341 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
11342 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011343 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011344 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011345 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
11346 /*Last=*/OMPC_DEPEND_unknown, Except)
11347 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011348 return nullptr;
11349 }
11350 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000011351 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011352 llvm::APSInt DepCounter(/*BitWidth=*/32);
11353 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
11354 if (DepKind == OMPC_DEPEND_sink) {
11355 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
11356 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
11357 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011358 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011359 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011360 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
11361 DSAStack->getParentOrderedRegionParam()) {
11362 for (auto &RefExpr : VarList) {
11363 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000011364 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011365 // It will be analyzed later.
11366 Vars.push_back(RefExpr);
11367 continue;
11368 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011369
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011370 SourceLocation ELoc = RefExpr->getExprLoc();
11371 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
11372 if (DepKind == OMPC_DEPEND_sink) {
11373 if (DepCounter >= TotalDepCount) {
11374 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
11375 continue;
11376 }
11377 ++DepCounter;
11378 // OpenMP [2.13.9, Summary]
11379 // depend(dependence-type : vec), where dependence-type is:
11380 // 'sink' and where vec is the iteration vector, which has the form:
11381 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
11382 // where n is the value specified by the ordered clause in the loop
11383 // directive, xi denotes the loop iteration variable of the i-th nested
11384 // loop associated with the loop directive, and di is a constant
11385 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000011386 if (CurContext->isDependentContext()) {
11387 // It will be analyzed later.
11388 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011389 continue;
11390 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011391 SimpleExpr = SimpleExpr->IgnoreImplicit();
11392 OverloadedOperatorKind OOK = OO_None;
11393 SourceLocation OOLoc;
11394 Expr *LHS = SimpleExpr;
11395 Expr *RHS = nullptr;
11396 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
11397 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
11398 OOLoc = BO->getOperatorLoc();
11399 LHS = BO->getLHS()->IgnoreParenImpCasts();
11400 RHS = BO->getRHS()->IgnoreParenImpCasts();
11401 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
11402 OOK = OCE->getOperator();
11403 OOLoc = OCE->getOperatorLoc();
11404 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11405 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
11406 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
11407 OOK = MCE->getMethodDecl()
11408 ->getNameInfo()
11409 .getName()
11410 .getCXXOverloadedOperator();
11411 OOLoc = MCE->getCallee()->getExprLoc();
11412 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
11413 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11414 }
11415 SourceLocation ELoc;
11416 SourceRange ERange;
11417 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
11418 /*AllowArraySection=*/false);
11419 if (Res.second) {
11420 // It will be analyzed later.
11421 Vars.push_back(RefExpr);
11422 }
11423 ValueDecl *D = Res.first;
11424 if (!D)
11425 continue;
11426
11427 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
11428 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
11429 continue;
11430 }
11431 if (RHS) {
11432 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
11433 RHS, OMPC_depend, /*StrictlyPositive=*/false);
11434 if (RHSRes.isInvalid())
11435 continue;
11436 }
11437 if (!CurContext->isDependentContext() &&
11438 DSAStack->getParentOrderedRegionParam() &&
11439 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Rachel Craik1cf49e42017-09-19 21:04:23 +000011440 ValueDecl* VD = DSAStack->getParentLoopControlVariable(
11441 DepCounter.getZExtValue());
11442 if (VD) {
11443 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
11444 << 1 << VD;
11445 } else {
11446 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
11447 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011448 continue;
11449 }
11450 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011451 } else {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011452 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011453 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000011454 (ASE &&
11455 !ASE->getBase()
11456 ->getType()
11457 .getNonReferenceType()
11458 ->isPointerType() &&
11459 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev463a9fe2017-07-27 19:15:30 +000011460 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11461 << RefExpr->getSourceRange();
11462 continue;
11463 }
11464 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
11465 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevd070a582017-10-25 15:54:04 +000011466 ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
Alexey Bataev463a9fe2017-07-27 19:15:30 +000011467 RefExpr->IgnoreParenImpCasts());
11468 getDiagnostics().setSuppressAllDiagnostics(Suppress);
11469 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
11470 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11471 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011472 continue;
11473 }
11474 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011475 Vars.push_back(RefExpr->IgnoreParenImpCasts());
11476 }
11477
11478 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
11479 TotalDepCount > VarList.size() &&
Rachel Craik1cf49e42017-09-19 21:04:23 +000011480 DSAStack->getParentOrderedRegionParam() &&
11481 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
11482 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011483 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
11484 }
11485 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
11486 Vars.empty())
11487 return nullptr;
11488 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011489 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11490 DepKind, DepLoc, ColonLoc, Vars);
11491 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
11492 DSAStack->addDoacrossDependClause(C, OpsOffs);
11493 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011494}
Michael Wonge710d542015-08-07 16:16:36 +000011495
11496OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
11497 SourceLocation LParenLoc,
11498 SourceLocation EndLoc) {
11499 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000011500 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000011501
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011502 // OpenMP [2.9.1, Restrictions]
11503 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011504 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
11505 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011506 return nullptr;
11507
Alexey Bataev931e19b2017-10-02 16:32:39 +000011508 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011509 OpenMPDirectiveKind CaptureRegion =
11510 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
11511 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011512 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev931e19b2017-10-02 16:32:39 +000011513 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11514 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11515 HelperValStmt = buildPreInits(Context, Captures);
11516 }
11517
Alexey Bataev8451efa2018-01-15 19:06:12 +000011518 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
11519 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000011520}
Kelvin Li0bff7af2015-11-23 05:32:03 +000011521
Kelvin Li0bff7af2015-11-23 05:32:03 +000011522static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
11523 DSAStackTy *Stack, QualType QTy) {
11524 NamedDecl *ND;
11525 if (QTy->isIncompleteType(&ND)) {
11526 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
11527 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011528 }
11529 return true;
11530}
11531
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011532/// \brief Return true if it can be proven that the provided array expression
11533/// (array section or array subscript) does NOT specify the whole size of the
11534/// array whose base type is \a BaseQTy.
11535static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
11536 const Expr *E,
11537 QualType BaseQTy) {
11538 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11539
11540 // If this is an array subscript, it refers to the whole size if the size of
11541 // the dimension is constant and equals 1. Also, an array section assumes the
11542 // format of an array subscript if no colon is used.
11543 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
11544 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11545 return ATy->getSize().getSExtValue() != 1;
11546 // Size can't be evaluated statically.
11547 return false;
11548 }
11549
11550 assert(OASE && "Expecting array section if not an array subscript.");
11551 auto *LowerBound = OASE->getLowerBound();
11552 auto *Length = OASE->getLength();
11553
11554 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000011555 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011556 if (LowerBound) {
11557 llvm::APSInt ConstLowerBound;
11558 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
11559 return false; // Can't get the integer value as a constant.
11560 if (ConstLowerBound.getSExtValue())
11561 return true;
11562 }
11563
11564 // If we don't have a length we covering the whole dimension.
11565 if (!Length)
11566 return false;
11567
11568 // If the base is a pointer, we don't have a way to get the size of the
11569 // pointee.
11570 if (BaseQTy->isPointerType())
11571 return false;
11572
11573 // We can only check if the length is the same as the size of the dimension
11574 // if we have a constant array.
11575 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
11576 if (!CATy)
11577 return false;
11578
11579 llvm::APSInt ConstLength;
11580 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11581 return false; // Can't get the integer value as a constant.
11582
11583 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
11584}
11585
11586// Return true if it can be proven that the provided array expression (array
11587// section or array subscript) does NOT specify a single element of the array
11588// whose base type is \a BaseQTy.
11589static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000011590 const Expr *E,
11591 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011592 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11593
11594 // An array subscript always refer to a single element. Also, an array section
11595 // assumes the format of an array subscript if no colon is used.
11596 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11597 return false;
11598
11599 assert(OASE && "Expecting array section if not an array subscript.");
11600 auto *Length = OASE->getLength();
11601
11602 // If we don't have a length we have to check if the array has unitary size
11603 // for this dimension. Also, we should always expect a length if the base type
11604 // is pointer.
11605 if (!Length) {
11606 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11607 return ATy->getSize().getSExtValue() != 1;
11608 // We cannot assume anything.
11609 return false;
11610 }
11611
11612 // Check if the length evaluates to 1.
11613 llvm::APSInt ConstLength;
11614 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11615 return false; // Can't get the integer value as a constant.
11616
11617 return ConstLength.getSExtValue() != 1;
11618}
11619
Samuel Antao661c0902016-05-26 17:39:58 +000011620// Return the expression of the base of the mappable expression or null if it
11621// cannot be determined and do all the necessary checks to see if the expression
11622// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000011623// components of the expression.
11624static Expr *CheckMapClauseExpressionBase(
11625 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000011626 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011627 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011628 SourceLocation ELoc = E->getExprLoc();
11629 SourceRange ERange = E->getSourceRange();
11630
11631 // The base of elements of list in a map clause have to be either:
11632 // - a reference to variable or field.
11633 // - a member expression.
11634 // - an array expression.
11635 //
11636 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11637 // reference to 'r'.
11638 //
11639 // If we have:
11640 //
11641 // struct SS {
11642 // Bla S;
11643 // foo() {
11644 // #pragma omp target map (S.Arr[:12]);
11645 // }
11646 // }
11647 //
11648 // We want to retrieve the member expression 'this->S';
11649
11650 Expr *RelevantExpr = nullptr;
11651
Samuel Antao5de996e2016-01-22 20:21:36 +000011652 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11653 // If a list item is an array section, it must specify contiguous storage.
11654 //
11655 // For this restriction it is sufficient that we make sure only references
11656 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011657 // exist except in the rightmost expression (unless they cover the whole
11658 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000011659 //
11660 // r.ArrS[3:5].Arr[6:7]
11661 //
11662 // r.ArrS[3:5].x
11663 //
11664 // but these would be valid:
11665 // r.ArrS[3].Arr[6:7]
11666 //
11667 // r.ArrS[3].x
11668
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011669 bool AllowUnitySizeArraySection = true;
11670 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000011671
Dmitry Polukhin644a9252016-03-11 07:58:34 +000011672 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011673 E = E->IgnoreParenImpCasts();
11674
11675 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11676 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000011677 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011678
11679 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011680
11681 // If we got a reference to a declaration, we should not expect any array
11682 // section before that.
11683 AllowUnitySizeArraySection = false;
11684 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011685
11686 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011687 CurComponents.emplace_back(CurE, CurE->getDecl());
11688 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011689 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11690
11691 if (isa<CXXThisExpr>(BaseE))
11692 // We found a base expression: this->Val.
11693 RelevantExpr = CurE;
11694 else
11695 E = BaseE;
11696
11697 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011698 if (!NoDiagnose) {
11699 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11700 << CurE->getSourceRange();
11701 return nullptr;
11702 }
11703 if (RelevantExpr)
11704 return nullptr;
11705 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011706 }
11707
11708 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11709
11710 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11711 // A bit-field cannot appear in a map clause.
11712 //
11713 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011714 if (!NoDiagnose) {
11715 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11716 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
11717 return nullptr;
11718 }
11719 if (RelevantExpr)
11720 return nullptr;
11721 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011722 }
11723
11724 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11725 // If the type of a list item is a reference to a type T then the type
11726 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011727 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011728
11729 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11730 // A list item cannot be a variable that is a member of a structure with
11731 // a union type.
11732 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011733 if (auto *RT = CurType->getAs<RecordType>()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011734 if (RT->isUnionType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011735 if (!NoDiagnose) {
11736 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11737 << CurE->getSourceRange();
11738 return nullptr;
11739 }
11740 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011741 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011742 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011743
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011744 // If we got a member expression, we should not expect any array section
11745 // before that:
11746 //
11747 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11748 // If a list item is an element of a structure, only the rightmost symbol
11749 // of the variable reference can be an array section.
11750 //
11751 AllowUnitySizeArraySection = false;
11752 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011753
11754 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011755 CurComponents.emplace_back(CurE, FD);
11756 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011757 E = CurE->getBase()->IgnoreParenImpCasts();
11758
11759 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011760 if (!NoDiagnose) {
11761 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11762 << 0 << CurE->getSourceRange();
11763 return nullptr;
11764 }
11765 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011766 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011767
11768 // If we got an array subscript that express the whole dimension we
11769 // can have any array expressions before. If it only expressing part of
11770 // the dimension, we can only have unitary-size array expressions.
11771 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11772 E->getType()))
11773 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011774
11775 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011776 CurComponents.emplace_back(CurE, nullptr);
11777 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011778 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000011779 E = CurE->getBase()->IgnoreParenImpCasts();
11780
Alexey Bataev27041fa2017-12-05 15:22:49 +000011781 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011782 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11783
Samuel Antao5de996e2016-01-22 20:21:36 +000011784 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11785 // If the type of a list item is a reference to a type T then the type
11786 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000011787 if (CurType->isReferenceType())
11788 CurType = CurType->getPointeeType();
11789
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011790 bool IsPointer = CurType->isAnyPointerType();
11791
11792 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011793 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11794 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000011795 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011796 }
11797
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011798 bool NotWhole =
11799 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11800 bool NotUnity =
11801 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11802
Samuel Antaodab51bb2016-07-18 23:22:11 +000011803 if (AllowWholeSizeArraySection) {
11804 // Any array section is currently allowed. Allowing a whole size array
11805 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011806 //
11807 // If this array section refers to the whole dimension we can still
11808 // accept other array sections before this one, except if the base is a
11809 // pointer. Otherwise, only unitary sections are accepted.
11810 if (NotWhole || IsPointer)
11811 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000011812 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011813 // A unity or whole array section is not allowed and that is not
11814 // compatible with the properties of the current array section.
11815 SemaRef.Diag(
11816 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11817 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000011818 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011819 }
Samuel Antao90927002016-04-26 14:54:23 +000011820
11821 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011822 CurComponents.emplace_back(CurE, nullptr);
11823 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011824 if (!NoDiagnose) {
11825 // If nothing else worked, this is not a valid map clause expression.
11826 SemaRef.Diag(
11827 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
11828 << ERange;
11829 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000011830 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011831 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011832 }
11833
11834 return RelevantExpr;
11835}
11836
11837// Return true if expression E associated with value VD has conflicts with other
11838// map information.
Samuel Antao90927002016-04-26 14:54:23 +000011839static bool CheckMapConflicts(
11840 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11841 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000011842 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11843 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011844 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000011845 SourceLocation ELoc = E->getExprLoc();
11846 SourceRange ERange = E->getSourceRange();
11847
11848 // In order to easily check the conflicts we need to match each component of
11849 // the expression under test with the components of the expressions that are
11850 // already in the stack.
11851
Samuel Antao5de996e2016-01-22 20:21:36 +000011852 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011853 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011854 "Map clause expression with unexpected base!");
11855
11856 // Variables to help detecting enclosing problems in data environment nests.
11857 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000011858 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011859
Samuel Antao90927002016-04-26 14:54:23 +000011860 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11861 VD, CurrentRegionOnly,
11862 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000011863 StackComponents,
11864 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000011865
Samuel Antao5de996e2016-01-22 20:21:36 +000011866 assert(!StackComponents.empty() &&
11867 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011868 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011869 "Map clause expression with unexpected base!");
11870
Samuel Antao90927002016-04-26 14:54:23 +000011871 // The whole expression in the stack.
11872 auto *RE = StackComponents.front().getAssociatedExpression();
11873
Samuel Antao5de996e2016-01-22 20:21:36 +000011874 // Expressions must start from the same base. Here we detect at which
11875 // point both expressions diverge from each other and see if we can
11876 // detect if the memory referred to both expressions is contiguous and
11877 // do not overlap.
11878 auto CI = CurComponents.rbegin();
11879 auto CE = CurComponents.rend();
11880 auto SI = StackComponents.rbegin();
11881 auto SE = StackComponents.rend();
11882 for (; CI != CE && SI != SE; ++CI, ++SI) {
11883
11884 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11885 // At most one list item can be an array item derived from a given
11886 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000011887 if (CurrentRegionOnly &&
11888 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
11889 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
11890 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
11891 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
11892 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000011893 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000011894 << CI->getAssociatedExpression()->getSourceRange();
11895 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
11896 diag::note_used_here)
11897 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000011898 return true;
11899 }
11900
11901 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000011902 if (CI->getAssociatedExpression()->getStmtClass() !=
11903 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000011904 break;
11905
11906 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000011907 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000011908 break;
11909 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000011910 // Check if the extra components of the expressions in the enclosing
11911 // data environment are redundant for the current base declaration.
11912 // If they are, the maps completely overlap, which is legal.
11913 for (; SI != SE; ++SI) {
11914 QualType Type;
11915 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000011916 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011917 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000011918 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
11919 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011920 auto *E = OASE->getBase()->IgnoreParenImpCasts();
11921 Type =
11922 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11923 }
11924 if (Type.isNull() || Type->isAnyPointerType() ||
11925 CheckArrayExpressionDoesNotReferToWholeSize(
11926 SemaRef, SI->getAssociatedExpression(), Type))
11927 break;
11928 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011929
11930 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11931 // List items of map clauses in the same construct must not share
11932 // original storage.
11933 //
11934 // If the expressions are exactly the same or one is a subset of the
11935 // other, it means they are sharing storage.
11936 if (CI == CE && SI == SE) {
11937 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000011938 if (CKind == OMPC_map)
11939 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11940 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011941 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011942 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11943 << ERange;
11944 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011945 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11946 << RE->getSourceRange();
11947 return true;
11948 } else {
11949 // If we find the same expression in the enclosing data environment,
11950 // that is legal.
11951 IsEnclosedByDataEnvironmentExpr = true;
11952 return false;
11953 }
11954 }
11955
Samuel Antao90927002016-04-26 14:54:23 +000011956 QualType DerivedType =
11957 std::prev(CI)->getAssociatedDeclaration()->getType();
11958 SourceLocation DerivedLoc =
11959 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000011960
11961 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11962 // If the type of a list item is a reference to a type T then the type
11963 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011964 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011965
11966 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
11967 // A variable for which the type is pointer and an array section
11968 // derived from that variable must not appear as list items of map
11969 // clauses of the same construct.
11970 //
11971 // Also, cover one of the cases in:
11972 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11973 // If any part of the original storage of a list item has corresponding
11974 // storage in the device data environment, all of the original storage
11975 // must have corresponding storage in the device data environment.
11976 //
11977 if (DerivedType->isAnyPointerType()) {
11978 if (CI == CE || SI == SE) {
11979 SemaRef.Diag(
11980 DerivedLoc,
11981 diag::err_omp_pointer_mapped_along_with_derived_section)
11982 << DerivedLoc;
11983 } else {
11984 assert(CI != CE && SI != SE);
11985 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
11986 << DerivedLoc;
11987 }
11988 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11989 << RE->getSourceRange();
11990 return true;
11991 }
11992
11993 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11994 // List items of map clauses in the same construct must not share
11995 // original storage.
11996 //
11997 // An expression is a subset of the other.
11998 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000011999 if (CKind == OMPC_map)
12000 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12001 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012002 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012003 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12004 << ERange;
12005 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012006 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12007 << RE->getSourceRange();
12008 return true;
12009 }
12010
12011 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000012012 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000012013 if (!CurrentRegionOnly && SI != SE)
12014 EnclosingExpr = RE;
12015
12016 // The current expression is a subset of the expression in the data
12017 // environment.
12018 IsEnclosedByDataEnvironmentExpr |=
12019 (!CurrentRegionOnly && CI != CE && SI == SE);
12020
12021 return false;
12022 });
12023
12024 if (CurrentRegionOnly)
12025 return FoundError;
12026
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 must
12030 // have corresponding storage in the device data environment.
12031 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
12032 // If a list item is an element of a structure, and a different element of
12033 // the structure has a corresponding list item in the device data environment
12034 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000012035 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000012036 // data environment prior to the task encountering the construct.
12037 //
12038 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
12039 SemaRef.Diag(ELoc,
12040 diag::err_omp_original_storage_is_shared_and_does_not_contain)
12041 << ERange;
12042 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
12043 << EnclosingExpr->getSourceRange();
12044 return true;
12045 }
12046
12047 return FoundError;
12048}
12049
Samuel Antao661c0902016-05-26 17:39:58 +000012050namespace {
12051// Utility struct that gathers all the related lists associated with a mappable
12052// expression.
12053struct MappableVarListInfo final {
12054 // The list of expressions.
12055 ArrayRef<Expr *> VarList;
12056 // The list of processed expressions.
12057 SmallVector<Expr *, 16> ProcessedVarList;
12058 // The mappble components for each expression.
12059 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
12060 // The base declaration of the variable.
12061 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
12062
12063 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
12064 // We have a list of components and base declarations for each entry in the
12065 // variable list.
12066 VarComponents.reserve(VarList.size());
12067 VarBaseDeclarations.reserve(VarList.size());
12068 }
12069};
12070}
12071
12072// Check the validity of the provided variable list for the provided clause kind
12073// \a CKind. In the check process the valid expressions, and mappable expression
12074// components and variables are extracted and used to fill \a Vars,
12075// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
12076// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
12077static void
12078checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
12079 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
12080 SourceLocation StartLoc,
12081 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
12082 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000012083 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
12084 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000012085 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012086
Samuel Antao90927002016-04-26 14:54:23 +000012087 // Keep track of the mappable components and base declarations in this clause.
12088 // Each entry in the list is going to have a list of components associated. We
12089 // record each set of the components so that we can build the clause later on.
12090 // In the end we should have the same amount of declarations and component
12091 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000012092
Samuel Antao661c0902016-05-26 17:39:58 +000012093 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000012094 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012095 SourceLocation ELoc = RE->getExprLoc();
12096
Kelvin Li0bff7af2015-11-23 05:32:03 +000012097 auto *VE = RE->IgnoreParenLValueCasts();
12098
12099 if (VE->isValueDependent() || VE->isTypeDependent() ||
12100 VE->isInstantiationDependent() ||
12101 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012102 // We can only analyze this information once the missing information is
12103 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000012104 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012105 continue;
12106 }
12107
12108 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012109
Samuel Antao5de996e2016-01-22 20:21:36 +000012110 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000012111 SemaRef.Diag(ELoc,
12112 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000012113 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012114 continue;
12115 }
12116
Samuel Antao90927002016-04-26 14:54:23 +000012117 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
12118 ValueDecl *CurDeclaration = nullptr;
12119
12120 // Obtain the array or member expression bases if required. Also, fill the
12121 // components array with all the components identified in the process.
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012122 auto *BE = CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents,
12123 CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000012124 if (!BE)
12125 continue;
12126
Samuel Antao90927002016-04-26 14:54:23 +000012127 assert(!CurComponents.empty() &&
12128 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012129
Samuel Antao90927002016-04-26 14:54:23 +000012130 // For the following checks, we rely on the base declaration which is
12131 // expected to be associated with the last component. The declaration is
12132 // expected to be a variable or a field (if 'this' is being mapped).
12133 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
12134 assert(CurDeclaration && "Null decl on map clause.");
12135 assert(
12136 CurDeclaration->isCanonicalDecl() &&
12137 "Expecting components to have associated only canonical declarations.");
12138
12139 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
12140 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000012141
12142 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000012143 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000012144
12145 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000012146 // threadprivate variables cannot appear in a map clause.
12147 // OpenMP 4.5 [2.10.5, target update Construct]
12148 // threadprivate variables cannot appear in a from clause.
12149 if (VD && DSAS->isThreadPrivate(VD)) {
12150 auto DVar = DSAS->getTopDSA(VD, false);
12151 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
12152 << getOpenMPClauseName(CKind);
12153 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012154 continue;
12155 }
12156
Samuel Antao5de996e2016-01-22 20:21:36 +000012157 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12158 // A list item cannot appear in both a map clause and a data-sharing
12159 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000012160
Samuel Antao5de996e2016-01-22 20:21:36 +000012161 // Check conflicts with other map clause expressions. We check the conflicts
12162 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000012163 // environment, because the restrictions are different. We only have to
12164 // check conflicts across regions for the map clauses.
12165 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12166 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000012167 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012168 if (CKind == OMPC_map &&
12169 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12170 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000012171 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012172
Samuel Antao661c0902016-05-26 17:39:58 +000012173 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000012174 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12175 // If the type of a list item is a reference to a type T then the type will
12176 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000012177 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012178
Samuel Antao661c0902016-05-26 17:39:58 +000012179 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
12180 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000012181 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000012182 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000012183 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
12184 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000012185 continue;
12186
Samuel Antao661c0902016-05-26 17:39:58 +000012187 if (CKind == OMPC_map) {
12188 // target enter data
12189 // OpenMP [2.10.2, Restrictions, p. 99]
12190 // A map-type must be specified in all map clauses and must be either
12191 // to or alloc.
12192 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
12193 if (DKind == OMPD_target_enter_data &&
12194 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
12195 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12196 << (IsMapTypeImplicit ? 1 : 0)
12197 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12198 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012199 continue;
12200 }
Samuel Antao661c0902016-05-26 17:39:58 +000012201
12202 // target exit_data
12203 // OpenMP [2.10.3, Restrictions, p. 102]
12204 // A map-type must be specified in all map clauses and must be either
12205 // from, release, or delete.
12206 if (DKind == OMPD_target_exit_data &&
12207 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
12208 MapType == OMPC_MAP_delete)) {
12209 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12210 << (IsMapTypeImplicit ? 1 : 0)
12211 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12212 << getOpenMPDirectiveName(DKind);
12213 continue;
12214 }
12215
12216 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12217 // A list item cannot appear in both a map clause and a data-sharing
12218 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000012219 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000012220 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000012221 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000012222 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
12223 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000012224 auto DVar = DSAS->getTopDSA(VD, false);
12225 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000012226 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000012227 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000012228 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000012229 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
12230 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
12231 continue;
12232 }
12233 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012234 }
12235
Samuel Antao90927002016-04-26 14:54:23 +000012236 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000012237 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000012238
12239 // Store the components in the stack so that they can be used to check
12240 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000012241 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
12242 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000012243
12244 // Save the components and declaration to create the clause. For purposes of
12245 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000012246 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000012247 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12248 MVLI.VarComponents.back().append(CurComponents.begin(),
12249 CurComponents.end());
12250 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
12251 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012252 }
Samuel Antao661c0902016-05-26 17:39:58 +000012253}
12254
12255OMPClause *
12256Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
12257 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12258 SourceLocation MapLoc, SourceLocation ColonLoc,
12259 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12260 SourceLocation LParenLoc, SourceLocation EndLoc) {
12261 MappableVarListInfo MVLI(VarList);
12262 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
12263 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012264
Samuel Antao5de996e2016-01-22 20:21:36 +000012265 // We need to produce a map clause even if we don't have variables so that
12266 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000012267 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12268 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12269 MVLI.VarComponents, MapTypeModifier, MapType,
12270 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012271}
Kelvin Li099bb8c2015-11-24 20:50:12 +000012272
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012273QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
12274 TypeResult ParsedType) {
12275 assert(ParsedType.isUsable());
12276
12277 QualType ReductionType = GetTypeFromParser(ParsedType.get());
12278 if (ReductionType.isNull())
12279 return QualType();
12280
12281 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
12282 // A type name in a declare reduction directive cannot be a function type, an
12283 // array type, a reference type, or a type qualified with const, volatile or
12284 // restrict.
12285 if (ReductionType.hasQualifiers()) {
12286 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
12287 return QualType();
12288 }
12289
12290 if (ReductionType->isFunctionType()) {
12291 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
12292 return QualType();
12293 }
12294 if (ReductionType->isReferenceType()) {
12295 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
12296 return QualType();
12297 }
12298 if (ReductionType->isArrayType()) {
12299 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
12300 return QualType();
12301 }
12302 return ReductionType;
12303}
12304
12305Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
12306 Scope *S, DeclContext *DC, DeclarationName Name,
12307 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
12308 AccessSpecifier AS, Decl *PrevDeclInScope) {
12309 SmallVector<Decl *, 8> Decls;
12310 Decls.reserve(ReductionTypes.size());
12311
12312 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000012313 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012314 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
12315 // A reduction-identifier may not be re-declared in the current scope for the
12316 // same type or for a type that is compatible according to the base language
12317 // rules.
12318 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
12319 OMPDeclareReductionDecl *PrevDRD = nullptr;
12320 bool InCompoundScope = true;
12321 if (S != nullptr) {
12322 // Find previous declaration with the same name not referenced in other
12323 // declarations.
12324 FunctionScopeInfo *ParentFn = getEnclosingFunction();
12325 InCompoundScope =
12326 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
12327 LookupName(Lookup, S);
12328 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
12329 /*AllowInlineNamespace=*/false);
12330 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
12331 auto Filter = Lookup.makeFilter();
12332 while (Filter.hasNext()) {
12333 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
12334 if (InCompoundScope) {
12335 auto I = UsedAsPrevious.find(PrevDecl);
12336 if (I == UsedAsPrevious.end())
12337 UsedAsPrevious[PrevDecl] = false;
12338 if (auto *D = PrevDecl->getPrevDeclInScope())
12339 UsedAsPrevious[D] = true;
12340 }
12341 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
12342 PrevDecl->getLocation();
12343 }
12344 Filter.done();
12345 if (InCompoundScope) {
12346 for (auto &PrevData : UsedAsPrevious) {
12347 if (!PrevData.second) {
12348 PrevDRD = PrevData.first;
12349 break;
12350 }
12351 }
12352 }
12353 } else if (PrevDeclInScope != nullptr) {
12354 auto *PrevDRDInScope = PrevDRD =
12355 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
12356 do {
12357 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
12358 PrevDRDInScope->getLocation();
12359 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
12360 } while (PrevDRDInScope != nullptr);
12361 }
12362 for (auto &TyData : ReductionTypes) {
12363 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
12364 bool Invalid = false;
12365 if (I != PreviousRedeclTypes.end()) {
12366 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
12367 << TyData.first;
12368 Diag(I->second, diag::note_previous_definition);
12369 Invalid = true;
12370 }
12371 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
12372 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
12373 Name, TyData.first, PrevDRD);
12374 DC->addDecl(DRD);
12375 DRD->setAccess(AS);
12376 Decls.push_back(DRD);
12377 if (Invalid)
12378 DRD->setInvalidDecl();
12379 else
12380 PrevDRD = DRD;
12381 }
12382
12383 return DeclGroupPtrTy::make(
12384 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
12385}
12386
12387void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
12388 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12389
12390 // Enter new function scope.
12391 PushFunctionScope();
12392 getCurFunction()->setHasBranchProtectedScope();
12393 getCurFunction()->setHasOMPDeclareReductionCombiner();
12394
12395 if (S != nullptr)
12396 PushDeclContext(S, DRD);
12397 else
12398 CurContext = DRD;
12399
Faisal Valid143a0c2017-04-01 21:30:49 +000012400 PushExpressionEvaluationContext(
12401 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012402
12403 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012404 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
12405 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
12406 // uses semantics of argument handles by value, but it should be passed by
12407 // reference. C lang does not support references, so pass all parameters as
12408 // pointers.
12409 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012410 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012411 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012412 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
12413 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
12414 // uses semantics of argument handles by value, but it should be passed by
12415 // reference. C lang does not support references, so pass all parameters as
12416 // pointers.
12417 // Create 'T omp_out;' variable.
12418 auto *OmpOutParm =
12419 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
12420 if (S != nullptr) {
12421 PushOnScopeChains(OmpInParm, S);
12422 PushOnScopeChains(OmpOutParm, S);
12423 } else {
12424 DRD->addDecl(OmpInParm);
12425 DRD->addDecl(OmpOutParm);
12426 }
12427}
12428
12429void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
12430 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12431 DiscardCleanupsInEvaluationContext();
12432 PopExpressionEvaluationContext();
12433
12434 PopDeclContext();
12435 PopFunctionScopeInfo();
12436
12437 if (Combiner != nullptr)
12438 DRD->setCombiner(Combiner);
12439 else
12440 DRD->setInvalidDecl();
12441}
12442
Alexey Bataev070f43a2017-09-06 14:49:58 +000012443VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012444 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12445
12446 // Enter new function scope.
12447 PushFunctionScope();
12448 getCurFunction()->setHasBranchProtectedScope();
12449
12450 if (S != nullptr)
12451 PushDeclContext(S, DRD);
12452 else
12453 CurContext = DRD;
12454
Faisal Valid143a0c2017-04-01 21:30:49 +000012455 PushExpressionEvaluationContext(
12456 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012457
12458 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012459 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
12460 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
12461 // uses semantics of argument handles by value, but it should be passed by
12462 // reference. C lang does not support references, so pass all parameters as
12463 // pointers.
12464 // Create 'T omp_priv;' variable.
12465 auto *OmpPrivParm =
12466 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012467 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
12468 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
12469 // uses semantics of argument handles by value, but it should be passed by
12470 // reference. C lang does not support references, so pass all parameters as
12471 // pointers.
12472 // Create 'T omp_orig;' variable.
12473 auto *OmpOrigParm =
12474 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012475 if (S != nullptr) {
12476 PushOnScopeChains(OmpPrivParm, S);
12477 PushOnScopeChains(OmpOrigParm, S);
12478 } else {
12479 DRD->addDecl(OmpPrivParm);
12480 DRD->addDecl(OmpOrigParm);
12481 }
Alexey Bataev070f43a2017-09-06 14:49:58 +000012482 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012483}
12484
Alexey Bataev070f43a2017-09-06 14:49:58 +000012485void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
12486 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012487 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12488 DiscardCleanupsInEvaluationContext();
12489 PopExpressionEvaluationContext();
12490
12491 PopDeclContext();
12492 PopFunctionScopeInfo();
12493
Alexey Bataev070f43a2017-09-06 14:49:58 +000012494 if (Initializer != nullptr) {
12495 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
12496 } else if (OmpPrivParm->hasInit()) {
12497 DRD->setInitializer(OmpPrivParm->getInit(),
12498 OmpPrivParm->isDirectInit()
12499 ? OMPDeclareReductionDecl::DirectInit
12500 : OMPDeclareReductionDecl::CopyInit);
12501 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012502 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000012503 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012504}
12505
12506Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
12507 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
12508 for (auto *D : DeclReductions.get()) {
12509 if (IsValid) {
12510 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12511 if (S != nullptr)
12512 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
12513 } else
12514 D->setInvalidDecl();
12515 }
12516 return DeclReductions;
12517}
12518
David Majnemer9d168222016-08-05 17:44:54 +000012519OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000012520 SourceLocation StartLoc,
12521 SourceLocation LParenLoc,
12522 SourceLocation EndLoc) {
12523 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012524 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012525
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012526 // OpenMP [teams Constrcut, Restrictions]
12527 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012528 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
12529 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012530 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012531
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012532 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012533 OpenMPDirectiveKind CaptureRegion =
12534 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
12535 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012536 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012537 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12538 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12539 HelperValStmt = buildPreInits(Context, Captures);
12540 }
12541
12542 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
12543 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000012544}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012545
12546OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12547 SourceLocation StartLoc,
12548 SourceLocation LParenLoc,
12549 SourceLocation EndLoc) {
12550 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012551 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012552
12553 // OpenMP [teams Constrcut, Restrictions]
12554 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012555 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
12556 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012557 return nullptr;
12558
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012559 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012560 OpenMPDirectiveKind CaptureRegion =
12561 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
12562 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012563 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012564 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12565 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12566 HelperValStmt = buildPreInits(Context, Captures);
12567 }
12568
12569 return new (Context) OMPThreadLimitClause(
12570 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012571}
Alexey Bataeva0569352015-12-01 10:17:31 +000012572
12573OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
12574 SourceLocation StartLoc,
12575 SourceLocation LParenLoc,
12576 SourceLocation EndLoc) {
12577 Expr *ValExpr = Priority;
12578
12579 // OpenMP [2.9.1, task Constrcut]
12580 // The priority-value is a non-negative numerical scalar expression.
12581 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
12582 /*StrictlyPositive=*/false))
12583 return nullptr;
12584
12585 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12586}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012587
12588OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
12589 SourceLocation StartLoc,
12590 SourceLocation LParenLoc,
12591 SourceLocation EndLoc) {
12592 Expr *ValExpr = Grainsize;
12593
12594 // OpenMP [2.9.2, taskloop Constrcut]
12595 // The parameter of the grainsize clause must be a positive integer
12596 // expression.
12597 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
12598 /*StrictlyPositive=*/true))
12599 return nullptr;
12600
12601 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12602}
Alexey Bataev382967a2015-12-08 12:06:20 +000012603
12604OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12605 SourceLocation StartLoc,
12606 SourceLocation LParenLoc,
12607 SourceLocation EndLoc) {
12608 Expr *ValExpr = NumTasks;
12609
12610 // OpenMP [2.9.2, taskloop Constrcut]
12611 // The parameter of the num_tasks clause must be a positive integer
12612 // expression.
12613 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
12614 /*StrictlyPositive=*/true))
12615 return nullptr;
12616
12617 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12618}
12619
Alexey Bataev28c75412015-12-15 08:19:24 +000012620OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12621 SourceLocation LParenLoc,
12622 SourceLocation EndLoc) {
12623 // OpenMP [2.13.2, critical construct, Description]
12624 // ... where hint-expression is an integer constant expression that evaluates
12625 // to a valid lock hint.
12626 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12627 if (HintExpr.isInvalid())
12628 return nullptr;
12629 return new (Context)
12630 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12631}
12632
Carlo Bertollib4adf552016-01-15 18:50:31 +000012633OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12634 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12635 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12636 SourceLocation EndLoc) {
12637 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12638 std::string Values;
12639 Values += "'";
12640 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12641 Values += "'";
12642 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12643 << Values << getOpenMPClauseName(OMPC_dist_schedule);
12644 return nullptr;
12645 }
12646 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012647 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012648 if (ChunkSize) {
12649 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12650 !ChunkSize->isInstantiationDependent() &&
12651 !ChunkSize->containsUnexpandedParameterPack()) {
12652 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12653 ExprResult Val =
12654 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12655 if (Val.isInvalid())
12656 return nullptr;
12657
12658 ValExpr = Val.get();
12659
12660 // OpenMP [2.7.1, Restrictions]
12661 // chunk_size must be a loop invariant integer expression with a positive
12662 // value.
12663 llvm::APSInt Result;
12664 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12665 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12666 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12667 << "dist_schedule" << ChunkSize->getSourceRange();
12668 return nullptr;
12669 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012670 } else if (getOpenMPCaptureRegionForClause(
12671 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
12672 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012673 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012674 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000012675 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12676 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12677 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012678 }
12679 }
12680 }
12681
12682 return new (Context)
12683 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000012684 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012685}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012686
12687OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12688 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12689 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12690 SourceLocation KindLoc, SourceLocation EndLoc) {
12691 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000012692 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012693 std::string Value;
12694 SourceLocation Loc;
12695 Value += "'";
12696 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12697 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012698 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012699 Loc = MLoc;
12700 } else {
12701 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012702 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012703 Loc = KindLoc;
12704 }
12705 Value += "'";
12706 Diag(Loc, diag::err_omp_unexpected_clause_value)
12707 << Value << getOpenMPClauseName(OMPC_defaultmap);
12708 return nullptr;
12709 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000012710 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012711
12712 return new (Context)
12713 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12714}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012715
12716bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12717 DeclContext *CurLexicalContext = getCurLexicalContext();
12718 if (!CurLexicalContext->isFileContext() &&
12719 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000012720 !CurLexicalContext->isExternCXXContext() &&
12721 !isa<CXXRecordDecl>(CurLexicalContext) &&
12722 !isa<ClassTemplateDecl>(CurLexicalContext) &&
12723 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12724 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012725 Diag(Loc, diag::err_omp_region_not_file_context);
12726 return false;
12727 }
12728 if (IsInOpenMPDeclareTargetContext) {
12729 Diag(Loc, diag::err_omp_enclosed_declare_target);
12730 return false;
12731 }
12732
12733 IsInOpenMPDeclareTargetContext = true;
12734 return true;
12735}
12736
12737void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12738 assert(IsInOpenMPDeclareTargetContext &&
12739 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12740
12741 IsInOpenMPDeclareTargetContext = false;
12742}
12743
David Majnemer9d168222016-08-05 17:44:54 +000012744void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12745 CXXScopeSpec &ScopeSpec,
12746 const DeclarationNameInfo &Id,
12747 OMPDeclareTargetDeclAttr::MapTypeTy MT,
12748 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012749 LookupResult Lookup(*this, Id, LookupOrdinaryName);
12750 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12751
12752 if (Lookup.isAmbiguous())
12753 return;
12754 Lookup.suppressDiagnostics();
12755
12756 if (!Lookup.isSingleResult()) {
12757 if (TypoCorrection Corrected =
12758 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12759 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12760 CTK_ErrorRecovery)) {
12761 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12762 << Id.getName());
12763 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12764 return;
12765 }
12766
12767 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12768 return;
12769 }
12770
12771 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12772 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12773 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12774 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12775
12776 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12777 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12778 ND->addAttr(A);
12779 if (ASTMutationListener *ML = Context.getASTMutationListener())
12780 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000012781 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012782 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12783 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12784 << Id.getName();
12785 }
12786 } else
12787 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12788}
12789
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012790static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12791 Sema &SemaRef, Decl *D) {
12792 if (!D)
12793 return;
12794 Decl *LD = nullptr;
12795 if (isa<TagDecl>(D)) {
12796 LD = cast<TagDecl>(D)->getDefinition();
12797 } else if (isa<VarDecl>(D)) {
12798 LD = cast<VarDecl>(D)->getDefinition();
12799
12800 // If this is an implicit variable that is legal and we do not need to do
12801 // anything.
12802 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012803 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12804 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12805 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012806 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012807 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012808 return;
12809 }
12810
12811 } else if (isa<FunctionDecl>(D)) {
12812 const FunctionDecl *FD = nullptr;
12813 if (cast<FunctionDecl>(D)->hasBody(FD))
12814 LD = const_cast<FunctionDecl *>(FD);
12815
12816 // If the definition is associated with the current declaration in the
12817 // target region (it can be e.g. a lambda) that is legal and we do not need
12818 // to do anything else.
12819 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012820 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12821 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12822 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012823 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012824 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012825 return;
12826 }
12827 }
12828 if (!LD)
12829 LD = D;
12830 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12831 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12832 // Outlined declaration is not declared target.
12833 if (LD->isOutOfLine()) {
12834 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12835 SemaRef.Diag(SL, diag::note_used_here) << SR;
12836 } else {
12837 DeclContext *DC = LD->getDeclContext();
12838 while (DC) {
12839 if (isa<FunctionDecl>(DC) &&
12840 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12841 break;
12842 DC = DC->getParent();
12843 }
12844 if (DC)
12845 return;
12846
12847 // Is not declared in target context.
12848 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12849 SemaRef.Diag(SL, diag::note_used_here) << SR;
12850 }
12851 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012852 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12853 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12854 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012855 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012856 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012857 }
12858}
12859
12860static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12861 Sema &SemaRef, DSAStackTy *Stack,
12862 ValueDecl *VD) {
12863 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12864 return true;
12865 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
12866 return false;
12867 return true;
12868}
12869
Kelvin Li1ce87c72017-12-12 20:08:12 +000012870void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
12871 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012872 if (!D || D->isInvalidDecl())
12873 return;
12874 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
12875 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
12876 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
12877 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12878 if (DSAStack->isThreadPrivate(VD)) {
12879 Diag(SL, diag::err_omp_threadprivate_in_target);
12880 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
12881 return;
12882 }
12883 }
12884 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
12885 // Problem if any with var declared with incomplete type will be reported
12886 // as normal, so no need to check it here.
12887 if ((E || !VD->getType()->isIncompleteType()) &&
12888 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
12889 // Mark decl as declared target to prevent further diagnostic.
12890 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012891 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12892 Context, OMPDeclareTargetDeclAttr::MT_To);
12893 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012894 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012895 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012896 }
12897 return;
12898 }
12899 }
Kelvin Li1ce87c72017-12-12 20:08:12 +000012900 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12901 if (FD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12902 (FD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
12903 OMPDeclareTargetDeclAttr::MT_Link)) {
12904 assert(IdLoc.isValid() && "Source location is expected");
12905 Diag(IdLoc, diag::err_omp_function_in_link_clause);
12906 Diag(FD->getLocation(), diag::note_defined_here) << FD;
12907 return;
12908 }
12909 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012910 if (!E) {
12911 // Checking declaration inside declare target region.
12912 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
12913 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012914 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12915 Context, OMPDeclareTargetDeclAttr::MT_To);
12916 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012917 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012918 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012919 }
12920 return;
12921 }
12922 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
12923}
Samuel Antao661c0902016-05-26 17:39:58 +000012924
12925OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
12926 SourceLocation StartLoc,
12927 SourceLocation LParenLoc,
12928 SourceLocation EndLoc) {
12929 MappableVarListInfo MVLI(VarList);
12930 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
12931 if (MVLI.ProcessedVarList.empty())
12932 return nullptr;
12933
12934 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12935 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12936 MVLI.VarComponents);
12937}
Samuel Antaoec172c62016-05-26 17:49:04 +000012938
12939OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
12940 SourceLocation StartLoc,
12941 SourceLocation LParenLoc,
12942 SourceLocation EndLoc) {
12943 MappableVarListInfo MVLI(VarList);
12944 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
12945 if (MVLI.ProcessedVarList.empty())
12946 return nullptr;
12947
12948 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12949 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12950 MVLI.VarComponents);
12951}
Carlo Bertolli2404b172016-07-13 15:37:16 +000012952
12953OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
12954 SourceLocation StartLoc,
12955 SourceLocation LParenLoc,
12956 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000012957 MappableVarListInfo MVLI(VarList);
12958 SmallVector<Expr *, 8> PrivateCopies;
12959 SmallVector<Expr *, 8> Inits;
12960
Carlo Bertolli2404b172016-07-13 15:37:16 +000012961 for (auto &RefExpr : VarList) {
12962 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
12963 SourceLocation ELoc;
12964 SourceRange ERange;
12965 Expr *SimpleRefExpr = RefExpr;
12966 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12967 if (Res.second) {
12968 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000012969 MVLI.ProcessedVarList.push_back(RefExpr);
12970 PrivateCopies.push_back(nullptr);
12971 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012972 }
12973 ValueDecl *D = Res.first;
12974 if (!D)
12975 continue;
12976
12977 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000012978 Type = Type.getNonReferenceType().getUnqualifiedType();
12979
12980 auto *VD = dyn_cast<VarDecl>(D);
12981
12982 // Item should be a pointer or reference to pointer.
12983 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000012984 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
12985 << 0 << RefExpr->getSourceRange();
12986 continue;
12987 }
Samuel Antaocc10b852016-07-28 14:23:26 +000012988
12989 // Build the private variable and the expression that refers to it.
12990 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
12991 D->hasAttrs() ? &D->getAttrs() : nullptr);
12992 if (VDPrivate->isInvalidDecl())
12993 continue;
12994
12995 CurContext->addDecl(VDPrivate);
12996 auto VDPrivateRefExpr = buildDeclRefExpr(
12997 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
12998
12999 // Add temporary variable to initialize the private copy of the pointer.
13000 auto *VDInit =
13001 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
13002 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
13003 RefExpr->getExprLoc());
13004 AddInitializerToDecl(VDPrivate,
13005 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000013006 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000013007
13008 // If required, build a capture to implement the privatization initialized
13009 // with the current list item value.
13010 DeclRefExpr *Ref = nullptr;
13011 if (!VD)
13012 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
13013 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
13014 PrivateCopies.push_back(VDPrivateRefExpr);
13015 Inits.push_back(VDInitRefExpr);
13016
13017 // We need to add a data sharing attribute for this variable to make sure it
13018 // is correctly captured. A variable that shows up in a use_device_ptr has
13019 // similar properties of a first private variable.
13020 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
13021
13022 // Create a mappable component for the list item. List items in this clause
13023 // only need a component.
13024 MVLI.VarBaseDeclarations.push_back(D);
13025 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13026 MVLI.VarComponents.back().push_back(
13027 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000013028 }
13029
Samuel Antaocc10b852016-07-28 14:23:26 +000013030 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000013031 return nullptr;
13032
Samuel Antaocc10b852016-07-28 14:23:26 +000013033 return OMPUseDevicePtrClause::Create(
13034 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13035 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000013036}
Carlo Bertolli70594e92016-07-13 17:16:49 +000013037
13038OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
13039 SourceLocation StartLoc,
13040 SourceLocation LParenLoc,
13041 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000013042 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013043 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000013044 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000013045 SourceLocation ELoc;
13046 SourceRange ERange;
13047 Expr *SimpleRefExpr = RefExpr;
13048 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13049 if (Res.second) {
13050 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000013051 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013052 }
13053 ValueDecl *D = Res.first;
13054 if (!D)
13055 continue;
13056
13057 QualType Type = D->getType();
13058 // item should be a pointer or array or reference to pointer or array
13059 if (!Type.getNonReferenceType()->isPointerType() &&
13060 !Type.getNonReferenceType()->isArrayType()) {
13061 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
13062 << 0 << RefExpr->getSourceRange();
13063 continue;
13064 }
Samuel Antao6890b092016-07-28 14:25:09 +000013065
13066 // Check if the declaration in the clause does not show up in any data
13067 // sharing attribute.
13068 auto DVar = DSAStack->getTopDSA(D, false);
13069 if (isOpenMPPrivate(DVar.CKind)) {
13070 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13071 << getOpenMPClauseName(DVar.CKind)
13072 << getOpenMPClauseName(OMPC_is_device_ptr)
13073 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13074 ReportOriginalDSA(*this, DSAStack, D, DVar);
13075 continue;
13076 }
13077
13078 Expr *ConflictExpr;
13079 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000013080 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000013081 [&ConflictExpr](
13082 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
13083 OpenMPClauseKind) -> bool {
13084 ConflictExpr = R.front().getAssociatedExpression();
13085 return true;
13086 })) {
13087 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
13088 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
13089 << ConflictExpr->getSourceRange();
13090 continue;
13091 }
13092
13093 // Store the components in the stack so that they can be used to check
13094 // against other clauses later on.
13095 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
13096 DSAStack->addMappableExpressionComponents(
13097 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
13098
13099 // Record the expression we've just processed.
13100 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
13101
13102 // Create a mappable component for the list item. List items in this clause
13103 // only need a component. We use a null declaration to signal fields in
13104 // 'this'.
13105 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
13106 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
13107 "Unexpected device pointer expression!");
13108 MVLI.VarBaseDeclarations.push_back(
13109 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
13110 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13111 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013112 }
13113
Samuel Antao6890b092016-07-28 14:25:09 +000013114 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000013115 return nullptr;
13116
Samuel Antao6890b092016-07-28 14:25:09 +000013117 return OMPIsDevicePtrClause::Create(
13118 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13119 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013120}