blob: c4aeff6be5f7f8c8caea6227b87f0ae4f6808e26 [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);
Alexey Bataev0c869ef2018-01-16 15:57:07 +00002140 // Mark this captured region as inlined, because we don't use outlined
2141 // function directly.
2142 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2143 AlwaysInlineAttr::CreateImplicit(
2144 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002145 Sema::CapturedParamNameType ParamsTarget[] = {
2146 std::make_pair(StringRef(), QualType()) // __context with shared vars
2147 };
2148 // Start a captured region for 'target' with no implicit parameters.
2149 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2150 ParamsTarget);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002151 QualType KmpInt32PtrTy =
2152 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002153 Sema::CapturedParamNameType ParamsTeamsOrParallel[] = {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002154 std::make_pair(".global_tid.", KmpInt32PtrTy),
2155 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2156 std::make_pair(StringRef(), QualType()) // __context with shared vars
2157 };
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002158 // Start a captured region for 'teams' or 'parallel'. Both regions have
2159 // the same implicit parameters.
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002160 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
Arpith Chacko Jacob99a1e0e2017-01-25 02:18:43 +00002161 ParamsTeamsOrParallel);
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002162 break;
2163 }
Alexey Bataev8451efa2018-01-15 19:06:12 +00002164 case OMPD_target:
2165 case OMPD_target_simd: {
2166 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2167 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2168 FunctionProtoType::ExtProtoInfo EPI;
2169 EPI.Variadic = true;
2170 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2171 Sema::CapturedParamNameType Params[] = {
2172 std::make_pair(".global_tid.", KmpInt32Ty),
2173 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2174 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2175 std::make_pair(".copy_fn.",
2176 Context.getPointerType(CopyFnType).withConst()),
2177 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2178 std::make_pair(StringRef(), QualType()) // __context with shared vars
2179 };
2180 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2181 Params);
2182 // Mark this captured region as inlined, because we don't use outlined
2183 // function directly.
2184 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2185 AlwaysInlineAttr::CreateImplicit(
2186 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2187 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2188 std::make_pair(StringRef(), QualType()));
2189 break;
2190 }
Kelvin Li70a12c52016-07-13 21:51:49 +00002191 case OMPD_simd:
2192 case OMPD_for:
2193 case OMPD_for_simd:
2194 case OMPD_sections:
2195 case OMPD_section:
2196 case OMPD_single:
2197 case OMPD_master:
2198 case OMPD_critical:
Kelvin Lia579b912016-07-14 02:54:56 +00002199 case OMPD_taskgroup:
2200 case OMPD_distribute:
Alexey Bataev46506272017-12-05 17:41:34 +00002201 case OMPD_distribute_simd:
Kelvin Li70a12c52016-07-13 21:51:49 +00002202 case OMPD_ordered:
2203 case OMPD_atomic:
Alexey Bataev8451efa2018-01-15 19:06:12 +00002204 case OMPD_target_data: {
Alexey Bataevdf9b1592014-06-25 04:09:13 +00002205 Sema::CapturedParamNameType Params[] = {
Alexey Bataevf29276e2014-06-18 04:14:57 +00002206 std::make_pair(StringRef(), QualType()) // __context with shared vars
2207 };
Alexey Bataevbae9a792014-06-27 10:37:06 +00002208 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2209 Params);
Alexey Bataevf29276e2014-06-18 04:14:57 +00002210 break;
2211 }
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002212 case OMPD_task: {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002213 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
Alexey Bataev3ae88e22015-05-22 08:56:35 +00002214 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2215 FunctionProtoType::ExtProtoInfo EPI;
2216 EPI.Variadic = true;
2217 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002218 Sema::CapturedParamNameType Params[] = {
Alexey Bataev62b63b12015-03-10 07:28:44 +00002219 std::make_pair(".global_tid.", KmpInt32Ty),
Alexey Bataev48591dd2016-04-20 04:01:36 +00002220 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2221 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2222 std::make_pair(".copy_fn.",
2223 Context.getPointerType(CopyFnType).withConst()),
2224 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002225 std::make_pair(StringRef(), QualType()) // __context with shared vars
2226 };
2227 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2228 Params);
Alexey Bataev62b63b12015-03-10 07:28:44 +00002229 // Mark this captured region as inlined, because we don't use outlined
2230 // function directly.
2231 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2232 AlwaysInlineAttr::CreateImplicit(
2233 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00002234 break;
2235 }
Alexey Bataev1e73ef32016-04-28 12:14:51 +00002236 case OMPD_taskloop:
2237 case OMPD_taskloop_simd: {
Alexey Bataev7292c292016-04-25 12:22:29 +00002238 QualType KmpInt32Ty =
2239 Context.getIntTypeForBitwidth(/*DestWidth=*/32, /*Signed=*/1);
2240 QualType KmpUInt64Ty =
2241 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
2242 QualType KmpInt64Ty =
2243 Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
2244 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2245 FunctionProtoType::ExtProtoInfo EPI;
2246 EPI.Variadic = true;
2247 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
Alexey Bataev49f6e782015-12-01 04:18:41 +00002248 Sema::CapturedParamNameType Params[] = {
Alexey Bataev7292c292016-04-25 12:22:29 +00002249 std::make_pair(".global_tid.", KmpInt32Ty),
2250 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2251 std::make_pair(".privates.",
2252 Context.VoidPtrTy.withConst().withRestrict()),
2253 std::make_pair(
2254 ".copy_fn.",
2255 Context.getPointerType(CopyFnType).withConst().withRestrict()),
2256 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2257 std::make_pair(".lb.", KmpUInt64Ty),
2258 std::make_pair(".ub.", KmpUInt64Ty), std::make_pair(".st.", KmpInt64Ty),
2259 std::make_pair(".liter.", KmpInt32Ty),
Alexey Bataevbe5a8b42017-07-17 13:30:36 +00002260 std::make_pair(".reductions.",
2261 Context.VoidPtrTy.withConst().withRestrict()),
Alexey Bataev49f6e782015-12-01 04:18:41 +00002262 std::make_pair(StringRef(), QualType()) // __context with shared vars
2263 };
2264 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2265 Params);
Alexey Bataev7292c292016-04-25 12:22:29 +00002266 // Mark this captured region as inlined, because we don't use outlined
2267 // function directly.
2268 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2269 AlwaysInlineAttr::CreateImplicit(
2270 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
Alexey Bataev49f6e782015-12-01 04:18:41 +00002271 break;
2272 }
Kelvin Li4a39add2016-07-05 05:00:15 +00002273 case OMPD_distribute_parallel_for_simd:
Alexey Bataev647dd842018-01-15 20:59:40 +00002274 case OMPD_distribute_parallel_for: {
Carlo Bertolli9925f152016-06-27 14:55:37 +00002275 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2276 QualType KmpInt32PtrTy =
2277 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2278 Sema::CapturedParamNameType Params[] = {
2279 std::make_pair(".global_tid.", KmpInt32PtrTy),
2280 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2281 std::make_pair(".previous.lb.", Context.getSizeType()),
2282 std::make_pair(".previous.ub.", Context.getSizeType()),
2283 std::make_pair(StringRef(), QualType()) // __context with shared vars
2284 };
2285 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2286 Params);
2287 break;
2288 }
Alexey Bataev647dd842018-01-15 20:59:40 +00002289 case OMPD_target_teams_distribute_parallel_for:
2290 case OMPD_target_teams_distribute_parallel_for_simd: {
Carlo Bertolli52978c32018-01-03 21:12:44 +00002291 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2292 QualType KmpInt32PtrTy =
2293 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2294
Alexey Bataev8451efa2018-01-15 19:06:12 +00002295 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2296 FunctionProtoType::ExtProtoInfo EPI;
2297 EPI.Variadic = true;
2298 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2299 Sema::CapturedParamNameType Params[] = {
2300 std::make_pair(".global_tid.", KmpInt32Ty),
2301 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2302 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2303 std::make_pair(".copy_fn.",
2304 Context.getPointerType(CopyFnType).withConst()),
2305 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2306 std::make_pair(StringRef(), QualType()) // __context with shared vars
2307 };
2308 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2309 Params);
Carlo Bertolli52978c32018-01-03 21:12:44 +00002310 Sema::CapturedParamNameType ParamsTarget[] = {
2311 std::make_pair(StringRef(), QualType()) // __context with shared vars
2312 };
2313 // Start a captured region for 'target' with no implicit parameters.
2314 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2315 ParamsTarget);
2316
2317 Sema::CapturedParamNameType ParamsTeams[] = {
2318 std::make_pair(".global_tid.", KmpInt32PtrTy),
2319 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2320 std::make_pair(StringRef(), QualType()) // __context with shared vars
2321 };
2322 // Start a captured region for 'target' with no implicit parameters.
2323 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2324 ParamsTeams);
2325
2326 Sema::CapturedParamNameType ParamsParallel[] = {
2327 std::make_pair(".global_tid.", KmpInt32PtrTy),
2328 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2329 std::make_pair(".previous.lb.", Context.getSizeType()),
2330 std::make_pair(".previous.ub.", Context.getSizeType()),
2331 std::make_pair(StringRef(), QualType()) // __context with shared vars
2332 };
2333 // Start a captured region for 'teams' or 'parallel'. Both regions have
2334 // the same implicit parameters.
2335 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2336 ParamsParallel);
2337 break;
2338 }
2339
Alexey Bataev46506272017-12-05 17:41:34 +00002340 case OMPD_teams_distribute_parallel_for:
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00002341 case OMPD_teams_distribute_parallel_for_simd: {
Carlo Bertolli62fae152017-11-20 20:46:39 +00002342 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2343 QualType KmpInt32PtrTy =
2344 Context.getPointerType(KmpInt32Ty).withConst().withRestrict();
2345
2346 Sema::CapturedParamNameType ParamsTeams[] = {
2347 std::make_pair(".global_tid.", KmpInt32PtrTy),
2348 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2349 std::make_pair(StringRef(), QualType()) // __context with shared vars
2350 };
2351 // Start a captured region for 'target' with no implicit parameters.
2352 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2353 ParamsTeams);
2354
2355 Sema::CapturedParamNameType ParamsParallel[] = {
2356 std::make_pair(".global_tid.", KmpInt32PtrTy),
2357 std::make_pair(".bound_tid.", KmpInt32PtrTy),
2358 std::make_pair(".previous.lb.", Context.getSizeType()),
2359 std::make_pair(".previous.ub.", Context.getSizeType()),
2360 std::make_pair(StringRef(), QualType()) // __context with shared vars
2361 };
2362 // Start a captured region for 'teams' or 'parallel'. Both regions have
2363 // the same implicit parameters.
2364 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2365 ParamsParallel);
2366 break;
2367 }
Alexey Bataev7828b252017-11-21 17:08:48 +00002368 case OMPD_target_update:
2369 case OMPD_target_enter_data:
2370 case OMPD_target_exit_data: {
2371 QualType KmpInt32Ty = Context.getIntTypeForBitwidth(32, 1);
2372 QualType Args[] = {Context.VoidPtrTy.withConst().withRestrict()};
2373 FunctionProtoType::ExtProtoInfo EPI;
2374 EPI.Variadic = true;
2375 QualType CopyFnType = Context.getFunctionType(Context.VoidTy, Args, EPI);
2376 Sema::CapturedParamNameType Params[] = {
2377 std::make_pair(".global_tid.", KmpInt32Ty),
2378 std::make_pair(".part_id.", Context.getPointerType(KmpInt32Ty)),
2379 std::make_pair(".privates.", Context.VoidPtrTy.withConst()),
2380 std::make_pair(".copy_fn.",
2381 Context.getPointerType(CopyFnType).withConst()),
2382 std::make_pair(".task_t.", Context.VoidPtrTy.withConst()),
2383 std::make_pair(StringRef(), QualType()) // __context with shared vars
2384 };
2385 ActOnCapturedRegionStart(DSAStack->getConstructLoc(), CurScope, CR_OpenMP,
2386 Params);
2387 // Mark this captured region as inlined, because we don't use outlined
2388 // function directly.
2389 getCurCapturedRegion()->TheCapturedDecl->addAttr(
2390 AlwaysInlineAttr::CreateImplicit(
2391 Context, AlwaysInlineAttr::Keyword_forceinline, SourceRange()));
2392 break;
2393 }
Alexey Bataev9959db52014-05-06 10:08:46 +00002394 case OMPD_threadprivate:
Alexey Bataevee9af452014-11-21 11:33:46 +00002395 case OMPD_taskyield:
2396 case OMPD_barrier:
2397 case OMPD_taskwait:
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002398 case OMPD_cancellation_point:
Alexey Bataev80909872015-07-02 11:25:17 +00002399 case OMPD_cancel:
Alexey Bataevee9af452014-11-21 11:33:46 +00002400 case OMPD_flush:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00002401 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00002402 case OMPD_declare_simd:
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00002403 case OMPD_declare_target:
2404 case OMPD_end_declare_target:
Alexey Bataev9959db52014-05-06 10:08:46 +00002405 llvm_unreachable("OpenMP Directive is not allowed");
2406 case OMPD_unknown:
Alexey Bataev9959db52014-05-06 10:08:46 +00002407 llvm_unreachable("Unknown OpenMP directive");
2408 }
2409}
2410
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002411int Sema::getOpenMPCaptureLevels(OpenMPDirectiveKind DKind) {
2412 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2413 getOpenMPCaptureRegions(CaptureRegions, DKind);
2414 return CaptureRegions.size();
2415}
2416
Alexey Bataev3392d762016-02-16 11:18:12 +00002417static OMPCapturedExprDecl *buildCaptureDecl(Sema &S, IdentifierInfo *Id,
Alexey Bataev5a3af132016-03-29 08:58:54 +00002418 Expr *CaptureExpr, bool WithInit,
2419 bool AsExpression) {
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002420 assert(CaptureExpr);
Alexey Bataev4244be22016-02-11 05:35:55 +00002421 ASTContext &C = S.getASTContext();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002422 Expr *Init = AsExpression ? CaptureExpr : CaptureExpr->IgnoreImpCasts();
Alexey Bataev4244be22016-02-11 05:35:55 +00002423 QualType Ty = Init->getType();
2424 if (CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002425 if (S.getLangOpts().CPlusPlus) {
Alexey Bataev4244be22016-02-11 05:35:55 +00002426 Ty = C.getLValueReferenceType(Ty);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002427 } else {
Alexey Bataev4244be22016-02-11 05:35:55 +00002428 Ty = C.getPointerType(Ty);
2429 ExprResult Res =
2430 S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_AddrOf, Init);
2431 if (!Res.isUsable())
2432 return nullptr;
2433 Init = Res.get();
2434 }
Alexey Bataev61205072016-03-02 04:57:40 +00002435 WithInit = true;
Alexey Bataev4244be22016-02-11 05:35:55 +00002436 }
Alexey Bataeva7206b92016-12-20 16:51:02 +00002437 auto *CED = OMPCapturedExprDecl::Create(C, S.CurContext, Id, Ty,
2438 CaptureExpr->getLocStart());
Alexey Bataev2bbf7212016-03-03 03:52:24 +00002439 if (!WithInit)
2440 CED->addAttr(OMPCaptureNoInitAttr::CreateImplicit(C, SourceRange()));
Alexey Bataev4244be22016-02-11 05:35:55 +00002441 S.CurContext->addHiddenDecl(CED);
Richard Smith3beb7c62017-01-12 02:27:38 +00002442 S.AddInitializerToDecl(CED, Init, /*DirectInit=*/false);
Alexey Bataev3392d762016-02-16 11:18:12 +00002443 return CED;
2444}
2445
Alexey Bataev61205072016-03-02 04:57:40 +00002446static DeclRefExpr *buildCapture(Sema &S, ValueDecl *D, Expr *CaptureExpr,
2447 bool WithInit) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002448 OMPCapturedExprDecl *CD;
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002449 if (auto *VD = S.IsOpenMPCapturedDecl(D)) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00002450 CD = cast<OMPCapturedExprDecl>(VD);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002451 } else {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002452 CD = buildCaptureDecl(S, D->getIdentifier(), CaptureExpr, WithInit,
2453 /*AsExpression=*/false);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002454 }
Alexey Bataev3392d762016-02-16 11:18:12 +00002455 return buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
Alexey Bataev1efd1662016-03-29 10:59:56 +00002456 CaptureExpr->getExprLoc());
Alexey Bataev3392d762016-02-16 11:18:12 +00002457}
2458
Alexey Bataev5a3af132016-03-29 08:58:54 +00002459static ExprResult buildCapture(Sema &S, Expr *CaptureExpr, DeclRefExpr *&Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002460 CaptureExpr = S.DefaultLvalueConversion(CaptureExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00002461 if (!Ref) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002462 OMPCapturedExprDecl *CD = buildCaptureDecl(
2463 S, &S.getASTContext().Idents.get(".capture_expr."), CaptureExpr,
2464 /*WithInit=*/true, /*AsExpression=*/true);
Alexey Bataev5a3af132016-03-29 08:58:54 +00002465 Ref = buildDeclRefExpr(S, CD, CD->getType().getNonReferenceType(),
2466 CaptureExpr->getExprLoc());
2467 }
2468 ExprResult Res = Ref;
2469 if (!S.getLangOpts().CPlusPlus &&
2470 CaptureExpr->getObjectKind() == OK_Ordinary && CaptureExpr->isGLValue() &&
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002471 Ref->getType()->isPointerType()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00002472 Res = S.CreateBuiltinUnaryOp(CaptureExpr->getExprLoc(), UO_Deref, Ref);
Alexey Bataev8e769ee2017-12-22 21:01:52 +00002473 if (!Res.isUsable())
2474 return ExprError();
2475 }
2476 return S.DefaultLvalueConversion(Res.get());
Alexey Bataev4244be22016-02-11 05:35:55 +00002477}
2478
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002479namespace {
2480// OpenMP directives parsed in this section are represented as a
2481// CapturedStatement with an associated statement. If a syntax error
2482// is detected during the parsing of the associated statement, the
2483// compiler must abort processing and close the CapturedStatement.
2484//
2485// Combined directives such as 'target parallel' have more than one
2486// nested CapturedStatements. This RAII ensures that we unwind out
2487// of all the nested CapturedStatements when an error is found.
2488class CaptureRegionUnwinderRAII {
2489private:
2490 Sema &S;
2491 bool &ErrorFound;
2492 OpenMPDirectiveKind DKind;
2493
2494public:
2495 CaptureRegionUnwinderRAII(Sema &S, bool &ErrorFound,
2496 OpenMPDirectiveKind DKind)
2497 : S(S), ErrorFound(ErrorFound), DKind(DKind) {}
2498 ~CaptureRegionUnwinderRAII() {
2499 if (ErrorFound) {
2500 int ThisCaptureLevel = S.getOpenMPCaptureLevels(DKind);
2501 while (--ThisCaptureLevel >= 0)
2502 S.ActOnCapturedRegionError();
2503 }
2504 }
2505};
2506} // namespace
2507
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002508StmtResult Sema::ActOnOpenMPRegionEnd(StmtResult S,
2509 ArrayRef<OMPClause *> Clauses) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002510 bool ErrorFound = false;
2511 CaptureRegionUnwinderRAII CaptureRegionUnwinder(
2512 *this, ErrorFound, DSAStack->getCurrentDirective());
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002513 if (!S.isUsable()) {
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002514 ErrorFound = true;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002515 return StmtError();
2516 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002517
Alexey Bataev2ba67042017-11-28 21:11:44 +00002518 SmallVector<OpenMPDirectiveKind, 4> CaptureRegions;
2519 getOpenMPCaptureRegions(CaptureRegions, DSAStack->getCurrentDirective());
Alexey Bataev993d2802015-12-28 06:23:08 +00002520 OMPOrderedClause *OC = nullptr;
Alexey Bataev6402bca2015-12-28 07:25:51 +00002521 OMPScheduleClause *SC = nullptr;
Alexey Bataev993d2802015-12-28 06:23:08 +00002522 SmallVector<OMPLinearClause *, 4> LCs;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002523 SmallVector<OMPClauseWithPreInit *, 8> PICs;
Alexey Bataev040d5402015-05-12 08:35:28 +00002524 // This is required for proper codegen.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002525 for (auto *Clause : Clauses) {
Alexey Bataev88202be2017-07-27 13:20:36 +00002526 if (isOpenMPTaskingDirective(DSAStack->getCurrentDirective()) &&
2527 Clause->getClauseKind() == OMPC_in_reduction) {
2528 // Capture taskgroup task_reduction descriptors inside the tasking regions
2529 // with the corresponding in_reduction items.
2530 auto *IRC = cast<OMPInReductionClause>(Clause);
2531 for (auto *E : IRC->taskgroup_descriptors())
2532 if (E)
2533 MarkDeclarationsReferencedInExpr(E);
2534 }
Alexey Bataev16dc7b62015-05-20 03:46:04 +00002535 if (isOpenMPPrivate(Clause->getClauseKind()) ||
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002536 Clause->getClauseKind() == OMPC_copyprivate ||
2537 (getLangOpts().OpenMPUseTLS &&
2538 getASTContext().getTargetInfo().isTLSSupported() &&
2539 Clause->getClauseKind() == OMPC_copyin)) {
2540 DSAStack->setForceVarCapturing(Clause->getClauseKind() == OMPC_copyin);
Alexey Bataev040d5402015-05-12 08:35:28 +00002541 // Mark all variables in private list clauses as used in inner region.
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002542 for (auto *VarRef : Clause->children()) {
2543 if (auto *E = cast_or_null<Expr>(VarRef)) {
Alexey Bataev8bf6b3e2015-04-02 13:07:08 +00002544 MarkDeclarationsReferencedInExpr(E);
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002545 }
2546 }
Samuel Antao9c75cfe2015-07-27 16:38:06 +00002547 DSAStack->setForceVarCapturing(/*V=*/false);
Alexey Bataev2ba67042017-11-28 21:11:44 +00002548 } else if (CaptureRegions.size() > 1 ||
2549 CaptureRegions.back() != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002550 if (auto *C = OMPClauseWithPreInit::get(Clause))
2551 PICs.push_back(C);
Alexey Bataev005248a2016-02-25 05:25:57 +00002552 if (auto *C = OMPClauseWithPostUpdate::get(Clause)) {
2553 if (auto *E = C->getPostUpdateExpr())
2554 MarkDeclarationsReferencedInExpr(E);
2555 }
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002556 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002557 if (Clause->getClauseKind() == OMPC_schedule)
2558 SC = cast<OMPScheduleClause>(Clause);
2559 else if (Clause->getClauseKind() == OMPC_ordered)
Alexey Bataev993d2802015-12-28 06:23:08 +00002560 OC = cast<OMPOrderedClause>(Clause);
2561 else if (Clause->getClauseKind() == OMPC_linear)
2562 LCs.push_back(cast<OMPLinearClause>(Clause));
2563 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002564 // OpenMP, 2.7.1 Loop Construct, Restrictions
2565 // The nonmonotonic modifier cannot be specified if an ordered clause is
2566 // specified.
2567 if (SC &&
2568 (SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
2569 SC->getSecondScheduleModifier() ==
2570 OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
2571 OC) {
2572 Diag(SC->getFirstScheduleModifier() == OMPC_SCHEDULE_MODIFIER_nonmonotonic
2573 ? SC->getFirstScheduleModifierLoc()
2574 : SC->getSecondScheduleModifierLoc(),
2575 diag::err_omp_schedule_nonmonotonic_ordered)
2576 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2577 ErrorFound = true;
2578 }
Alexey Bataev993d2802015-12-28 06:23:08 +00002579 if (!LCs.empty() && OC && OC->getNumForLoops()) {
2580 for (auto *C : LCs) {
2581 Diag(C->getLocStart(), diag::err_omp_linear_ordered)
2582 << SourceRange(OC->getLocStart(), OC->getLocEnd());
2583 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002584 ErrorFound = true;
2585 }
Alexey Bataev113438c2015-12-30 12:06:23 +00002586 if (isOpenMPWorksharingDirective(DSAStack->getCurrentDirective()) &&
2587 isOpenMPSimdDirective(DSAStack->getCurrentDirective()) && OC &&
2588 OC->getNumForLoops()) {
2589 Diag(OC->getLocStart(), diag::err_omp_ordered_simd)
2590 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
2591 ErrorFound = true;
2592 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00002593 if (ErrorFound) {
Alexey Bataev993d2802015-12-28 06:23:08 +00002594 return StmtError();
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002595 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002596 StmtResult SR = S;
Alexey Bataev2ba67042017-11-28 21:11:44 +00002597 for (OpenMPDirectiveKind ThisCaptureRegion : llvm::reverse(CaptureRegions)) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002598 // Mark all variables in private list clauses as used in inner region.
2599 // Required for proper codegen of combined directives.
2600 // TODO: add processing for other clauses.
Alexey Bataev2ba67042017-11-28 21:11:44 +00002601 if (ThisCaptureRegion != OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002602 for (auto *C : PICs) {
2603 OpenMPDirectiveKind CaptureRegion = C->getCaptureRegion();
2604 // Find the particular capture region for the clause if the
2605 // directive is a combined one with multiple capture regions.
2606 // If the directive is not a combined one, the capture region
2607 // associated with the clause is OMPD_unknown and is generated
2608 // only once.
2609 if (CaptureRegion == ThisCaptureRegion ||
2610 CaptureRegion == OMPD_unknown) {
2611 if (auto *DS = cast_or_null<DeclStmt>(C->getPreInitStmt())) {
2612 for (auto *D : DS->decls())
2613 MarkVariableReferenced(D->getLocation(), cast<VarDecl>(D));
2614 }
2615 }
2616 }
2617 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002618 SR = ActOnCapturedRegionEnd(SR.get());
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00002619 }
Arpith Chacko Jacob19b911c2017-01-18 18:18:53 +00002620 return SR;
Alexey Bataeva8d4a5432015-04-02 07:48:16 +00002621}
2622
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002623static bool checkCancelRegion(Sema &SemaRef, OpenMPDirectiveKind CurrentRegion,
2624 OpenMPDirectiveKind CancelRegion,
2625 SourceLocation StartLoc) {
2626 // CancelRegion is only needed for cancel and cancellation_point.
2627 if (CurrentRegion != OMPD_cancel && CurrentRegion != OMPD_cancellation_point)
2628 return false;
2629
2630 if (CancelRegion == OMPD_parallel || CancelRegion == OMPD_for ||
2631 CancelRegion == OMPD_sections || CancelRegion == OMPD_taskgroup)
2632 return false;
2633
2634 SemaRef.Diag(StartLoc, diag::err_omp_wrong_cancel_region)
2635 << getOpenMPDirectiveName(CancelRegion);
2636 return true;
2637}
2638
2639static bool checkNestingOfRegions(Sema &SemaRef, DSAStackTy *Stack,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002640 OpenMPDirectiveKind CurrentRegion,
2641 const DeclarationNameInfo &CurrentName,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002642 OpenMPDirectiveKind CancelRegion,
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002643 SourceLocation StartLoc) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002644 if (Stack->getCurScope()) {
2645 auto ParentRegion = Stack->getParentDirective();
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002646 auto OffendingRegion = ParentRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002647 bool NestingProhibited = false;
2648 bool CloseNesting = true;
David Majnemer9d168222016-08-05 17:44:54 +00002649 bool OrphanSeen = false;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002650 enum {
2651 NoRecommend,
2652 ShouldBeInParallelRegion,
Alexey Bataev13314bf2014-10-09 04:18:56 +00002653 ShouldBeInOrderedRegion,
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002654 ShouldBeInTargetRegion,
2655 ShouldBeInTeamsRegion
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002656 } Recommend = NoRecommend;
Kelvin Lifd8b5742016-07-01 14:30:25 +00002657 if (isOpenMPSimdDirective(ParentRegion) && CurrentRegion != OMPD_ordered) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002658 // OpenMP [2.16, Nesting of Regions]
2659 // OpenMP constructs may not be nested inside a simd region.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002660 // OpenMP [2.8.1,simd Construct, Restrictions]
Kelvin Lifd8b5742016-07-01 14:30:25 +00002661 // An ordered construct with the simd clause is the only OpenMP
2662 // construct that can appear in the simd region.
David Majnemer9d168222016-08-05 17:44:54 +00002663 // Allowing a SIMD construct nested in another SIMD construct is an
Kelvin Lifd8b5742016-07-01 14:30:25 +00002664 // extension. The OpenMP 4.5 spec does not allow it. Issue a warning
2665 // message.
2666 SemaRef.Diag(StartLoc, (CurrentRegion != OMPD_simd)
2667 ? diag::err_omp_prohibited_region_simd
2668 : diag::warn_omp_nesting_simd);
2669 return CurrentRegion != OMPD_simd;
Alexey Bataev549210e2014-06-24 04:39:47 +00002670 }
Alexey Bataev0162e452014-07-22 10:10:35 +00002671 if (ParentRegion == OMPD_atomic) {
2672 // OpenMP [2.16, Nesting of Regions]
2673 // OpenMP constructs may not be nested inside an atomic region.
2674 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region_atomic);
2675 return true;
2676 }
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002677 if (CurrentRegion == OMPD_section) {
2678 // OpenMP [2.7.2, sections Construct, Restrictions]
2679 // Orphaned section directives are prohibited. That is, the section
2680 // directives must appear within the sections construct and must not be
2681 // encountered elsewhere in the sections region.
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00002682 if (ParentRegion != OMPD_sections &&
2683 ParentRegion != OMPD_parallel_sections) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00002684 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_section_directive)
2685 << (ParentRegion != OMPD_unknown)
2686 << getOpenMPDirectiveName(ParentRegion);
2687 return true;
2688 }
2689 return false;
2690 }
Kelvin Li2b51f722016-07-26 04:32:50 +00002691 // Allow some constructs (except teams) to be orphaned (they could be
David Majnemer9d168222016-08-05 17:44:54 +00002692 // used in functions, called from OpenMP regions with the required
Kelvin Li2b51f722016-07-26 04:32:50 +00002693 // preconditions).
Kelvin Libf594a52016-12-17 05:48:59 +00002694 if (ParentRegion == OMPD_unknown &&
2695 !isOpenMPNestingTeamsDirective(CurrentRegion))
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002696 return false;
Alexey Bataev80909872015-07-02 11:25:17 +00002697 if (CurrentRegion == OMPD_cancellation_point ||
2698 CurrentRegion == OMPD_cancel) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002699 // OpenMP [2.16, Nesting of Regions]
2700 // A cancellation point construct for which construct-type-clause is
2701 // taskgroup must be nested inside a task construct. A cancellation
2702 // point construct for which construct-type-clause is not taskgroup must
2703 // be closely nested inside an OpenMP construct that matches the type
2704 // specified in construct-type-clause.
Alexey Bataev80909872015-07-02 11:25:17 +00002705 // A cancel construct for which construct-type-clause is taskgroup must be
2706 // nested inside a task construct. A cancel construct for which
2707 // construct-type-clause is not taskgroup must be closely nested inside an
2708 // OpenMP construct that matches the type specified in
2709 // construct-type-clause.
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002710 NestingProhibited =
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00002711 !((CancelRegion == OMPD_parallel &&
2712 (ParentRegion == OMPD_parallel ||
2713 ParentRegion == OMPD_target_parallel)) ||
Alexey Bataev25e5b442015-09-15 12:52:43 +00002714 (CancelRegion == OMPD_for &&
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00002715 (ParentRegion == OMPD_for || ParentRegion == OMPD_parallel_for ||
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00002716 ParentRegion == OMPD_target_parallel_for ||
2717 ParentRegion == OMPD_distribute_parallel_for ||
Alexey Bataev16e79882017-11-22 21:12:03 +00002718 ParentRegion == OMPD_teams_distribute_parallel_for ||
2719 ParentRegion == OMPD_target_teams_distribute_parallel_for)) ||
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002720 (CancelRegion == OMPD_taskgroup && ParentRegion == OMPD_task) ||
2721 (CancelRegion == OMPD_sections &&
Alexey Bataev25e5b442015-09-15 12:52:43 +00002722 (ParentRegion == OMPD_section || ParentRegion == OMPD_sections ||
2723 ParentRegion == OMPD_parallel_sections)));
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002724 } else if (CurrentRegion == OMPD_master) {
Alexander Musman80c22892014-07-17 08:54:58 +00002725 // OpenMP [2.16, Nesting of Regions]
2726 // A master region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002727 // atomic, or explicit task region.
Alexander Musman80c22892014-07-17 08:54:58 +00002728 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002729 isOpenMPTaskingDirective(ParentRegion);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002730 } else if (CurrentRegion == OMPD_critical && CurrentName.getName()) {
2731 // OpenMP [2.16, Nesting of Regions]
2732 // A critical region may not be nested (closely or otherwise) inside a
2733 // critical region with the same name. Note that this restriction is not
2734 // sufficient to prevent deadlock.
2735 SourceLocation PreviousCriticalLoc;
David Majnemer9d168222016-08-05 17:44:54 +00002736 bool DeadLock = Stack->hasDirective(
2737 [CurrentName, &PreviousCriticalLoc](OpenMPDirectiveKind K,
2738 const DeclarationNameInfo &DNI,
2739 SourceLocation Loc) -> bool {
2740 if (K == OMPD_critical && DNI.getName() == CurrentName.getName()) {
2741 PreviousCriticalLoc = Loc;
2742 return true;
2743 } else
2744 return false;
2745 },
2746 false /* skip top directive */);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00002747 if (DeadLock) {
2748 SemaRef.Diag(StartLoc,
2749 diag::err_omp_prohibited_region_critical_same_name)
2750 << CurrentName.getName();
2751 if (PreviousCriticalLoc.isValid())
2752 SemaRef.Diag(PreviousCriticalLoc,
2753 diag::note_omp_previous_critical_region);
2754 return true;
2755 }
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00002756 } else if (CurrentRegion == OMPD_barrier) {
2757 // OpenMP [2.16, Nesting of Regions]
2758 // A barrier region may not be closely nested inside a worksharing,
Alexey Bataev0162e452014-07-22 10:10:35 +00002759 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002760 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2761 isOpenMPTaskingDirective(ParentRegion) ||
2762 ParentRegion == OMPD_master ||
2763 ParentRegion == OMPD_critical ||
2764 ParentRegion == OMPD_ordered;
Alexander Musman80c22892014-07-17 08:54:58 +00002765 } else if (isOpenMPWorksharingDirective(CurrentRegion) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00002766 !isOpenMPParallelDirective(CurrentRegion) &&
2767 !isOpenMPTeamsDirective(CurrentRegion)) {
Alexey Bataev549210e2014-06-24 04:39:47 +00002768 // OpenMP [2.16, Nesting of Regions]
2769 // A worksharing region may not be closely nested inside a worksharing,
2770 // explicit task, critical, ordered, atomic, or master region.
Alexey Bataev35aaee62016-04-13 13:36:48 +00002771 NestingProhibited = isOpenMPWorksharingDirective(ParentRegion) ||
2772 isOpenMPTaskingDirective(ParentRegion) ||
2773 ParentRegion == OMPD_master ||
2774 ParentRegion == OMPD_critical ||
2775 ParentRegion == OMPD_ordered;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002776 Recommend = ShouldBeInParallelRegion;
2777 } else if (CurrentRegion == OMPD_ordered) {
2778 // OpenMP [2.16, Nesting of Regions]
2779 // An ordered region may not be closely nested inside a critical,
Alexey Bataev0162e452014-07-22 10:10:35 +00002780 // atomic, or explicit task region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002781 // An ordered region must be closely nested inside a loop region (or
2782 // parallel loop region) with an ordered clause.
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002783 // OpenMP [2.8.1,simd Construct, Restrictions]
2784 // An ordered construct with the simd clause is the only OpenMP construct
2785 // that can appear in the simd region.
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002786 NestingProhibited = ParentRegion == OMPD_critical ||
Alexey Bataev35aaee62016-04-13 13:36:48 +00002787 isOpenMPTaskingDirective(ParentRegion) ||
Alexey Bataevd14d1e62015-09-28 06:39:35 +00002788 !(isOpenMPSimdDirective(ParentRegion) ||
2789 Stack->isParentOrderedRegion());
Alexey Bataev9fb6e642014-07-22 06:45:04 +00002790 Recommend = ShouldBeInOrderedRegion;
Kelvin Libf594a52016-12-17 05:48:59 +00002791 } else if (isOpenMPNestingTeamsDirective(CurrentRegion)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002792 // OpenMP [2.16, Nesting of Regions]
2793 // If specified, a teams construct must be contained within a target
2794 // construct.
2795 NestingProhibited = ParentRegion != OMPD_target;
Kelvin Li2b51f722016-07-26 04:32:50 +00002796 OrphanSeen = ParentRegion == OMPD_unknown;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002797 Recommend = ShouldBeInTargetRegion;
Alexey Bataev13314bf2014-10-09 04:18:56 +00002798 }
Kelvin Libf594a52016-12-17 05:48:59 +00002799 if (!NestingProhibited &&
2800 !isOpenMPTargetExecutionDirective(CurrentRegion) &&
2801 !isOpenMPTargetDataManagementDirective(CurrentRegion) &&
2802 (ParentRegion == OMPD_teams || ParentRegion == OMPD_target_teams)) {
Alexey Bataev13314bf2014-10-09 04:18:56 +00002803 // OpenMP [2.16, Nesting of Regions]
2804 // distribute, parallel, parallel sections, parallel workshare, and the
2805 // parallel loop and parallel loop SIMD constructs are the only OpenMP
2806 // constructs that can be closely nested in the teams region.
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002807 NestingProhibited = !isOpenMPParallelDirective(CurrentRegion) &&
2808 !isOpenMPDistributeDirective(CurrentRegion);
Alexey Bataev13314bf2014-10-09 04:18:56 +00002809 Recommend = ShouldBeInParallelRegion;
Alexey Bataev549210e2014-06-24 04:39:47 +00002810 }
David Majnemer9d168222016-08-05 17:44:54 +00002811 if (!NestingProhibited &&
Kelvin Li02532872016-08-05 14:37:37 +00002812 isOpenMPNestingDistributeDirective(CurrentRegion)) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002813 // OpenMP 4.5 [2.17 Nesting of Regions]
2814 // The region associated with the distribute construct must be strictly
2815 // nested inside a teams region
Kelvin Libf594a52016-12-17 05:48:59 +00002816 NestingProhibited =
2817 (ParentRegion != OMPD_teams && ParentRegion != OMPD_target_teams);
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00002818 Recommend = ShouldBeInTeamsRegion;
2819 }
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002820 if (!NestingProhibited &&
2821 (isOpenMPTargetExecutionDirective(CurrentRegion) ||
2822 isOpenMPTargetDataManagementDirective(CurrentRegion))) {
2823 // OpenMP 4.5 [2.17 Nesting of Regions]
2824 // If a target, target update, target data, target enter data, or
2825 // target exit data construct is encountered during execution of a
2826 // target region, the behavior is unspecified.
2827 NestingProhibited = Stack->hasDirective(
Alexey Bataev7ace49d2016-05-17 08:55:33 +00002828 [&OffendingRegion](OpenMPDirectiveKind K, const DeclarationNameInfo &,
2829 SourceLocation) -> bool {
Arpith Chacko Jacob3d58f262016-02-02 04:00:47 +00002830 if (isOpenMPTargetExecutionDirective(K)) {
2831 OffendingRegion = K;
2832 return true;
2833 } else
2834 return false;
2835 },
2836 false /* don't skip top directive */);
2837 CloseNesting = false;
2838 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002839 if (NestingProhibited) {
Kelvin Li2b51f722016-07-26 04:32:50 +00002840 if (OrphanSeen) {
2841 SemaRef.Diag(StartLoc, diag::err_omp_orphaned_device_directive)
2842 << getOpenMPDirectiveName(CurrentRegion) << Recommend;
2843 } else {
2844 SemaRef.Diag(StartLoc, diag::err_omp_prohibited_region)
2845 << CloseNesting << getOpenMPDirectiveName(OffendingRegion)
2846 << Recommend << getOpenMPDirectiveName(CurrentRegion);
2847 }
Alexey Bataev549210e2014-06-24 04:39:47 +00002848 return true;
2849 }
2850 }
2851 return false;
2852}
2853
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002854static bool checkIfClauses(Sema &S, OpenMPDirectiveKind Kind,
2855 ArrayRef<OMPClause *> Clauses,
2856 ArrayRef<OpenMPDirectiveKind> AllowedNameModifiers) {
2857 bool ErrorFound = false;
2858 unsigned NamedModifiersNumber = 0;
2859 SmallVector<const OMPIfClause *, OMPC_unknown + 1> FoundNameModifiers(
2860 OMPD_unknown + 1);
Alexey Bataevecb156a2015-09-15 17:23:56 +00002861 SmallVector<SourceLocation, 4> NameModifierLoc;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002862 for (const auto *C : Clauses) {
2863 if (const auto *IC = dyn_cast_or_null<OMPIfClause>(C)) {
2864 // At most one if clause without a directive-name-modifier can appear on
2865 // the directive.
2866 OpenMPDirectiveKind CurNM = IC->getNameModifier();
2867 if (FoundNameModifiers[CurNM]) {
2868 S.Diag(C->getLocStart(), diag::err_omp_more_one_clause)
2869 << getOpenMPDirectiveName(Kind) << getOpenMPClauseName(OMPC_if)
2870 << (CurNM != OMPD_unknown) << getOpenMPDirectiveName(CurNM);
2871 ErrorFound = true;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002872 } else if (CurNM != OMPD_unknown) {
2873 NameModifierLoc.push_back(IC->getNameModifierLoc());
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002874 ++NamedModifiersNumber;
Alexey Bataevecb156a2015-09-15 17:23:56 +00002875 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002876 FoundNameModifiers[CurNM] = IC;
2877 if (CurNM == OMPD_unknown)
2878 continue;
2879 // Check if the specified name modifier is allowed for the current
2880 // directive.
2881 // At most one if clause with the particular directive-name-modifier can
2882 // appear on the directive.
2883 bool MatchFound = false;
2884 for (auto NM : AllowedNameModifiers) {
2885 if (CurNM == NM) {
2886 MatchFound = true;
2887 break;
2888 }
2889 }
2890 if (!MatchFound) {
2891 S.Diag(IC->getNameModifierLoc(),
2892 diag::err_omp_wrong_if_directive_name_modifier)
2893 << getOpenMPDirectiveName(CurNM) << getOpenMPDirectiveName(Kind);
2894 ErrorFound = true;
2895 }
2896 }
2897 }
2898 // If any if clause on the directive includes a directive-name-modifier then
2899 // all if clauses on the directive must include a directive-name-modifier.
2900 if (FoundNameModifiers[OMPD_unknown] && NamedModifiersNumber > 0) {
2901 if (NamedModifiersNumber == AllowedNameModifiers.size()) {
2902 S.Diag(FoundNameModifiers[OMPD_unknown]->getLocStart(),
2903 diag::err_omp_no_more_if_clause);
2904 } else {
2905 std::string Values;
2906 std::string Sep(", ");
2907 unsigned AllowedCnt = 0;
2908 unsigned TotalAllowedNum =
2909 AllowedNameModifiers.size() - NamedModifiersNumber;
2910 for (unsigned Cnt = 0, End = AllowedNameModifiers.size(); Cnt < End;
2911 ++Cnt) {
2912 OpenMPDirectiveKind NM = AllowedNameModifiers[Cnt];
2913 if (!FoundNameModifiers[NM]) {
2914 Values += "'";
2915 Values += getOpenMPDirectiveName(NM);
2916 Values += "'";
2917 if (AllowedCnt + 2 == TotalAllowedNum)
2918 Values += " or ";
2919 else if (AllowedCnt + 1 != TotalAllowedNum)
2920 Values += Sep;
2921 ++AllowedCnt;
2922 }
2923 }
2924 S.Diag(FoundNameModifiers[OMPD_unknown]->getCondition()->getLocStart(),
2925 diag::err_omp_unnamed_if_clause)
2926 << (TotalAllowedNum > 1) << Values;
2927 }
Alexey Bataevecb156a2015-09-15 17:23:56 +00002928 for (auto Loc : NameModifierLoc) {
2929 S.Diag(Loc, diag::note_omp_previous_named_if_clause);
2930 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00002931 ErrorFound = true;
2932 }
2933 return ErrorFound;
2934}
2935
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002936StmtResult Sema::ActOnOpenMPExecutableDirective(
2937 OpenMPDirectiveKind Kind, const DeclarationNameInfo &DirName,
2938 OpenMPDirectiveKind CancelRegion, ArrayRef<OMPClause *> Clauses,
2939 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00002940 StmtResult Res = StmtError();
Jonas Hahnfeld64a9e3c2017-02-22 06:49:10 +00002941 // First check CancelRegion which is then used in checkNestingOfRegions.
2942 if (checkCancelRegion(*this, Kind, CancelRegion, StartLoc) ||
2943 checkNestingOfRegions(*this, DSAStack, Kind, DirName, CancelRegion,
Alexey Bataev6d4ed052015-07-01 06:57:41 +00002944 StartLoc))
Alexey Bataev549210e2014-06-24 04:39:47 +00002945 return StmtError();
Alexey Bataev758e55e2013-09-06 18:03:48 +00002946
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002947 llvm::SmallVector<OMPClause *, 8> ClausesWithImplicit;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00002948 llvm::DenseMap<ValueDecl *, Expr *> VarsWithInheritedDSA;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00002949 bool ErrorFound = false;
Alexey Bataev6125da92014-07-21 11:26:11 +00002950 ClausesWithImplicit.append(Clauses.begin(), Clauses.end());
Alexey Bataev0dce2ea2017-09-21 14:06:59 +00002951 if (AStmt && !CurContext->isDependentContext()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002952 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
2953
2954 // Check default data sharing attributes for referenced variables.
2955 DSAAttrChecker DSAChecker(DSAStack, *this, cast<CapturedStmt>(AStmt));
Arpith Chacko Jacob1f46b702017-01-23 15:38:49 +00002956 int ThisCaptureLevel = getOpenMPCaptureLevels(Kind);
2957 Stmt *S = AStmt;
2958 while (--ThisCaptureLevel >= 0)
2959 S = cast<CapturedStmt>(S)->getCapturedStmt();
2960 DSAChecker.Visit(S);
Alexey Bataev68446b72014-07-18 07:47:19 +00002961 if (DSAChecker.isErrorFound())
2962 return StmtError();
2963 // Generate list of implicitly defined firstprivate variables.
2964 VarsWithInheritedDSA = DSAChecker.getVarsWithInheritedDSA();
Alexey Bataev68446b72014-07-18 07:47:19 +00002965
Alexey Bataev88202be2017-07-27 13:20:36 +00002966 SmallVector<Expr *, 4> ImplicitFirstprivates(
2967 DSAChecker.getImplicitFirstprivate().begin(),
2968 DSAChecker.getImplicitFirstprivate().end());
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002969 SmallVector<Expr *, 4> ImplicitMaps(DSAChecker.getImplicitMap().begin(),
2970 DSAChecker.getImplicitMap().end());
Alexey Bataev88202be2017-07-27 13:20:36 +00002971 // Mark taskgroup task_reduction descriptors as implicitly firstprivate.
2972 for (auto *C : Clauses) {
2973 if (auto *IRC = dyn_cast<OMPInReductionClause>(C)) {
2974 for (auto *E : IRC->taskgroup_descriptors())
2975 if (E)
2976 ImplicitFirstprivates.emplace_back(E);
2977 }
2978 }
2979 if (!ImplicitFirstprivates.empty()) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002980 if (OMPClause *Implicit = ActOnOpenMPFirstprivateClause(
Alexey Bataev88202be2017-07-27 13:20:36 +00002981 ImplicitFirstprivates, SourceLocation(), SourceLocation(),
2982 SourceLocation())) {
Alexey Bataev68446b72014-07-18 07:47:19 +00002983 ClausesWithImplicit.push_back(Implicit);
2984 ErrorFound = cast<OMPFirstprivateClause>(Implicit)->varlist_size() !=
Alexey Bataev88202be2017-07-27 13:20:36 +00002985 ImplicitFirstprivates.size();
Alexey Bataev68446b72014-07-18 07:47:19 +00002986 } else
2987 ErrorFound = true;
2988 }
Alexey Bataevf47c4b42017-09-26 13:47:31 +00002989 if (!ImplicitMaps.empty()) {
2990 if (OMPClause *Implicit = ActOnOpenMPMapClause(
2991 OMPC_MAP_unknown, OMPC_MAP_tofrom, /*IsMapTypeImplicit=*/true,
2992 SourceLocation(), SourceLocation(), ImplicitMaps,
2993 SourceLocation(), SourceLocation(), SourceLocation())) {
2994 ClausesWithImplicit.emplace_back(Implicit);
2995 ErrorFound |=
2996 cast<OMPMapClause>(Implicit)->varlist_size() != ImplicitMaps.size();
2997 } else
2998 ErrorFound = true;
2999 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003000 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00003001
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003002 llvm::SmallVector<OpenMPDirectiveKind, 4> AllowedNameModifiers;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003003 switch (Kind) {
3004 case OMPD_parallel:
Alexey Bataeved09d242014-05-28 05:53:51 +00003005 Res = ActOnOpenMPParallelDirective(ClausesWithImplicit, AStmt, StartLoc,
3006 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003007 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003008 break;
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003009 case OMPD_simd:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003010 Res = ActOnOpenMPSimdDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3011 VarsWithInheritedDSA);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00003012 break;
Alexey Bataevf29276e2014-06-18 04:14:57 +00003013 case OMPD_for:
Alexey Bataev4acb8592014-07-07 13:01:15 +00003014 Res = ActOnOpenMPForDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc,
3015 VarsWithInheritedDSA);
Alexey Bataevf29276e2014-06-18 04:14:57 +00003016 break;
Alexander Musmanf82886e2014-09-18 05:12:34 +00003017 case OMPD_for_simd:
3018 Res = ActOnOpenMPForSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3019 EndLoc, VarsWithInheritedDSA);
3020 break;
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00003021 case OMPD_sections:
3022 Res = ActOnOpenMPSectionsDirective(ClausesWithImplicit, AStmt, StartLoc,
3023 EndLoc);
3024 break;
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003025 case OMPD_section:
3026 assert(ClausesWithImplicit.empty() &&
Alexander Musman80c22892014-07-17 08:54:58 +00003027 "No clauses are allowed for 'omp section' directive");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00003028 Res = ActOnOpenMPSectionDirective(AStmt, StartLoc, EndLoc);
3029 break;
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00003030 case OMPD_single:
3031 Res = ActOnOpenMPSingleDirective(ClausesWithImplicit, AStmt, StartLoc,
3032 EndLoc);
3033 break;
Alexander Musman80c22892014-07-17 08:54:58 +00003034 case OMPD_master:
3035 assert(ClausesWithImplicit.empty() &&
3036 "No clauses are allowed for 'omp master' directive");
3037 Res = ActOnOpenMPMasterDirective(AStmt, StartLoc, EndLoc);
3038 break;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003039 case OMPD_critical:
Alexey Bataev28c75412015-12-15 08:19:24 +00003040 Res = ActOnOpenMPCriticalDirective(DirName, ClausesWithImplicit, AStmt,
3041 StartLoc, EndLoc);
Alexander Musmand9ed09f2014-07-21 09:42:05 +00003042 break;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003043 case OMPD_parallel_for:
3044 Res = ActOnOpenMPParallelForDirective(ClausesWithImplicit, AStmt, StartLoc,
3045 EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003046 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev4acb8592014-07-07 13:01:15 +00003047 break;
Alexander Musmane4e893b2014-09-23 09:33:00 +00003048 case OMPD_parallel_for_simd:
3049 Res = ActOnOpenMPParallelForSimdDirective(
3050 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003051 AllowedNameModifiers.push_back(OMPD_parallel);
Alexander Musmane4e893b2014-09-23 09:33:00 +00003052 break;
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003053 case OMPD_parallel_sections:
3054 Res = ActOnOpenMPParallelSectionsDirective(ClausesWithImplicit, AStmt,
3055 StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003056 AllowedNameModifiers.push_back(OMPD_parallel);
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00003057 break;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003058 case OMPD_task:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003059 Res =
3060 ActOnOpenMPTaskDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003061 AllowedNameModifiers.push_back(OMPD_task);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003062 break;
Alexey Bataev68446b72014-07-18 07:47:19 +00003063 case OMPD_taskyield:
3064 assert(ClausesWithImplicit.empty() &&
3065 "No clauses are allowed for 'omp taskyield' directive");
3066 assert(AStmt == nullptr &&
3067 "No associated statement allowed for 'omp taskyield' directive");
3068 Res = ActOnOpenMPTaskyieldDirective(StartLoc, EndLoc);
3069 break;
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00003070 case OMPD_barrier:
3071 assert(ClausesWithImplicit.empty() &&
3072 "No clauses are allowed for 'omp barrier' directive");
3073 assert(AStmt == nullptr &&
3074 "No associated statement allowed for 'omp barrier' directive");
3075 Res = ActOnOpenMPBarrierDirective(StartLoc, EndLoc);
3076 break;
Alexey Bataev2df347a2014-07-18 10:17:07 +00003077 case OMPD_taskwait:
3078 assert(ClausesWithImplicit.empty() &&
3079 "No clauses are allowed for 'omp taskwait' directive");
3080 assert(AStmt == nullptr &&
3081 "No associated statement allowed for 'omp taskwait' directive");
3082 Res = ActOnOpenMPTaskwaitDirective(StartLoc, EndLoc);
3083 break;
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003084 case OMPD_taskgroup:
Alexey Bataev169d96a2017-07-18 20:17:46 +00003085 Res = ActOnOpenMPTaskgroupDirective(ClausesWithImplicit, AStmt, StartLoc,
3086 EndLoc);
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00003087 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00003088 case OMPD_flush:
3089 assert(AStmt == nullptr &&
3090 "No associated statement allowed for 'omp flush' directive");
3091 Res = ActOnOpenMPFlushDirective(ClausesWithImplicit, StartLoc, EndLoc);
3092 break;
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003093 case OMPD_ordered:
Alexey Bataev346265e2015-09-25 10:37:12 +00003094 Res = ActOnOpenMPOrderedDirective(ClausesWithImplicit, AStmt, StartLoc,
3095 EndLoc);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00003096 break;
Alexey Bataev0162e452014-07-22 10:10:35 +00003097 case OMPD_atomic:
3098 Res = ActOnOpenMPAtomicDirective(ClausesWithImplicit, AStmt, StartLoc,
3099 EndLoc);
3100 break;
Alexey Bataev13314bf2014-10-09 04:18:56 +00003101 case OMPD_teams:
3102 Res =
3103 ActOnOpenMPTeamsDirective(ClausesWithImplicit, AStmt, StartLoc, EndLoc);
3104 break;
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003105 case OMPD_target:
3106 Res = ActOnOpenMPTargetDirective(ClausesWithImplicit, AStmt, StartLoc,
3107 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003108 AllowedNameModifiers.push_back(OMPD_target);
Alexey Bataev0bd520b2014-09-19 08:19:49 +00003109 break;
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00003110 case OMPD_target_parallel:
3111 Res = ActOnOpenMPTargetParallelDirective(ClausesWithImplicit, AStmt,
3112 StartLoc, EndLoc);
3113 AllowedNameModifiers.push_back(OMPD_target);
3114 AllowedNameModifiers.push_back(OMPD_parallel);
3115 break;
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00003116 case OMPD_target_parallel_for:
3117 Res = ActOnOpenMPTargetParallelForDirective(
3118 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3119 AllowedNameModifiers.push_back(OMPD_target);
3120 AllowedNameModifiers.push_back(OMPD_parallel);
3121 break;
Alexey Bataev6d4ed052015-07-01 06:57:41 +00003122 case OMPD_cancellation_point:
3123 assert(ClausesWithImplicit.empty() &&
3124 "No clauses are allowed for 'omp cancellation point' directive");
3125 assert(AStmt == nullptr && "No associated statement allowed for 'omp "
3126 "cancellation point' directive");
3127 Res = ActOnOpenMPCancellationPointDirective(StartLoc, EndLoc, CancelRegion);
3128 break;
Alexey Bataev80909872015-07-02 11:25:17 +00003129 case OMPD_cancel:
Alexey Bataev80909872015-07-02 11:25:17 +00003130 assert(AStmt == nullptr &&
3131 "No associated statement allowed for 'omp cancel' directive");
Alexey Bataev87933c72015-09-18 08:07:34 +00003132 Res = ActOnOpenMPCancelDirective(ClausesWithImplicit, StartLoc, EndLoc,
3133 CancelRegion);
3134 AllowedNameModifiers.push_back(OMPD_cancel);
Alexey Bataev80909872015-07-02 11:25:17 +00003135 break;
Michael Wong65f367f2015-07-21 13:44:28 +00003136 case OMPD_target_data:
3137 Res = ActOnOpenMPTargetDataDirective(ClausesWithImplicit, AStmt, StartLoc,
3138 EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003139 AllowedNameModifiers.push_back(OMPD_target_data);
Michael Wong65f367f2015-07-21 13:44:28 +00003140 break;
Samuel Antaodf67fc42016-01-19 19:15:56 +00003141 case OMPD_target_enter_data:
3142 Res = ActOnOpenMPTargetEnterDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003143 EndLoc, AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00003144 AllowedNameModifiers.push_back(OMPD_target_enter_data);
3145 break;
Samuel Antao72590762016-01-19 20:04:50 +00003146 case OMPD_target_exit_data:
3147 Res = ActOnOpenMPTargetExitDataDirective(ClausesWithImplicit, StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00003148 EndLoc, AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00003149 AllowedNameModifiers.push_back(OMPD_target_exit_data);
3150 break;
Alexey Bataev49f6e782015-12-01 04:18:41 +00003151 case OMPD_taskloop:
3152 Res = ActOnOpenMPTaskLoopDirective(ClausesWithImplicit, AStmt, StartLoc,
3153 EndLoc, VarsWithInheritedDSA);
3154 AllowedNameModifiers.push_back(OMPD_taskloop);
3155 break;
Alexey Bataev0a6ed842015-12-03 09:40:15 +00003156 case OMPD_taskloop_simd:
3157 Res = ActOnOpenMPTaskLoopSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3158 EndLoc, VarsWithInheritedDSA);
3159 AllowedNameModifiers.push_back(OMPD_taskloop);
3160 break;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00003161 case OMPD_distribute:
3162 Res = ActOnOpenMPDistributeDirective(ClausesWithImplicit, AStmt, StartLoc,
3163 EndLoc, VarsWithInheritedDSA);
3164 break;
Samuel Antao686c70c2016-05-26 17:30:50 +00003165 case OMPD_target_update:
Alexey Bataev7828b252017-11-21 17:08:48 +00003166 Res = ActOnOpenMPTargetUpdateDirective(ClausesWithImplicit, StartLoc,
3167 EndLoc, AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00003168 AllowedNameModifiers.push_back(OMPD_target_update);
3169 break;
Carlo Bertolli9925f152016-06-27 14:55:37 +00003170 case OMPD_distribute_parallel_for:
3171 Res = ActOnOpenMPDistributeParallelForDirective(
3172 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3173 AllowedNameModifiers.push_back(OMPD_parallel);
3174 break;
Kelvin Li4a39add2016-07-05 05:00:15 +00003175 case OMPD_distribute_parallel_for_simd:
3176 Res = ActOnOpenMPDistributeParallelForSimdDirective(
3177 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3178 AllowedNameModifiers.push_back(OMPD_parallel);
3179 break;
Kelvin Li787f3fc2016-07-06 04:45:38 +00003180 case OMPD_distribute_simd:
3181 Res = ActOnOpenMPDistributeSimdDirective(
3182 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3183 break;
Kelvin Lia579b912016-07-14 02:54:56 +00003184 case OMPD_target_parallel_for_simd:
3185 Res = ActOnOpenMPTargetParallelForSimdDirective(
3186 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3187 AllowedNameModifiers.push_back(OMPD_target);
3188 AllowedNameModifiers.push_back(OMPD_parallel);
3189 break;
Kelvin Li986330c2016-07-20 22:57:10 +00003190 case OMPD_target_simd:
3191 Res = ActOnOpenMPTargetSimdDirective(ClausesWithImplicit, AStmt, StartLoc,
3192 EndLoc, VarsWithInheritedDSA);
3193 AllowedNameModifiers.push_back(OMPD_target);
3194 break;
Kelvin Li02532872016-08-05 14:37:37 +00003195 case OMPD_teams_distribute:
David Majnemer9d168222016-08-05 17:44:54 +00003196 Res = ActOnOpenMPTeamsDistributeDirective(
3197 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
Kelvin Li02532872016-08-05 14:37:37 +00003198 break;
Kelvin Li4e325f72016-10-25 12:50:55 +00003199 case OMPD_teams_distribute_simd:
3200 Res = ActOnOpenMPTeamsDistributeSimdDirective(
3201 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3202 break;
Kelvin Li579e41c2016-11-30 23:51:03 +00003203 case OMPD_teams_distribute_parallel_for_simd:
3204 Res = ActOnOpenMPTeamsDistributeParallelForSimdDirective(
3205 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3206 AllowedNameModifiers.push_back(OMPD_parallel);
3207 break;
Kelvin Li7ade93f2016-12-09 03:24:30 +00003208 case OMPD_teams_distribute_parallel_for:
3209 Res = ActOnOpenMPTeamsDistributeParallelForDirective(
3210 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3211 AllowedNameModifiers.push_back(OMPD_parallel);
3212 break;
Kelvin Libf594a52016-12-17 05:48:59 +00003213 case OMPD_target_teams:
3214 Res = ActOnOpenMPTargetTeamsDirective(ClausesWithImplicit, AStmt, StartLoc,
3215 EndLoc);
3216 AllowedNameModifiers.push_back(OMPD_target);
3217 break;
Kelvin Li83c451e2016-12-25 04:52:54 +00003218 case OMPD_target_teams_distribute:
3219 Res = ActOnOpenMPTargetTeamsDistributeDirective(
3220 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3221 AllowedNameModifiers.push_back(OMPD_target);
3222 break;
Kelvin Li80e8f562016-12-29 22:16:30 +00003223 case OMPD_target_teams_distribute_parallel_for:
3224 Res = ActOnOpenMPTargetTeamsDistributeParallelForDirective(
3225 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3226 AllowedNameModifiers.push_back(OMPD_target);
3227 AllowedNameModifiers.push_back(OMPD_parallel);
3228 break;
Kelvin Li1851df52017-01-03 05:23:48 +00003229 case OMPD_target_teams_distribute_parallel_for_simd:
3230 Res = ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
3231 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3232 AllowedNameModifiers.push_back(OMPD_target);
3233 AllowedNameModifiers.push_back(OMPD_parallel);
3234 break;
Kelvin Lida681182017-01-10 18:08:18 +00003235 case OMPD_target_teams_distribute_simd:
3236 Res = ActOnOpenMPTargetTeamsDistributeSimdDirective(
3237 ClausesWithImplicit, AStmt, StartLoc, EndLoc, VarsWithInheritedDSA);
3238 AllowedNameModifiers.push_back(OMPD_target);
3239 break;
Dmitry Polukhin0b0da292016-04-06 11:38:59 +00003240 case OMPD_declare_target:
3241 case OMPD_end_declare_target:
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00003242 case OMPD_threadprivate:
Alexey Bataev94a4f0c2016-03-03 05:21:39 +00003243 case OMPD_declare_reduction:
Alexey Bataev587e1de2016-03-30 10:43:55 +00003244 case OMPD_declare_simd:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003245 llvm_unreachable("OpenMP Directive is not allowed");
3246 case OMPD_unknown:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003247 llvm_unreachable("Unknown OpenMP directive");
3248 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00003249
Alexey Bataev4acb8592014-07-07 13:01:15 +00003250 for (auto P : VarsWithInheritedDSA) {
3251 Diag(P.second->getExprLoc(), diag::err_omp_no_dsa_for_variable)
3252 << P.first << P.second->getSourceRange();
3253 }
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003254 ErrorFound = !VarsWithInheritedDSA.empty() || ErrorFound;
3255
3256 if (!AllowedNameModifiers.empty())
3257 ErrorFound = checkIfClauses(*this, Kind, Clauses, AllowedNameModifiers) ||
3258 ErrorFound;
Alexey Bataev4acb8592014-07-07 13:01:15 +00003259
Alexey Bataeved09d242014-05-28 05:53:51 +00003260 if (ErrorFound)
3261 return StmtError();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003262 return Res;
3263}
3264
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003265Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareSimdDirective(
3266 DeclGroupPtrTy DG, OMPDeclareSimdDeclAttr::BranchStateTy BS, Expr *Simdlen,
Alexey Bataevd93d3762016-04-12 09:35:56 +00003267 ArrayRef<Expr *> Uniforms, ArrayRef<Expr *> Aligneds,
Alexey Bataevecba70f2016-04-12 11:02:11 +00003268 ArrayRef<Expr *> Alignments, ArrayRef<Expr *> Linears,
3269 ArrayRef<unsigned> LinModifiers, ArrayRef<Expr *> Steps, SourceRange SR) {
Alexey Bataevd93d3762016-04-12 09:35:56 +00003270 assert(Aligneds.size() == Alignments.size());
Alexey Bataevecba70f2016-04-12 11:02:11 +00003271 assert(Linears.size() == LinModifiers.size());
3272 assert(Linears.size() == Steps.size());
Alexey Bataev587e1de2016-03-30 10:43:55 +00003273 if (!DG || DG.get().isNull())
3274 return DeclGroupPtrTy();
3275
3276 if (!DG.get().isSingleDecl()) {
Alexey Bataev20dfd772016-04-04 10:12:15 +00003277 Diag(SR.getBegin(), diag::err_omp_single_decl_in_declare_simd);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003278 return DG;
3279 }
3280 auto *ADecl = DG.get().getSingleDecl();
3281 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ADecl))
3282 ADecl = FTD->getTemplatedDecl();
3283
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003284 auto *FD = dyn_cast<FunctionDecl>(ADecl);
3285 if (!FD) {
3286 Diag(ADecl->getLocation(), diag::err_omp_function_expected);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003287 return DeclGroupPtrTy();
3288 }
3289
Alexey Bataev2af33e32016-04-07 12:45:37 +00003290 // OpenMP [2.8.2, declare simd construct, Description]
3291 // The parameter of the simdlen clause must be a constant positive integer
3292 // expression.
3293 ExprResult SL;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003294 if (Simdlen)
Alexey Bataev2af33e32016-04-07 12:45:37 +00003295 SL = VerifyPositiveIntegerConstantInClause(Simdlen, OMPC_simdlen);
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003296 // OpenMP [2.8.2, declare simd construct, Description]
3297 // The special this pointer can be used as if was one of the arguments to the
3298 // function in any of the linear, aligned, or uniform clauses.
3299 // The uniform clause declares one or more arguments to have an invariant
3300 // value for all concurrent invocations of the function in the execution of a
3301 // single SIMD loop.
Alexey Bataevecba70f2016-04-12 11:02:11 +00003302 llvm::DenseMap<Decl *, Expr *> UniformedArgs;
3303 Expr *UniformedLinearThis = nullptr;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003304 for (auto *E : Uniforms) {
3305 E = E->IgnoreParenImpCasts();
3306 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3307 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl()))
3308 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3309 FD->getParamDecl(PVD->getFunctionScopeIndex())
Alexey Bataevecba70f2016-04-12 11:02:11 +00003310 ->getCanonicalDecl() == PVD->getCanonicalDecl()) {
3311 UniformedArgs.insert(std::make_pair(PVD->getCanonicalDecl(), E));
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003312 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003313 }
3314 if (isa<CXXThisExpr>(E)) {
3315 UniformedLinearThis = E;
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003316 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +00003317 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003318 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3319 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
Alexey Bataev2af33e32016-04-07 12:45:37 +00003320 }
Alexey Bataevd93d3762016-04-12 09:35:56 +00003321 // OpenMP [2.8.2, declare simd construct, Description]
3322 // The aligned clause declares that the object to which each list item points
3323 // is aligned to the number of bytes expressed in the optional parameter of
3324 // the aligned clause.
3325 // The special this pointer can be used as if was one of the arguments to the
3326 // function in any of the linear, aligned, or uniform clauses.
3327 // The type of list items appearing in the aligned clause must be array,
3328 // pointer, reference to array, or reference to pointer.
3329 llvm::DenseMap<Decl *, Expr *> AlignedArgs;
3330 Expr *AlignedThis = nullptr;
3331 for (auto *E : Aligneds) {
3332 E = E->IgnoreParenImpCasts();
3333 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3334 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3335 auto *CanonPVD = PVD->getCanonicalDecl();
3336 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3337 FD->getParamDecl(PVD->getFunctionScopeIndex())
3338 ->getCanonicalDecl() == CanonPVD) {
3339 // OpenMP [2.8.1, simd construct, Restrictions]
3340 // A list-item cannot appear in more than one aligned clause.
3341 if (AlignedArgs.count(CanonPVD) > 0) {
3342 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3343 << 1 << E->getSourceRange();
3344 Diag(AlignedArgs[CanonPVD]->getExprLoc(),
3345 diag::note_omp_explicit_dsa)
3346 << getOpenMPClauseName(OMPC_aligned);
3347 continue;
3348 }
3349 AlignedArgs[CanonPVD] = E;
3350 QualType QTy = PVD->getType()
3351 .getNonReferenceType()
3352 .getUnqualifiedType()
3353 .getCanonicalType();
3354 const Type *Ty = QTy.getTypePtrOrNull();
3355 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
3356 Diag(E->getExprLoc(), diag::err_omp_aligned_expected_array_or_ptr)
3357 << QTy << getLangOpts().CPlusPlus << E->getSourceRange();
3358 Diag(PVD->getLocation(), diag::note_previous_decl) << PVD;
3359 }
3360 continue;
3361 }
3362 }
3363 if (isa<CXXThisExpr>(E)) {
3364 if (AlignedThis) {
3365 Diag(E->getExprLoc(), diag::err_omp_aligned_twice)
3366 << 2 << E->getSourceRange();
3367 Diag(AlignedThis->getExprLoc(), diag::note_omp_explicit_dsa)
3368 << getOpenMPClauseName(OMPC_aligned);
3369 }
3370 AlignedThis = E;
3371 continue;
3372 }
3373 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3374 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3375 }
3376 // The optional parameter of the aligned clause, alignment, must be a constant
3377 // positive integer expression. If no optional parameter is specified,
3378 // implementation-defined default alignments for SIMD instructions on the
3379 // target platforms are assumed.
3380 SmallVector<Expr *, 4> NewAligns;
3381 for (auto *E : Alignments) {
3382 ExprResult Align;
3383 if (E)
3384 Align = VerifyPositiveIntegerConstantInClause(E, OMPC_aligned);
3385 NewAligns.push_back(Align.get());
3386 }
Alexey Bataevecba70f2016-04-12 11:02:11 +00003387 // OpenMP [2.8.2, declare simd construct, Description]
3388 // The linear clause declares one or more list items to be private to a SIMD
3389 // lane and to have a linear relationship with respect to the iteration space
3390 // of a loop.
3391 // The special this pointer can be used as if was one of the arguments to the
3392 // function in any of the linear, aligned, or uniform clauses.
3393 // When a linear-step expression is specified in a linear clause it must be
3394 // either a constant integer expression or an integer-typed parameter that is
3395 // specified in a uniform clause on the directive.
3396 llvm::DenseMap<Decl *, Expr *> LinearArgs;
3397 const bool IsUniformedThis = UniformedLinearThis != nullptr;
3398 auto MI = LinModifiers.begin();
3399 for (auto *E : Linears) {
3400 auto LinKind = static_cast<OpenMPLinearClauseKind>(*MI);
3401 ++MI;
3402 E = E->IgnoreParenImpCasts();
3403 if (auto *DRE = dyn_cast<DeclRefExpr>(E))
3404 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3405 auto *CanonPVD = PVD->getCanonicalDecl();
3406 if (FD->getNumParams() > PVD->getFunctionScopeIndex() &&
3407 FD->getParamDecl(PVD->getFunctionScopeIndex())
3408 ->getCanonicalDecl() == CanonPVD) {
3409 // OpenMP [2.15.3.7, linear Clause, Restrictions]
3410 // A list-item cannot appear in more than one linear clause.
3411 if (LinearArgs.count(CanonPVD) > 0) {
3412 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3413 << getOpenMPClauseName(OMPC_linear)
3414 << getOpenMPClauseName(OMPC_linear) << E->getSourceRange();
3415 Diag(LinearArgs[CanonPVD]->getExprLoc(),
3416 diag::note_omp_explicit_dsa)
3417 << getOpenMPClauseName(OMPC_linear);
3418 continue;
3419 }
3420 // Each argument can appear in at most one uniform or linear clause.
3421 if (UniformedArgs.count(CanonPVD) > 0) {
3422 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3423 << getOpenMPClauseName(OMPC_linear)
3424 << getOpenMPClauseName(OMPC_uniform) << E->getSourceRange();
3425 Diag(UniformedArgs[CanonPVD]->getExprLoc(),
3426 diag::note_omp_explicit_dsa)
3427 << getOpenMPClauseName(OMPC_uniform);
3428 continue;
3429 }
3430 LinearArgs[CanonPVD] = E;
3431 if (E->isValueDependent() || E->isTypeDependent() ||
3432 E->isInstantiationDependent() ||
3433 E->containsUnexpandedParameterPack())
3434 continue;
3435 (void)CheckOpenMPLinearDecl(CanonPVD, E->getExprLoc(), LinKind,
3436 PVD->getOriginalType());
3437 continue;
3438 }
3439 }
3440 if (isa<CXXThisExpr>(E)) {
3441 if (UniformedLinearThis) {
3442 Diag(E->getExprLoc(), diag::err_omp_wrong_dsa)
3443 << getOpenMPClauseName(OMPC_linear)
3444 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform : OMPC_linear)
3445 << E->getSourceRange();
3446 Diag(UniformedLinearThis->getExprLoc(), diag::note_omp_explicit_dsa)
3447 << getOpenMPClauseName(IsUniformedThis ? OMPC_uniform
3448 : OMPC_linear);
3449 continue;
3450 }
3451 UniformedLinearThis = E;
3452 if (E->isValueDependent() || E->isTypeDependent() ||
3453 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
3454 continue;
3455 (void)CheckOpenMPLinearDecl(/*D=*/nullptr, E->getExprLoc(), LinKind,
3456 E->getType());
3457 continue;
3458 }
3459 Diag(E->getExprLoc(), diag::err_omp_param_or_this_in_clause)
3460 << FD->getDeclName() << (isa<CXXMethodDecl>(ADecl) ? 1 : 0);
3461 }
3462 Expr *Step = nullptr;
3463 Expr *NewStep = nullptr;
3464 SmallVector<Expr *, 4> NewSteps;
3465 for (auto *E : Steps) {
3466 // Skip the same step expression, it was checked already.
3467 if (Step == E || !E) {
3468 NewSteps.push_back(E ? NewStep : nullptr);
3469 continue;
3470 }
3471 Step = E;
3472 if (auto *DRE = dyn_cast<DeclRefExpr>(Step))
3473 if (auto *PVD = dyn_cast<ParmVarDecl>(DRE->getDecl())) {
3474 auto *CanonPVD = PVD->getCanonicalDecl();
3475 if (UniformedArgs.count(CanonPVD) == 0) {
3476 Diag(Step->getExprLoc(), diag::err_omp_expected_uniform_param)
3477 << Step->getSourceRange();
3478 } else if (E->isValueDependent() || E->isTypeDependent() ||
3479 E->isInstantiationDependent() ||
3480 E->containsUnexpandedParameterPack() ||
3481 CanonPVD->getType()->hasIntegerRepresentation())
3482 NewSteps.push_back(Step);
3483 else {
3484 Diag(Step->getExprLoc(), diag::err_omp_expected_int_param)
3485 << Step->getSourceRange();
3486 }
3487 continue;
3488 }
3489 NewStep = Step;
3490 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
3491 !Step->isInstantiationDependent() &&
3492 !Step->containsUnexpandedParameterPack()) {
3493 NewStep = PerformOpenMPImplicitIntegerConversion(Step->getExprLoc(), Step)
3494 .get();
3495 if (NewStep)
3496 NewStep = VerifyIntegerConstantExpression(NewStep).get();
3497 }
3498 NewSteps.push_back(NewStep);
3499 }
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00003500 auto *NewAttr = OMPDeclareSimdDeclAttr::CreateImplicit(
3501 Context, BS, SL.get(), const_cast<Expr **>(Uniforms.data()),
Alexey Bataevd93d3762016-04-12 09:35:56 +00003502 Uniforms.size(), const_cast<Expr **>(Aligneds.data()), Aligneds.size(),
Alexey Bataevecba70f2016-04-12 11:02:11 +00003503 const_cast<Expr **>(NewAligns.data()), NewAligns.size(),
3504 const_cast<Expr **>(Linears.data()), Linears.size(),
3505 const_cast<unsigned *>(LinModifiers.data()), LinModifiers.size(),
3506 NewSteps.data(), NewSteps.size(), SR);
Alexey Bataev587e1de2016-03-30 10:43:55 +00003507 ADecl->addAttr(NewAttr);
3508 return ConvertDeclToDeclGroup(ADecl);
3509}
3510
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003511StmtResult Sema::ActOnOpenMPParallelDirective(ArrayRef<OMPClause *> Clauses,
3512 Stmt *AStmt,
3513 SourceLocation StartLoc,
3514 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00003515 if (!AStmt)
3516 return StmtError();
3517
Alexey Bataev9959db52014-05-06 10:08:46 +00003518 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
3519 // 1.2.2 OpenMP Language Terminology
3520 // Structured block - An executable statement with a single entry at the
3521 // top and a single exit at the bottom.
3522 // The point of exit cannot be a branch out of the structured block.
3523 // longjmp() and throw() must not violate the entry/exit criteria.
3524 CS->getCapturedDecl()->setNothrow();
3525
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003526 getCurFunction()->setHasBranchProtectedScope();
3527
Alexey Bataev25e5b442015-09-15 12:52:43 +00003528 return OMPParallelDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
3529 DSAStack->isCancelRegion());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00003530}
3531
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003532namespace {
3533/// \brief Helper class for checking canonical form of the OpenMP loops and
3534/// extracting iteration space of each loop in the loop nest, that will be used
3535/// for IR generation.
3536class OpenMPIterationSpaceChecker {
3537 /// \brief Reference to Sema.
3538 Sema &SemaRef;
3539 /// \brief A location for diagnostics (when there is no some better location).
3540 SourceLocation DefaultLoc;
3541 /// \brief A location for diagnostics (when increment is not compatible).
3542 SourceLocation ConditionLoc;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003543 /// \brief A source location for referring to loop init later.
3544 SourceRange InitSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003545 /// \brief A source location for referring to condition later.
3546 SourceRange ConditionSrcRange;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003547 /// \brief A source location for referring to increment later.
3548 SourceRange IncrementSrcRange;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003549 /// \brief Loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003550 ValueDecl *LCDecl = nullptr;
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003551 /// \brief Reference to loop variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003552 Expr *LCRef = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003553 /// \brief Lower bound (initializer for the var).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003554 Expr *LB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003555 /// \brief Upper bound.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003556 Expr *UB = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003557 /// \brief Loop step (increment).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003558 Expr *Step = nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003559 /// \brief This flag is true when condition is one of:
3560 /// Var < UB
3561 /// Var <= UB
3562 /// UB > Var
3563 /// UB >= Var
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003564 bool TestIsLessOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003565 /// \brief This flag is true when condition is strict ( < or > ).
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003566 bool TestIsStrictOp = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003567 /// \brief This flag is true when step is subtracted on each iteration.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003568 bool SubtractStep = false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003569
3570public:
3571 OpenMPIterationSpaceChecker(Sema &SemaRef, SourceLocation DefaultLoc)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003572 : SemaRef(SemaRef), DefaultLoc(DefaultLoc), ConditionLoc(DefaultLoc) {}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003573 /// \brief Check init-expr for canonical loop form and save loop counter
3574 /// variable - #Var and its initialization value - #LB.
Alexey Bataev9c821032015-04-30 04:23:23 +00003575 bool CheckInit(Stmt *S, bool EmitDiags = true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003576 /// \brief Check test-expr for canonical form, save upper-bound (#UB), flags
3577 /// for less/greater and for strict/non-strict comparison.
3578 bool CheckCond(Expr *S);
3579 /// \brief Check incr-expr for canonical loop form and return true if it
3580 /// does not conform, otherwise save loop step (#Step).
3581 bool CheckInc(Expr *S);
3582 /// \brief Return the loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003583 ValueDecl *GetLoopDecl() const { return LCDecl; }
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003584 /// \brief Return the reference expression to loop counter variable.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003585 Expr *GetLoopDeclRefExpr() const { return LCRef; }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003586 /// \brief Source range of the loop init.
3587 SourceRange GetInitSrcRange() const { return InitSrcRange; }
3588 /// \brief Source range of the loop condition.
3589 SourceRange GetConditionSrcRange() const { return ConditionSrcRange; }
3590 /// \brief Source range of the loop increment.
3591 SourceRange GetIncrementSrcRange() const { return IncrementSrcRange; }
3592 /// \brief True if the step should be subtracted.
3593 bool ShouldSubtractStep() const { return SubtractStep; }
3594 /// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003595 Expr *
3596 BuildNumIterations(Scope *S, const bool LimitedType,
3597 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexey Bataev62dbb972015-04-22 11:59:37 +00003598 /// \brief Build the precondition expression for the loops.
Alexey Bataev5a3af132016-03-29 08:58:54 +00003599 Expr *BuildPreCond(Scope *S, Expr *Cond,
3600 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const;
Alexander Musmana5f070a2014-10-01 06:03:56 +00003601 /// \brief Build reference expression to the counter be used for codegen.
Alexey Bataev5dff95c2016-04-22 03:56:56 +00003602 DeclRefExpr *BuildCounterVar(llvm::MapVector<Expr *, DeclRefExpr *> &Captures,
3603 DSAStackTy &DSA) const;
Alexey Bataeva8899172015-08-06 12:30:57 +00003604 /// \brief Build reference expression to the private counter be used for
3605 /// codegen.
3606 Expr *BuildPrivateCounterVar() const;
David Majnemer9d168222016-08-05 17:44:54 +00003607 /// \brief Build initialization of the counter be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00003608 Expr *BuildCounterInit() const;
3609 /// \brief Build step of the counter be used for codegen.
3610 Expr *BuildCounterStep() const;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003611 /// \brief Return true if any expression is dependent.
3612 bool Dependent() const;
3613
3614private:
3615 /// \brief Check the right-hand side of an assignment in the increment
3616 /// expression.
3617 bool CheckIncRHS(Expr *RHS);
3618 /// \brief Helper to set loop counter variable and its initializer.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003619 bool SetLCDeclAndLB(ValueDecl *NewLCDecl, Expr *NewDeclRefExpr, Expr *NewLB);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003620 /// \brief Helper to set upper bound.
Craig Toppere335f252015-10-04 04:53:55 +00003621 bool SetUB(Expr *NewUB, bool LessOp, bool StrictOp, SourceRange SR,
Craig Topper9cd5e4f2015-09-21 01:23:32 +00003622 SourceLocation SL);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003623 /// \brief Helper to set loop increment.
3624 bool SetStep(Expr *NewStep, bool Subtract);
3625};
3626
3627bool OpenMPIterationSpaceChecker::Dependent() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003628 if (!LCDecl) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003629 assert(!LB && !UB && !Step);
3630 return false;
3631 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003632 return LCDecl->getType()->isDependentType() ||
3633 (LB && LB->isValueDependent()) || (UB && UB->isValueDependent()) ||
3634 (Step && Step->isValueDependent());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003635}
3636
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003637bool OpenMPIterationSpaceChecker::SetLCDeclAndLB(ValueDecl *NewLCDecl,
3638 Expr *NewLCRefExpr,
3639 Expr *NewLB) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003640 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003641 assert(LCDecl == nullptr && LB == nullptr && LCRef == nullptr &&
Alexey Bataevcaf09b02014-07-25 06:27:47 +00003642 UB == nullptr && Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003643 if (!NewLCDecl || !NewLB)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003644 return true;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003645 LCDecl = getCanonicalDecl(NewLCDecl);
3646 LCRef = NewLCRefExpr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003647 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(NewLB))
3648 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003649 if ((Ctor->isCopyOrMoveConstructor() ||
3650 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3651 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003652 NewLB = CE->getArg(0)->IgnoreParenImpCasts();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003653 LB = NewLB;
3654 return false;
3655}
3656
3657bool OpenMPIterationSpaceChecker::SetUB(Expr *NewUB, bool LessOp, bool StrictOp,
Craig Toppere335f252015-10-04 04:53:55 +00003658 SourceRange SR, SourceLocation SL) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003659 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003660 assert(LCDecl != nullptr && LB != nullptr && UB == nullptr &&
3661 Step == nullptr && !TestIsLessOp && !TestIsStrictOp);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003662 if (!NewUB)
3663 return true;
3664 UB = NewUB;
3665 TestIsLessOp = LessOp;
3666 TestIsStrictOp = StrictOp;
3667 ConditionSrcRange = SR;
3668 ConditionLoc = SL;
3669 return false;
3670}
3671
3672bool OpenMPIterationSpaceChecker::SetStep(Expr *NewStep, bool Subtract) {
3673 // State consistency checking to ensure correct usage.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003674 assert(LCDecl != nullptr && LB != nullptr && Step == nullptr);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003675 if (!NewStep)
3676 return true;
3677 if (!NewStep->isValueDependent()) {
3678 // Check that the step is integer expression.
3679 SourceLocation StepLoc = NewStep->getLocStart();
Alexey Bataev5372fb82017-08-31 23:06:52 +00003680 ExprResult Val = SemaRef.PerformOpenMPImplicitIntegerConversion(
3681 StepLoc, getExprAsWritten(NewStep));
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003682 if (Val.isInvalid())
3683 return true;
3684 NewStep = Val.get();
3685
3686 // OpenMP [2.6, Canonical Loop Form, Restrictions]
3687 // If test-expr is of form var relational-op b and relational-op is < or
3688 // <= then incr-expr must cause var to increase on each iteration of the
3689 // loop. If test-expr is of form var relational-op b and relational-op is
3690 // > or >= then incr-expr must cause var to decrease on each iteration of
3691 // the loop.
3692 // If test-expr is of form b relational-op var and relational-op is < or
3693 // <= then incr-expr must cause var to decrease on each iteration of the
3694 // loop. If test-expr is of form b relational-op var and relational-op is
3695 // > or >= then incr-expr must cause var to increase on each iteration of
3696 // the loop.
3697 llvm::APSInt Result;
3698 bool IsConstant = NewStep->isIntegerConstantExpr(Result, SemaRef.Context);
3699 bool IsUnsigned = !NewStep->getType()->hasSignedIntegerRepresentation();
3700 bool IsConstNeg =
3701 IsConstant && Result.isSigned() && (Subtract != Result.isNegative());
Alexander Musmana5f070a2014-10-01 06:03:56 +00003702 bool IsConstPos =
3703 IsConstant && Result.isSigned() && (Subtract == Result.isNegative());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003704 bool IsConstZero = IsConstant && !Result.getBoolValue();
3705 if (UB && (IsConstZero ||
3706 (TestIsLessOp ? (IsConstNeg || (IsUnsigned && Subtract))
Alexander Musmana5f070a2014-10-01 06:03:56 +00003707 : (IsConstPos || (IsUnsigned && !Subtract))))) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003708 SemaRef.Diag(NewStep->getExprLoc(),
3709 diag::err_omp_loop_incr_not_compatible)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003710 << LCDecl << TestIsLessOp << NewStep->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003711 SemaRef.Diag(ConditionLoc,
3712 diag::note_omp_loop_cond_requres_compatible_incr)
3713 << TestIsLessOp << ConditionSrcRange;
3714 return true;
3715 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00003716 if (TestIsLessOp == Subtract) {
David Majnemer9d168222016-08-05 17:44:54 +00003717 NewStep =
3718 SemaRef.CreateBuiltinUnaryOp(NewStep->getExprLoc(), UO_Minus, NewStep)
3719 .get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00003720 Subtract = !Subtract;
3721 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003722 }
3723
3724 Step = NewStep;
3725 SubtractStep = Subtract;
3726 return false;
3727}
3728
Alexey Bataev9c821032015-04-30 04:23:23 +00003729bool OpenMPIterationSpaceChecker::CheckInit(Stmt *S, bool EmitDiags) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003730 // Check init-expr for canonical loop form and save loop counter
3731 // variable - #Var and its initialization value - #LB.
3732 // OpenMP [2.6] Canonical loop form. init-expr may be one of the following:
3733 // var = lb
3734 // integer-type var = lb
3735 // random-access-iterator-type var = lb
3736 // pointer-type var = lb
3737 //
3738 if (!S) {
Alexey Bataev9c821032015-04-30 04:23:23 +00003739 if (EmitDiags) {
3740 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_init);
3741 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003742 return true;
3743 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003744 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3745 if (!ExprTemp->cleanupsHaveSideEffects())
3746 S = ExprTemp->getSubExpr();
3747
Alexander Musmana5f070a2014-10-01 06:03:56 +00003748 InitSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003749 if (Expr *E = dyn_cast<Expr>(S))
3750 S = E->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003751 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003752 if (BO->getOpcode() == BO_Assign) {
3753 auto *LHS = BO->getLHS()->IgnoreParens();
3754 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
3755 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3756 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3757 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3758 return SetLCDeclAndLB(DRE->getDecl(), DRE, BO->getRHS());
3759 }
3760 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3761 if (ME->isArrow() &&
3762 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3763 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3764 }
3765 }
David Majnemer9d168222016-08-05 17:44:54 +00003766 } else if (auto *DS = dyn_cast<DeclStmt>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003767 if (DS->isSingleDecl()) {
David Majnemer9d168222016-08-05 17:44:54 +00003768 if (auto *Var = dyn_cast_or_null<VarDecl>(DS->getSingleDecl())) {
Alexey Bataeva8899172015-08-06 12:30:57 +00003769 if (Var->hasInit() && !Var->getType()->isReferenceType()) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003770 // Accept non-canonical init form here but emit ext. warning.
Alexey Bataev9c821032015-04-30 04:23:23 +00003771 if (Var->getInitStyle() != VarDecl::CInit && EmitDiags)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003772 SemaRef.Diag(S->getLocStart(),
3773 diag::ext_omp_loop_not_canonical_init)
3774 << S->getSourceRange();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003775 return SetLCDeclAndLB(Var, nullptr, Var->getInit());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003776 }
3777 }
3778 }
David Majnemer9d168222016-08-05 17:44:54 +00003779 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003780 if (CE->getOperator() == OO_Equal) {
3781 auto *LHS = CE->getArg(0);
David Majnemer9d168222016-08-05 17:44:54 +00003782 if (auto *DRE = dyn_cast<DeclRefExpr>(LHS)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003783 if (auto *CED = dyn_cast<OMPCapturedExprDecl>(DRE->getDecl()))
3784 if (auto *ME = dyn_cast<MemberExpr>(getExprAsWritten(CED->getInit())))
3785 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3786 return SetLCDeclAndLB(DRE->getDecl(), DRE, CE->getArg(1));
3787 }
3788 if (auto *ME = dyn_cast<MemberExpr>(LHS)) {
3789 if (ME->isArrow() &&
3790 isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3791 return SetLCDeclAndLB(ME->getMemberDecl(), ME, BO->getRHS());
3792 }
3793 }
3794 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003795
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003796 if (Dependent() || SemaRef.CurContext->isDependentContext())
3797 return false;
Alexey Bataev9c821032015-04-30 04:23:23 +00003798 if (EmitDiags) {
3799 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_init)
3800 << S->getSourceRange();
3801 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003802 return true;
3803}
3804
Alexey Bataev23b69422014-06-18 07:08:49 +00003805/// \brief Ignore parenthesizes, implicit casts, copy constructor and return the
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003806/// variable (which may be the loop variable) if possible.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003807static const ValueDecl *GetInitLCDecl(Expr *E) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003808 if (!E)
Craig Topper4b566922014-06-09 02:04:02 +00003809 return nullptr;
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003810 E = getExprAsWritten(E);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003811 if (auto *CE = dyn_cast_or_null<CXXConstructExpr>(E))
3812 if (const CXXConstructorDecl *Ctor = CE->getConstructor())
Alexey Bataev0d08a7f2015-07-16 04:19:43 +00003813 if ((Ctor->isCopyOrMoveConstructor() ||
3814 Ctor->isConvertingConstructor(/*AllowExplicit=*/false)) &&
3815 CE->getNumArgs() > 0 && CE->getArg(0) != nullptr)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003816 E = CE->getArg(0)->IgnoreParenImpCasts();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003817 if (auto *DRE = dyn_cast_or_null<DeclRefExpr>(E)) {
Alexey Bataev4d4624c2017-07-20 16:47:47 +00003818 if (auto *VD = dyn_cast<VarDecl>(DRE->getDecl()))
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003819 return getCanonicalDecl(VD);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003820 }
3821 if (auto *ME = dyn_cast_or_null<MemberExpr>(E))
3822 if (ME->isArrow() && isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()))
3823 return getCanonicalDecl(ME->getMemberDecl());
3824 return nullptr;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003825}
3826
3827bool OpenMPIterationSpaceChecker::CheckCond(Expr *S) {
3828 // Check test-expr for canonical form, save upper-bound UB, flags for
3829 // less/greater and for strict/non-strict comparison.
3830 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3831 // var relational-op b
3832 // b relational-op var
3833 //
3834 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003835 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_cond) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003836 return true;
3837 }
Alexey Bataev3bed68c2015-07-15 12:14:07 +00003838 S = getExprAsWritten(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003839 SourceLocation CondLoc = S->getLocStart();
David Majnemer9d168222016-08-05 17:44:54 +00003840 if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003841 if (BO->isRelationalOp()) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003842 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003843 return SetUB(BO->getRHS(),
3844 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_LE),
3845 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3846 BO->getSourceRange(), BO->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003847 if (GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003848 return SetUB(BO->getLHS(),
3849 (BO->getOpcode() == BO_GT || BO->getOpcode() == BO_GE),
3850 (BO->getOpcode() == BO_LT || BO->getOpcode() == BO_GT),
3851 BO->getSourceRange(), BO->getOperatorLoc());
3852 }
David Majnemer9d168222016-08-05 17:44:54 +00003853 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003854 if (CE->getNumArgs() == 2) {
3855 auto Op = CE->getOperator();
3856 switch (Op) {
3857 case OO_Greater:
3858 case OO_GreaterEqual:
3859 case OO_Less:
3860 case OO_LessEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003861 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003862 return SetUB(CE->getArg(1), Op == OO_Less || Op == OO_LessEqual,
3863 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3864 CE->getOperatorLoc());
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003865 if (GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003866 return SetUB(CE->getArg(0), Op == OO_Greater || Op == OO_GreaterEqual,
3867 Op == OO_Less || Op == OO_Greater, CE->getSourceRange(),
3868 CE->getOperatorLoc());
3869 break;
3870 default:
3871 break;
3872 }
3873 }
3874 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003875 if (Dependent() || SemaRef.CurContext->isDependentContext())
3876 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003877 SemaRef.Diag(CondLoc, diag::err_omp_loop_not_canonical_cond)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003878 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003879 return true;
3880}
3881
3882bool OpenMPIterationSpaceChecker::CheckIncRHS(Expr *RHS) {
3883 // RHS of canonical loop form increment can be:
3884 // var + incr
3885 // incr + var
3886 // var - incr
3887 //
3888 RHS = RHS->IgnoreParenImpCasts();
David Majnemer9d168222016-08-05 17:44:54 +00003889 if (auto *BO = dyn_cast<BinaryOperator>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003890 if (BO->isAdditiveOp()) {
3891 bool IsAdd = BO->getOpcode() == BO_Add;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003892 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003893 return SetStep(BO->getRHS(), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003894 if (IsAdd && GetInitLCDecl(BO->getRHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003895 return SetStep(BO->getLHS(), false);
3896 }
David Majnemer9d168222016-08-05 17:44:54 +00003897 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(RHS)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003898 bool IsAdd = CE->getOperator() == OO_Plus;
3899 if ((IsAdd || CE->getOperator() == OO_Minus) && CE->getNumArgs() == 2) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003900 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003901 return SetStep(CE->getArg(1), !IsAdd);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003902 if (IsAdd && GetInitLCDecl(CE->getArg(1)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003903 return SetStep(CE->getArg(0), false);
3904 }
3905 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003906 if (Dependent() || SemaRef.CurContext->isDependentContext())
3907 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003908 SemaRef.Diag(RHS->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003909 << RHS->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003910 return true;
3911}
3912
3913bool OpenMPIterationSpaceChecker::CheckInc(Expr *S) {
3914 // Check incr-expr for canonical loop form and return true if it
3915 // does not conform.
3916 // OpenMP [2.6] Canonical loop form. Test-expr may be one of the following:
3917 // ++var
3918 // var++
3919 // --var
3920 // var--
3921 // var += incr
3922 // var -= incr
3923 // var = var + incr
3924 // var = incr + var
3925 // var = var - incr
3926 //
3927 if (!S) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003928 SemaRef.Diag(DefaultLoc, diag::err_omp_loop_not_canonical_incr) << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003929 return true;
3930 }
Tim Shen4a05bb82016-06-21 20:29:17 +00003931 if (auto *ExprTemp = dyn_cast<ExprWithCleanups>(S))
3932 if (!ExprTemp->cleanupsHaveSideEffects())
3933 S = ExprTemp->getSubExpr();
3934
Alexander Musmana5f070a2014-10-01 06:03:56 +00003935 IncrementSrcRange = S->getSourceRange();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003936 S = S->IgnoreParens();
David Majnemer9d168222016-08-05 17:44:54 +00003937 if (auto *UO = dyn_cast<UnaryOperator>(S)) {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003938 if (UO->isIncrementDecrementOp() &&
3939 GetInitLCDecl(UO->getSubExpr()) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003940 return SetStep(SemaRef
3941 .ActOnIntegerConstant(UO->getLocStart(),
3942 (UO->isDecrementOp() ? -1 : 1))
3943 .get(),
3944 false);
3945 } else if (auto *BO = dyn_cast<BinaryOperator>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003946 switch (BO->getOpcode()) {
3947 case BO_AddAssign:
3948 case BO_SubAssign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003949 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003950 return SetStep(BO->getRHS(), BO->getOpcode() == BO_SubAssign);
3951 break;
3952 case BO_Assign:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003953 if (GetInitLCDecl(BO->getLHS()) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003954 return CheckIncRHS(BO->getRHS());
3955 break;
3956 default:
3957 break;
3958 }
David Majnemer9d168222016-08-05 17:44:54 +00003959 } else if (auto *CE = dyn_cast<CXXOperatorCallExpr>(S)) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003960 switch (CE->getOperator()) {
3961 case OO_PlusPlus:
3962 case OO_MinusMinus:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003963 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
David Majnemer9d168222016-08-05 17:44:54 +00003964 return SetStep(SemaRef
3965 .ActOnIntegerConstant(
3966 CE->getLocStart(),
3967 ((CE->getOperator() == OO_MinusMinus) ? -1 : 1))
3968 .get(),
3969 false);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003970 break;
3971 case OO_PlusEqual:
3972 case OO_MinusEqual:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003973 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003974 return SetStep(CE->getArg(1), CE->getOperator() == OO_MinusEqual);
3975 break;
3976 case OO_Equal:
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003977 if (GetInitLCDecl(CE->getArg(0)) == LCDecl)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003978 return CheckIncRHS(CE->getArg(1));
3979 break;
3980 default:
3981 break;
3982 }
3983 }
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003984 if (Dependent() || SemaRef.CurContext->isDependentContext())
3985 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003986 SemaRef.Diag(S->getLocStart(), diag::err_omp_loop_not_canonical_incr)
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00003987 << S->getSourceRange() << LCDecl;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00003988 return true;
3989}
Alexander Musmana5f070a2014-10-01 06:03:56 +00003990
Alexey Bataev5a3af132016-03-29 08:58:54 +00003991static ExprResult
3992tryBuildCapture(Sema &SemaRef, Expr *Capture,
3993 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00003994 if (SemaRef.CurContext->isDependentContext())
3995 return ExprResult(Capture);
Alexey Bataev5a3af132016-03-29 08:58:54 +00003996 if (Capture->isEvaluatable(SemaRef.Context, Expr::SE_AllowSideEffects))
3997 return SemaRef.PerformImplicitConversion(
3998 Capture->IgnoreImpCasts(), Capture->getType(), Sema::AA_Converting,
3999 /*AllowExplicit=*/true);
4000 auto I = Captures.find(Capture);
4001 if (I != Captures.end())
4002 return buildCapture(SemaRef, Capture, I->second);
4003 DeclRefExpr *Ref = nullptr;
4004 ExprResult Res = buildCapture(SemaRef, Capture, Ref);
4005 Captures[Capture] = Ref;
4006 return Res;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004007}
4008
Alexander Musmana5f070a2014-10-01 06:03:56 +00004009/// \brief Build the expression to calculate the number of iterations.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004010Expr *OpenMPIterationSpaceChecker::BuildNumIterations(
4011 Scope *S, const bool LimitedType,
4012 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004013 ExprResult Diff;
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004014 auto VarType = LCDecl->getType().getNonReferenceType();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004015 if (VarType->isIntegerType() || VarType->isPointerType() ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004016 SemaRef.getLangOpts().CPlusPlus) {
4017 // Upper - Lower
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004018 auto *UBExpr = TestIsLessOp ? UB : LB;
4019 auto *LBExpr = TestIsLessOp ? LB : UB;
Alexey Bataev5a3af132016-03-29 08:58:54 +00004020 Expr *Upper = tryBuildCapture(SemaRef, UBExpr, Captures).get();
4021 Expr *Lower = tryBuildCapture(SemaRef, LBExpr, Captures).get();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004022 if (!Upper || !Lower)
4023 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004024
4025 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Sub, Upper, Lower);
4026
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004027 if (!Diff.isUsable() && VarType->getAsCXXRecordDecl()) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004028 // BuildBinOp already emitted error, this one is to point user to upper
4029 // and lower bound, and to tell what is passed to 'operator-'.
4030 SemaRef.Diag(Upper->getLocStart(), diag::err_omp_loop_diff_cxx)
4031 << Upper->getSourceRange() << Lower->getSourceRange();
4032 return nullptr;
4033 }
4034 }
4035
4036 if (!Diff.isUsable())
4037 return nullptr;
4038
4039 // Upper - Lower [- 1]
4040 if (TestIsStrictOp)
4041 Diff = SemaRef.BuildBinOp(
4042 S, DefaultLoc, BO_Sub, Diff.get(),
4043 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4044 if (!Diff.isUsable())
4045 return nullptr;
4046
4047 // Upper - Lower [- 1] + Step
Alexey Bataev5a3af132016-03-29 08:58:54 +00004048 auto NewStep = tryBuildCapture(SemaRef, Step, Captures);
4049 if (!NewStep.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004050 return nullptr;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004051 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Add, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004052 if (!Diff.isUsable())
4053 return nullptr;
4054
4055 // Parentheses (for dumping/debugging purposes only).
4056 Diff = SemaRef.ActOnParenExpr(DefaultLoc, DefaultLoc, Diff.get());
4057 if (!Diff.isUsable())
4058 return nullptr;
4059
4060 // (Upper - Lower [- 1] + Step) / Step
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004061 Diff = SemaRef.BuildBinOp(S, DefaultLoc, BO_Div, Diff.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004062 if (!Diff.isUsable())
4063 return nullptr;
4064
Alexander Musman174b3ca2014-10-06 11:16:29 +00004065 // OpenMP runtime requires 32-bit or 64-bit loop variables.
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004066 QualType Type = Diff.get()->getType();
4067 auto &C = SemaRef.Context;
4068 bool UseVarType = VarType->hasIntegerRepresentation() &&
4069 C.getTypeSize(Type) > C.getTypeSize(VarType);
4070 if (!Type->isIntegerType() || UseVarType) {
4071 unsigned NewSize =
4072 UseVarType ? C.getTypeSize(VarType) : C.getTypeSize(Type);
4073 bool IsSigned = UseVarType ? VarType->hasSignedIntegerRepresentation()
4074 : Type->hasSignedIntegerRepresentation();
4075 Type = C.getIntTypeForBitwidth(NewSize, IsSigned);
Alexey Bataev11481f52016-02-17 10:29:05 +00004076 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), Type)) {
4077 Diff = SemaRef.PerformImplicitConversion(
4078 Diff.get(), Type, Sema::AA_Converting, /*AllowExplicit=*/true);
4079 if (!Diff.isUsable())
4080 return nullptr;
4081 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004082 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004083 if (LimitedType) {
Alexander Musman174b3ca2014-10-06 11:16:29 +00004084 unsigned NewSize = (C.getTypeSize(Type) > 32) ? 64 : 32;
4085 if (NewSize != C.getTypeSize(Type)) {
4086 if (NewSize < C.getTypeSize(Type)) {
4087 assert(NewSize == 64 && "incorrect loop var size");
4088 SemaRef.Diag(DefaultLoc, diag::warn_omp_loop_64_bit_var)
4089 << InitSrcRange << ConditionSrcRange;
4090 }
4091 QualType NewType = C.getIntTypeForBitwidth(
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004092 NewSize, Type->hasSignedIntegerRepresentation() ||
4093 C.getTypeSize(Type) < NewSize);
Alexey Bataev11481f52016-02-17 10:29:05 +00004094 if (!SemaRef.Context.hasSameType(Diff.get()->getType(), NewType)) {
4095 Diff = SemaRef.PerformImplicitConversion(Diff.get(), NewType,
4096 Sema::AA_Converting, true);
4097 if (!Diff.isUsable())
4098 return nullptr;
4099 }
Alexander Musman174b3ca2014-10-06 11:16:29 +00004100 }
4101 }
4102
Alexander Musmana5f070a2014-10-01 06:03:56 +00004103 return Diff.get();
4104}
4105
Alexey Bataev5a3af132016-03-29 08:58:54 +00004106Expr *OpenMPIterationSpaceChecker::BuildPreCond(
4107 Scope *S, Expr *Cond,
4108 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) const {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004109 // Try to build LB <op> UB, where <op> is <, >, <=, or >=.
4110 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4111 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004112
Alexey Bataev5a3af132016-03-29 08:58:54 +00004113 auto NewLB = tryBuildCapture(SemaRef, LB, Captures);
4114 auto NewUB = tryBuildCapture(SemaRef, UB, Captures);
4115 if (!NewLB.isUsable() || !NewUB.isUsable())
4116 return nullptr;
4117
Alexey Bataev62dbb972015-04-22 11:59:37 +00004118 auto CondExpr = SemaRef.BuildBinOp(
4119 S, DefaultLoc, TestIsLessOp ? (TestIsStrictOp ? BO_LT : BO_LE)
4120 : (TestIsStrictOp ? BO_GT : BO_GE),
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004121 NewLB.get(), NewUB.get());
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004122 if (CondExpr.isUsable()) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004123 if (!SemaRef.Context.hasSameUnqualifiedType(CondExpr.get()->getType(),
4124 SemaRef.Context.BoolTy))
Alexey Bataev11481f52016-02-17 10:29:05 +00004125 CondExpr = SemaRef.PerformImplicitConversion(
4126 CondExpr.get(), SemaRef.Context.BoolTy, /*Action=*/Sema::AA_Casting,
4127 /*AllowExplicit=*/true);
Alexey Bataev3bed68c2015-07-15 12:14:07 +00004128 }
Alexey Bataev62dbb972015-04-22 11:59:37 +00004129 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4130 // Otherwise use original loop conditon and evaluate it in runtime.
4131 return CondExpr.isUsable() ? CondExpr.get() : Cond;
4132}
4133
Alexander Musmana5f070a2014-10-01 06:03:56 +00004134/// \brief Build reference expression to the counter be used for codegen.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004135DeclRefExpr *OpenMPIterationSpaceChecker::BuildCounterVar(
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004136 llvm::MapVector<Expr *, DeclRefExpr *> &Captures, DSAStackTy &DSA) const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004137 auto *VD = dyn_cast<VarDecl>(LCDecl);
4138 if (!VD) {
4139 VD = SemaRef.IsOpenMPCapturedDecl(LCDecl);
4140 auto *Ref = buildDeclRefExpr(
4141 SemaRef, VD, VD->getType().getNonReferenceType(), DefaultLoc);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004142 DSAStackTy::DSAVarData Data = DSA.getTopDSA(LCDecl, /*FromParent=*/false);
4143 // If the loop control decl is explicitly marked as private, do not mark it
4144 // as captured again.
4145 if (!isOpenMPPrivate(Data.CKind) || !Data.RefExpr)
4146 Captures.insert(std::make_pair(LCRef, Ref));
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004147 return Ref;
4148 }
4149 return buildDeclRefExpr(SemaRef, VD, VD->getType().getNonReferenceType(),
Alexey Bataeva8899172015-08-06 12:30:57 +00004150 DefaultLoc);
4151}
4152
4153Expr *OpenMPIterationSpaceChecker::BuildPrivateCounterVar() const {
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004154 if (LCDecl && !LCDecl->isInvalidDecl()) {
4155 auto Type = LCDecl->getType().getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00004156 auto *PrivateVar =
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004157 buildVarDecl(SemaRef, DefaultLoc, Type, LCDecl->getName(),
4158 LCDecl->hasAttrs() ? &LCDecl->getAttrs() : nullptr);
Alexey Bataeva8899172015-08-06 12:30:57 +00004159 if (PrivateVar->isInvalidDecl())
4160 return nullptr;
4161 return buildDeclRefExpr(SemaRef, PrivateVar, Type, DefaultLoc);
4162 }
4163 return nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004164}
4165
Samuel Antao4c8035b2016-12-12 18:00:20 +00004166/// \brief Build initialization of the counter to be used for codegen.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004167Expr *OpenMPIterationSpaceChecker::BuildCounterInit() const { return LB; }
4168
4169/// \brief Build step of the counter be used for codegen.
4170Expr *OpenMPIterationSpaceChecker::BuildCounterStep() const { return Step; }
4171
4172/// \brief Iteration space of a single for loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004173struct LoopIterationSpace final {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004174 /// \brief Condition of the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004175 Expr *PreCond = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004176 /// \brief This expression calculates the number of iterations in the loop.
4177 /// It is always possible to calculate it before starting the loop.
Alexey Bataev8b427062016-05-25 12:36:08 +00004178 Expr *NumIterations = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004179 /// \brief The loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004180 Expr *CounterVar = nullptr;
Alexey Bataeva8899172015-08-06 12:30:57 +00004181 /// \brief Private loop counter variable.
Alexey Bataev8b427062016-05-25 12:36:08 +00004182 Expr *PrivateCounterVar = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004183 /// \brief This is initializer for the initial value of #CounterVar.
Alexey Bataev8b427062016-05-25 12:36:08 +00004184 Expr *CounterInit = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004185 /// \brief This is step for the #CounterVar used to generate its update:
4186 /// #CounterVar = #CounterInit + #CounterStep * CurrentIteration.
Alexey Bataev8b427062016-05-25 12:36:08 +00004187 Expr *CounterStep = nullptr;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004188 /// \brief Should step be subtracted?
Alexey Bataev8b427062016-05-25 12:36:08 +00004189 bool Subtract = false;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004190 /// \brief Source range of the loop init.
4191 SourceRange InitSrcRange;
4192 /// \brief Source range of the loop condition.
4193 SourceRange CondSrcRange;
4194 /// \brief Source range of the loop increment.
4195 SourceRange IncSrcRange;
4196};
4197
Alexey Bataev23b69422014-06-18 07:08:49 +00004198} // namespace
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004199
Alexey Bataev9c821032015-04-30 04:23:23 +00004200void Sema::ActOnOpenMPLoopInitialization(SourceLocation ForLoc, Stmt *Init) {
4201 assert(getLangOpts().OpenMP && "OpenMP is not active.");
4202 assert(Init && "Expected loop in canonical form.");
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004203 unsigned AssociatedLoops = DSAStack->getAssociatedLoops();
4204 if (AssociatedLoops > 0 &&
Alexey Bataev9c821032015-04-30 04:23:23 +00004205 isOpenMPLoopDirective(DSAStack->getCurrentDirective())) {
4206 OpenMPIterationSpaceChecker ISC(*this, ForLoc);
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004207 if (!ISC.CheckInit(Init, /*EmitDiags=*/false)) {
4208 if (auto *D = ISC.GetLoopDecl()) {
4209 auto *VD = dyn_cast<VarDecl>(D);
4210 if (!VD) {
4211 if (auto *Private = IsOpenMPCapturedDecl(D))
4212 VD = Private;
4213 else {
4214 auto *Ref = buildCapture(*this, D, ISC.GetLoopDeclRefExpr(),
4215 /*WithInit=*/false);
4216 VD = cast<VarDecl>(Ref->getDecl());
4217 }
4218 }
4219 DSAStack->addLoopControlVariable(D, VD);
4220 }
4221 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00004222 DSAStack->setAssociatedLoops(AssociatedLoops - 1);
Alexey Bataev9c821032015-04-30 04:23:23 +00004223 }
4224}
4225
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004226/// \brief Called on a for stmt to check and extract its iteration space
4227/// for further processing (such as collapsing).
Alexey Bataev4acb8592014-07-07 13:01:15 +00004228static bool CheckOpenMPIterationSpace(
4229 OpenMPDirectiveKind DKind, Stmt *S, Sema &SemaRef, DSAStackTy &DSA,
4230 unsigned CurrentNestedLoopCount, unsigned NestedLoopCount,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004231 Expr *CollapseLoopCountExpr, Expr *OrderedLoopCountExpr,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004232 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004233 LoopIterationSpace &ResultIterSpace,
4234 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004235 // OpenMP [2.6, Canonical Loop Form]
4236 // for (init-expr; test-expr; incr-expr) structured-block
David Majnemer9d168222016-08-05 17:44:54 +00004237 auto *For = dyn_cast_or_null<ForStmt>(S);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004238 if (!For) {
4239 SemaRef.Diag(S->getLocStart(), diag::err_omp_not_for)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004240 << (CollapseLoopCountExpr != nullptr || OrderedLoopCountExpr != nullptr)
4241 << getOpenMPDirectiveName(DKind) << NestedLoopCount
4242 << (CurrentNestedLoopCount > 0) << CurrentNestedLoopCount;
4243 if (NestedLoopCount > 1) {
4244 if (CollapseLoopCountExpr && OrderedLoopCountExpr)
4245 SemaRef.Diag(DSA.getConstructLoc(),
4246 diag::note_omp_collapse_ordered_expr)
4247 << 2 << CollapseLoopCountExpr->getSourceRange()
4248 << OrderedLoopCountExpr->getSourceRange();
4249 else if (CollapseLoopCountExpr)
4250 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4251 diag::note_omp_collapse_ordered_expr)
4252 << 0 << CollapseLoopCountExpr->getSourceRange();
4253 else
4254 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4255 diag::note_omp_collapse_ordered_expr)
4256 << 1 << OrderedLoopCountExpr->getSourceRange();
4257 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004258 return true;
4259 }
4260 assert(For->getBody());
4261
4262 OpenMPIterationSpaceChecker ISC(SemaRef, For->getForLoc());
4263
4264 // Check init.
Alexey Bataevdf9b1592014-06-25 04:09:13 +00004265 auto Init = For->getInit();
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004266 if (ISC.CheckInit(Init))
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004267 return true;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004268
4269 bool HasErrors = false;
4270
4271 // Check loop variable's type.
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004272 if (auto *LCDecl = ISC.GetLoopDecl()) {
4273 auto *LoopDeclRefExpr = ISC.GetLoopDeclRefExpr();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004274
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004275 // OpenMP [2.6, Canonical Loop Form]
4276 // Var is one of the following:
4277 // A variable of signed or unsigned integer type.
4278 // For C++, a variable of a random access iterator type.
4279 // For C, a variable of a pointer type.
4280 auto VarType = LCDecl->getType().getNonReferenceType();
4281 if (!VarType->isDependentType() && !VarType->isIntegerType() &&
4282 !VarType->isPointerType() &&
4283 !(SemaRef.getLangOpts().CPlusPlus && VarType->isOverloadableType())) {
4284 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_variable_type)
4285 << SemaRef.getLangOpts().CPlusPlus;
4286 HasErrors = true;
4287 }
4288
4289 // OpenMP, 2.14.1.1 Data-sharing Attribute Rules for Variables Referenced in
4290 // a Construct
4291 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4292 // parallel for construct is (are) private.
4293 // The loop iteration variable in the associated for-loop of a simd
4294 // construct with just one associated for-loop is linear with a
4295 // constant-linear-step that is the increment of the associated for-loop.
4296 // Exclude loop var from the list of variables with implicitly defined data
4297 // sharing attributes.
4298 VarsWithImplicitDSA.erase(LCDecl);
4299
4300 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
4301 // in a Construct, C/C++].
4302 // The loop iteration variable in the associated for-loop of a simd
4303 // construct with just one associated for-loop may be listed in a linear
4304 // clause with a constant-linear-step that is the increment of the
4305 // associated for-loop.
4306 // The loop iteration variable(s) in the associated for-loop(s) of a for or
4307 // parallel for construct may be listed in a private or lastprivate clause.
4308 DSAStackTy::DSAVarData DVar = DSA.getTopDSA(LCDecl, false);
4309 // If LoopVarRefExpr is nullptr it means the corresponding loop variable is
4310 // declared in the loop and it is predetermined as a private.
4311 auto PredeterminedCKind =
4312 isOpenMPSimdDirective(DKind)
4313 ? ((NestedLoopCount == 1) ? OMPC_linear : OMPC_lastprivate)
4314 : OMPC_private;
4315 if (((isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4316 DVar.CKind != PredeterminedCKind) ||
4317 ((isOpenMPWorksharingDirective(DKind) || DKind == OMPD_taskloop ||
4318 isOpenMPDistributeDirective(DKind)) &&
4319 !isOpenMPSimdDirective(DKind) && DVar.CKind != OMPC_unknown &&
4320 DVar.CKind != OMPC_private && DVar.CKind != OMPC_lastprivate)) &&
4321 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
4322 SemaRef.Diag(Init->getLocStart(), diag::err_omp_loop_var_dsa)
4323 << getOpenMPClauseName(DVar.CKind) << getOpenMPDirectiveName(DKind)
4324 << getOpenMPClauseName(PredeterminedCKind);
4325 if (DVar.RefExpr == nullptr)
4326 DVar.CKind = PredeterminedCKind;
4327 ReportOriginalDSA(SemaRef, &DSA, LCDecl, DVar, /*IsLoopIterVar=*/true);
4328 HasErrors = true;
4329 } else if (LoopDeclRefExpr != nullptr) {
4330 // Make the loop iteration variable private (for worksharing constructs),
4331 // linear (for simd directives with the only one associated loop) or
4332 // lastprivate (for simd directives with several collapsed or ordered
4333 // loops).
4334 if (DVar.CKind == OMPC_unknown)
Alexey Bataev7ace49d2016-05-17 08:55:33 +00004335 DVar = DSA.hasDSA(LCDecl, isOpenMPPrivate,
4336 [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataevc6ad97a2016-04-01 09:23:34 +00004337 /*FromParent=*/false);
4338 DSA.addDSA(LCDecl, LoopDeclRefExpr, PredeterminedCKind);
4339 }
4340
4341 assert(isOpenMPLoopDirective(DKind) && "DSA for non-loop vars");
4342
4343 // Check test-expr.
4344 HasErrors |= ISC.CheckCond(For->getCond());
4345
4346 // Check incr-expr.
4347 HasErrors |= ISC.CheckInc(For->getInc());
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004348 }
4349
Alexander Musmana5f070a2014-10-01 06:03:56 +00004350 if (ISC.Dependent() || SemaRef.CurContext->isDependentContext() || HasErrors)
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004351 return HasErrors;
4352
Alexander Musmana5f070a2014-10-01 06:03:56 +00004353 // Build the loop's iteration space representation.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004354 ResultIterSpace.PreCond =
4355 ISC.BuildPreCond(DSA.getCurScope(), For->getCond(), Captures);
Alexander Musman174b3ca2014-10-06 11:16:29 +00004356 ResultIterSpace.NumIterations = ISC.BuildNumIterations(
Alexey Bataev5a3af132016-03-29 08:58:54 +00004357 DSA.getCurScope(),
4358 (isOpenMPWorksharingDirective(DKind) ||
4359 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind)),
4360 Captures);
Alexey Bataev5dff95c2016-04-22 03:56:56 +00004361 ResultIterSpace.CounterVar = ISC.BuildCounterVar(Captures, DSA);
Alexey Bataeva8899172015-08-06 12:30:57 +00004362 ResultIterSpace.PrivateCounterVar = ISC.BuildPrivateCounterVar();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004363 ResultIterSpace.CounterInit = ISC.BuildCounterInit();
4364 ResultIterSpace.CounterStep = ISC.BuildCounterStep();
4365 ResultIterSpace.InitSrcRange = ISC.GetInitSrcRange();
4366 ResultIterSpace.CondSrcRange = ISC.GetConditionSrcRange();
4367 ResultIterSpace.IncSrcRange = ISC.GetIncrementSrcRange();
4368 ResultIterSpace.Subtract = ISC.ShouldSubtractStep();
4369
Alexey Bataev62dbb972015-04-22 11:59:37 +00004370 HasErrors |= (ResultIterSpace.PreCond == nullptr ||
4371 ResultIterSpace.NumIterations == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004372 ResultIterSpace.CounterVar == nullptr ||
Alexey Bataeva8899172015-08-06 12:30:57 +00004373 ResultIterSpace.PrivateCounterVar == nullptr ||
Alexander Musmana5f070a2014-10-01 06:03:56 +00004374 ResultIterSpace.CounterInit == nullptr ||
4375 ResultIterSpace.CounterStep == nullptr);
4376
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004377 return HasErrors;
4378}
4379
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004380/// \brief Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004381static ExprResult
4382BuildCounterInit(Sema &SemaRef, Scope *S, SourceLocation Loc, ExprResult VarRef,
4383 ExprResult Start,
4384 llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004385 // Build 'VarRef = Start.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004386 auto NewStart = tryBuildCapture(SemaRef, Start.get(), Captures);
4387 if (!NewStart.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004388 return ExprError();
Alexey Bataev11481f52016-02-17 10:29:05 +00004389 if (!SemaRef.Context.hasSameType(NewStart.get()->getType(),
Alexey Bataev11481f52016-02-17 10:29:05 +00004390 VarRef.get()->getType())) {
4391 NewStart = SemaRef.PerformImplicitConversion(
4392 NewStart.get(), VarRef.get()->getType(), Sema::AA_Converting,
4393 /*AllowExplicit=*/true);
4394 if (!NewStart.isUsable())
4395 return ExprError();
4396 }
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004397
4398 auto Init =
4399 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4400 return Init;
4401}
4402
Alexander Musmana5f070a2014-10-01 06:03:56 +00004403/// \brief Build 'VarRef = Start + Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004404static ExprResult
4405BuildCounterUpdate(Sema &SemaRef, Scope *S, SourceLocation Loc,
4406 ExprResult VarRef, ExprResult Start, ExprResult Iter,
4407 ExprResult Step, bool Subtract,
4408 llvm::MapVector<Expr *, DeclRefExpr *> *Captures = nullptr) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004409 // Add parentheses (for debugging purposes only).
4410 Iter = SemaRef.ActOnParenExpr(Loc, Loc, Iter.get());
4411 if (!VarRef.isUsable() || !Start.isUsable() || !Iter.isUsable() ||
4412 !Step.isUsable())
4413 return ExprError();
4414
Alexey Bataev5a3af132016-03-29 08:58:54 +00004415 ExprResult NewStep = Step;
4416 if (Captures)
4417 NewStep = tryBuildCapture(SemaRef, Step.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004418 if (NewStep.isInvalid())
4419 return ExprError();
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004420 ExprResult Update =
4421 SemaRef.BuildBinOp(S, Loc, BO_Mul, Iter.get(), NewStep.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004422 if (!Update.isUsable())
4423 return ExprError();
4424
Alexey Bataevc0214e02016-02-16 12:13:49 +00004425 // Try to build 'VarRef = Start, VarRef (+|-)= Iter * Step' or
4426 // 'VarRef = Start (+|-) Iter * Step'.
Alexey Bataev5a3af132016-03-29 08:58:54 +00004427 ExprResult NewStart = Start;
4428 if (Captures)
4429 NewStart = tryBuildCapture(SemaRef, Start.get(), *Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004430 if (NewStart.isInvalid())
4431 return ExprError();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004432
Alexey Bataevc0214e02016-02-16 12:13:49 +00004433 // First attempt: try to build 'VarRef = Start, VarRef += Iter * Step'.
4434 ExprResult SavedUpdate = Update;
4435 ExprResult UpdateVal;
4436 if (VarRef.get()->getType()->isOverloadableType() ||
4437 NewStart.get()->getType()->isOverloadableType() ||
4438 Update.get()->getType()->isOverloadableType()) {
4439 bool Suppress = SemaRef.getDiagnostics().getSuppressAllDiagnostics();
4440 SemaRef.getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
4441 Update =
4442 SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), NewStart.get());
4443 if (Update.isUsable()) {
4444 UpdateVal =
4445 SemaRef.BuildBinOp(S, Loc, Subtract ? BO_SubAssign : BO_AddAssign,
4446 VarRef.get(), SavedUpdate.get());
4447 if (UpdateVal.isUsable()) {
4448 Update = SemaRef.CreateBuiltinBinOp(Loc, BO_Comma, Update.get(),
4449 UpdateVal.get());
4450 }
4451 }
4452 SemaRef.getDiagnostics().setSuppressAllDiagnostics(Suppress);
4453 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004454
Alexey Bataevc0214e02016-02-16 12:13:49 +00004455 // Second attempt: try to build 'VarRef = Start (+|-) Iter * Step'.
4456 if (!Update.isUsable() || !UpdateVal.isUsable()) {
4457 Update = SemaRef.BuildBinOp(S, Loc, Subtract ? BO_Sub : BO_Add,
4458 NewStart.get(), SavedUpdate.get());
4459 if (!Update.isUsable())
4460 return ExprError();
4461
Alexey Bataev11481f52016-02-17 10:29:05 +00004462 if (!SemaRef.Context.hasSameType(Update.get()->getType(),
4463 VarRef.get()->getType())) {
4464 Update = SemaRef.PerformImplicitConversion(
4465 Update.get(), VarRef.get()->getType(), Sema::AA_Converting, true);
4466 if (!Update.isUsable())
4467 return ExprError();
4468 }
Alexey Bataevc0214e02016-02-16 12:13:49 +00004469
4470 Update = SemaRef.BuildBinOp(S, Loc, BO_Assign, VarRef.get(), Update.get());
4471 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004472 return Update;
4473}
4474
4475/// \brief Convert integer expression \a E to make it have at least \a Bits
4476/// bits.
David Majnemer9d168222016-08-05 17:44:54 +00004477static ExprResult WidenIterationCount(unsigned Bits, Expr *E, Sema &SemaRef) {
Alexander Musmana5f070a2014-10-01 06:03:56 +00004478 if (E == nullptr)
4479 return ExprError();
4480 auto &C = SemaRef.Context;
4481 QualType OldType = E->getType();
4482 unsigned HasBits = C.getTypeSize(OldType);
4483 if (HasBits >= Bits)
4484 return ExprResult(E);
4485 // OK to convert to signed, because new type has more bits than old.
4486 QualType NewType = C.getIntTypeForBitwidth(Bits, /* Signed */ true);
4487 return SemaRef.PerformImplicitConversion(E, NewType, Sema::AA_Converting,
4488 true);
4489}
4490
4491/// \brief Check if the given expression \a E is a constant integer that fits
4492/// into \a Bits bits.
4493static bool FitsInto(unsigned Bits, bool Signed, Expr *E, Sema &SemaRef) {
4494 if (E == nullptr)
4495 return false;
4496 llvm::APSInt Result;
4497 if (E->isIntegerConstantExpr(Result, SemaRef.Context))
4498 return Signed ? Result.isSignedIntN(Bits) : Result.isIntN(Bits);
4499 return false;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004500}
4501
Alexey Bataev5a3af132016-03-29 08:58:54 +00004502/// Build preinits statement for the given declarations.
4503static Stmt *buildPreInits(ASTContext &Context,
Alexey Bataevc5514062017-10-25 15:44:52 +00004504 MutableArrayRef<Decl *> PreInits) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004505 if (!PreInits.empty()) {
4506 return new (Context) DeclStmt(
4507 DeclGroupRef::Create(Context, PreInits.begin(), PreInits.size()),
4508 SourceLocation(), SourceLocation());
4509 }
4510 return nullptr;
4511}
4512
4513/// Build preinits statement for the given declarations.
Alexey Bataevc5514062017-10-25 15:44:52 +00004514static Stmt *
4515buildPreInits(ASTContext &Context,
4516 const llvm::MapVector<Expr *, DeclRefExpr *> &Captures) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004517 if (!Captures.empty()) {
4518 SmallVector<Decl *, 16> PreInits;
4519 for (auto &Pair : Captures)
4520 PreInits.push_back(Pair.second->getDecl());
4521 return buildPreInits(Context, PreInits);
4522 }
4523 return nullptr;
4524}
4525
4526/// Build postupdate expression for the given list of postupdates expressions.
4527static Expr *buildPostUpdate(Sema &S, ArrayRef<Expr *> PostUpdates) {
4528 Expr *PostUpdate = nullptr;
4529 if (!PostUpdates.empty()) {
4530 for (auto *E : PostUpdates) {
4531 Expr *ConvE = S.BuildCStyleCastExpr(
4532 E->getExprLoc(),
4533 S.Context.getTrivialTypeSourceInfo(S.Context.VoidTy),
4534 E->getExprLoc(), E)
4535 .get();
4536 PostUpdate = PostUpdate
4537 ? S.CreateBuiltinBinOp(ConvE->getExprLoc(), BO_Comma,
4538 PostUpdate, ConvE)
4539 .get()
4540 : ConvE;
4541 }
4542 }
4543 return PostUpdate;
4544}
4545
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004546/// \brief Called on a for stmt to check itself and nested loops (if any).
Alexey Bataevabfc0692014-06-25 06:52:00 +00004547/// \return Returns 0 if one of the collapsed stmts is not canonical for loop,
4548/// number of collapsed loops otherwise.
Alexey Bataev4acb8592014-07-07 13:01:15 +00004549static unsigned
Alexey Bataev10e775f2015-07-30 11:36:16 +00004550CheckOpenMPLoop(OpenMPDirectiveKind DKind, Expr *CollapseLoopCountExpr,
4551 Expr *OrderedLoopCountExpr, Stmt *AStmt, Sema &SemaRef,
4552 DSAStackTy &DSA,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00004553 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA,
Alexander Musmanc6388682014-12-15 07:07:06 +00004554 OMPLoopDirective::HelperExprs &Built) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004555 unsigned NestedLoopCount = 1;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004556 if (CollapseLoopCountExpr) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004557 // Found 'collapse' clause - calculate collapse number.
4558 llvm::APSInt Result;
Alexey Bataev10e775f2015-07-30 11:36:16 +00004559 if (CollapseLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext()))
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004560 NestedLoopCount = Result.getLimitedValue();
Alexey Bataev10e775f2015-07-30 11:36:16 +00004561 }
4562 if (OrderedLoopCountExpr) {
4563 // Found 'ordered' clause - calculate collapse number.
4564 llvm::APSInt Result;
Alexey Bataev7b6bc882015-11-26 07:50:39 +00004565 if (OrderedLoopCountExpr->EvaluateAsInt(Result, SemaRef.getASTContext())) {
4566 if (Result.getLimitedValue() < NestedLoopCount) {
4567 SemaRef.Diag(OrderedLoopCountExpr->getExprLoc(),
4568 diag::err_omp_wrong_ordered_loop_count)
4569 << OrderedLoopCountExpr->getSourceRange();
4570 SemaRef.Diag(CollapseLoopCountExpr->getExprLoc(),
4571 diag::note_collapse_loop_count)
4572 << CollapseLoopCountExpr->getSourceRange();
4573 }
4574 NestedLoopCount = Result.getLimitedValue();
4575 }
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004576 }
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004577 // This is helper routine for loop directives (e.g., 'for', 'simd',
4578 // 'for simd', etc.).
Alexey Bataev5a3af132016-03-29 08:58:54 +00004579 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004580 SmallVector<LoopIterationSpace, 4> IterSpaces;
4581 IterSpaces.resize(NestedLoopCount);
4582 Stmt *CurStmt = AStmt->IgnoreContainers(/* IgnoreCaptured */ true);
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004583 for (unsigned Cnt = 0; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataeve2f07d42014-06-24 12:55:56 +00004584 if (CheckOpenMPIterationSpace(DKind, CurStmt, SemaRef, DSA, Cnt,
Alexey Bataev10e775f2015-07-30 11:36:16 +00004585 NestedLoopCount, CollapseLoopCountExpr,
4586 OrderedLoopCountExpr, VarsWithImplicitDSA,
Alexey Bataev5a3af132016-03-29 08:58:54 +00004587 IterSpaces[Cnt], Captures))
Alexey Bataevabfc0692014-06-25 06:52:00 +00004588 return 0;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004589 // Move on to the next nested for loop, or to the loop body.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004590 // OpenMP [2.8.1, simd construct, Restrictions]
4591 // All loops associated with the construct must be perfectly nested; that
4592 // is, there must be no intervening code nor any OpenMP directive between
4593 // any two loops.
4594 CurStmt = cast<ForStmt>(CurStmt)->getBody()->IgnoreContainers();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00004595 }
4596
Alexander Musmana5f070a2014-10-01 06:03:56 +00004597 Built.clear(/* size */ NestedLoopCount);
4598
4599 if (SemaRef.CurContext->isDependentContext())
4600 return NestedLoopCount;
4601
4602 // An example of what is generated for the following code:
4603 //
Alexey Bataev10e775f2015-07-30 11:36:16 +00004604 // #pragma omp simd collapse(2) ordered(2)
Alexander Musmana5f070a2014-10-01 06:03:56 +00004605 // for (i = 0; i < NI; ++i)
Alexey Bataev10e775f2015-07-30 11:36:16 +00004606 // for (k = 0; k < NK; ++k)
4607 // for (j = J0; j < NJ; j+=2) {
4608 // <loop body>
4609 // }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004610 //
4611 // We generate the code below.
4612 // Note: the loop body may be outlined in CodeGen.
4613 // Note: some counters may be C++ classes, operator- is used to find number of
4614 // iterations and operator+= to calculate counter value.
4615 // Note: decltype(NumIterations) must be integer type (in 'omp for', only i32
4616 // or i64 is currently supported).
4617 //
4618 // #define NumIterations (NI * ((NJ - J0 - 1 + 2) / 2))
4619 // for (int[32|64]_t IV = 0; IV < NumIterations; ++IV ) {
4620 // .local.i = IV / ((NJ - J0 - 1 + 2) / 2);
4621 // .local.j = J0 + (IV % ((NJ - J0 - 1 + 2) / 2)) * 2;
4622 // // similar updates for vars in clauses (e.g. 'linear')
4623 // <loop body (using local i and j)>
4624 // }
4625 // i = NI; // assign final values of counters
4626 // j = NJ;
4627 //
4628
4629 // Last iteration number is (I1 * I2 * ... In) - 1, where I1, I2 ... In are
4630 // the iteration counts of the collapsed for loops.
Alexey Bataev62dbb972015-04-22 11:59:37 +00004631 // Precondition tests if there is at least one iteration (all conditions are
4632 // true).
4633 auto PreCond = ExprResult(IterSpaces[0].PreCond);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004634 auto N0 = IterSpaces[0].NumIterations;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004635 ExprResult LastIteration32 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004636 32 /* Bits */, SemaRef
4637 .PerformImplicitConversion(
4638 N0->IgnoreImpCasts(), N0->getType(),
4639 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004640 .get(),
4641 SemaRef);
4642 ExprResult LastIteration64 = WidenIterationCount(
David Majnemer9d168222016-08-05 17:44:54 +00004643 64 /* Bits */, SemaRef
4644 .PerformImplicitConversion(
4645 N0->IgnoreImpCasts(), N0->getType(),
4646 Sema::AA_Converting, /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004647 .get(),
4648 SemaRef);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004649
4650 if (!LastIteration32.isUsable() || !LastIteration64.isUsable())
4651 return NestedLoopCount;
4652
4653 auto &C = SemaRef.Context;
4654 bool AllCountsNeedLessThan32Bits = C.getTypeSize(N0->getType()) < 32;
4655
4656 Scope *CurScope = DSA.getCurScope();
4657 for (unsigned Cnt = 1; Cnt < NestedLoopCount; ++Cnt) {
Alexey Bataev62dbb972015-04-22 11:59:37 +00004658 if (PreCond.isUsable()) {
Alexey Bataeva7206b92016-12-20 16:51:02 +00004659 PreCond =
4660 SemaRef.BuildBinOp(CurScope, PreCond.get()->getExprLoc(), BO_LAnd,
4661 PreCond.get(), IterSpaces[Cnt].PreCond);
Alexey Bataev62dbb972015-04-22 11:59:37 +00004662 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004663 auto N = IterSpaces[Cnt].NumIterations;
Alexey Bataeva7206b92016-12-20 16:51:02 +00004664 SourceLocation Loc = N->getExprLoc();
Alexander Musmana5f070a2014-10-01 06:03:56 +00004665 AllCountsNeedLessThan32Bits &= C.getTypeSize(N->getType()) < 32;
4666 if (LastIteration32.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004667 LastIteration32 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004668 CurScope, Loc, BO_Mul, LastIteration32.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004669 SemaRef
4670 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4671 Sema::AA_Converting,
4672 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004673 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004674 if (LastIteration64.isUsable())
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004675 LastIteration64 = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004676 CurScope, Loc, BO_Mul, LastIteration64.get(),
David Majnemer9d168222016-08-05 17:44:54 +00004677 SemaRef
4678 .PerformImplicitConversion(N->IgnoreImpCasts(), N->getType(),
4679 Sema::AA_Converting,
4680 /*AllowExplicit=*/true)
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004681 .get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00004682 }
4683
4684 // Choose either the 32-bit or 64-bit version.
4685 ExprResult LastIteration = LastIteration64;
4686 if (LastIteration32.isUsable() &&
4687 C.getTypeSize(LastIteration32.get()->getType()) == 32 &&
4688 (AllCountsNeedLessThan32Bits || NestedLoopCount == 1 ||
4689 FitsInto(
4690 32 /* Bits */,
4691 LastIteration32.get()->getType()->hasSignedIntegerRepresentation(),
4692 LastIteration64.get(), SemaRef)))
4693 LastIteration = LastIteration32;
Alexey Bataev7292c292016-04-25 12:22:29 +00004694 QualType VType = LastIteration.get()->getType();
4695 QualType RealVType = VType;
4696 QualType StrideVType = VType;
4697 if (isOpenMPTaskLoopDirective(DKind)) {
4698 VType =
4699 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/0);
4700 StrideVType =
4701 SemaRef.Context.getIntTypeForBitwidth(/*DestWidth=*/64, /*Signed=*/1);
4702 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004703
4704 if (!LastIteration.isUsable())
4705 return 0;
4706
4707 // Save the number of iterations.
4708 ExprResult NumIterations = LastIteration;
4709 {
4710 LastIteration = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004711 CurScope, LastIteration.get()->getExprLoc(), BO_Sub,
4712 LastIteration.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004713 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4714 if (!LastIteration.isUsable())
4715 return 0;
4716 }
4717
4718 // Calculate the last iteration number beforehand instead of doing this on
4719 // each iteration. Do not do this if the number of iterations may be kfold-ed.
4720 llvm::APSInt Result;
4721 bool IsConstant =
4722 LastIteration.get()->isIntegerConstantExpr(Result, SemaRef.Context);
4723 ExprResult CalcLastIteration;
4724 if (!IsConstant) {
Alexey Bataev5a3af132016-03-29 08:58:54 +00004725 ExprResult SaveRef =
4726 tryBuildCapture(SemaRef, LastIteration.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004727 LastIteration = SaveRef;
4728
4729 // Prepare SaveRef + 1.
4730 NumIterations = SemaRef.BuildBinOp(
Alexey Bataeva7206b92016-12-20 16:51:02 +00004731 CurScope, SaveRef.get()->getExprLoc(), BO_Add, SaveRef.get(),
Alexander Musmana5f070a2014-10-01 06:03:56 +00004732 SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get());
4733 if (!NumIterations.isUsable())
4734 return 0;
4735 }
4736
4737 SourceLocation InitLoc = IterSpaces[0].InitSrcRange.getBegin();
4738
David Majnemer9d168222016-08-05 17:44:54 +00004739 // Build variables passed into runtime, necessary for worksharing directives.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004740 ExprResult LB, UB, IL, ST, EUB, CombLB, CombUB, PrevLB, PrevUB, CombEUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004741 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4742 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004743 // Lower bound variable, initialized with zero.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004744 VarDecl *LBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.lb");
4745 LB = buildDeclRefExpr(SemaRef, LBDecl, VType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004746 SemaRef.AddInitializerToDecl(LBDecl,
4747 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4748 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004749
4750 // Upper bound variable, initialized with last iteration number.
Alexey Bataev39f915b82015-05-08 10:41:21 +00004751 VarDecl *UBDecl = buildVarDecl(SemaRef, InitLoc, VType, ".omp.ub");
4752 UB = buildDeclRefExpr(SemaRef, UBDecl, VType, InitLoc);
Alexander Musmanc6388682014-12-15 07:07:06 +00004753 SemaRef.AddInitializerToDecl(UBDecl, LastIteration.get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00004754 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004755
4756 // A 32-bit variable-flag where runtime returns 1 for the last iteration.
4757 // This will be used to implement clause 'lastprivate'.
4758 QualType Int32Ty = SemaRef.Context.getIntTypeForBitwidth(32, true);
Alexey Bataev39f915b82015-05-08 10:41:21 +00004759 VarDecl *ILDecl = buildVarDecl(SemaRef, InitLoc, Int32Ty, ".omp.is_last");
4760 IL = buildDeclRefExpr(SemaRef, ILDecl, Int32Ty, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004761 SemaRef.AddInitializerToDecl(ILDecl,
4762 SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4763 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004764
4765 // Stride variable returned by runtime (we initialize it to 1 by default).
Alexey Bataev7292c292016-04-25 12:22:29 +00004766 VarDecl *STDecl =
4767 buildVarDecl(SemaRef, InitLoc, StrideVType, ".omp.stride");
4768 ST = buildDeclRefExpr(SemaRef, STDecl, StrideVType, InitLoc);
Richard Smith3beb7c62017-01-12 02:27:38 +00004769 SemaRef.AddInitializerToDecl(STDecl,
4770 SemaRef.ActOnIntegerConstant(InitLoc, 1).get(),
4771 /*DirectInit*/ false);
Alexander Musmanc6388682014-12-15 07:07:06 +00004772
4773 // Build expression: UB = min(UB, LastIteration)
David Majnemer9d168222016-08-05 17:44:54 +00004774 // It is necessary for CodeGen of directives with static scheduling.
Alexander Musmanc6388682014-12-15 07:07:06 +00004775 ExprResult IsUBGreater = SemaRef.BuildBinOp(CurScope, InitLoc, BO_GT,
4776 UB.get(), LastIteration.get());
4777 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4778 InitLoc, InitLoc, IsUBGreater.get(), LastIteration.get(), UB.get());
4779 EUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, UB.get(),
4780 CondOp.get());
4781 EUB = SemaRef.ActOnFinishFullExpr(EUB.get());
Carlo Bertolli9925f152016-06-27 14:55:37 +00004782
4783 // If we have a combined directive that combines 'distribute', 'for' or
4784 // 'simd' we need to be able to access the bounds of the schedule of the
4785 // enclosing region. E.g. in 'distribute parallel for' the bounds obtained
4786 // by scheduling 'distribute' have to be passed to the schedule of 'for'.
4787 if (isOpenMPLoopBoundSharingDirective(DKind)) {
Carlo Bertolli9925f152016-06-27 14:55:37 +00004788
Carlo Bertolliffafe102017-04-20 00:39:39 +00004789 // Lower bound variable, initialized with zero.
4790 VarDecl *CombLBDecl =
4791 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.lb");
4792 CombLB = buildDeclRefExpr(SemaRef, CombLBDecl, VType, InitLoc);
4793 SemaRef.AddInitializerToDecl(
4794 CombLBDecl, SemaRef.ActOnIntegerConstant(InitLoc, 0).get(),
4795 /*DirectInit*/ false);
4796
4797 // Upper bound variable, initialized with last iteration number.
4798 VarDecl *CombUBDecl =
4799 buildVarDecl(SemaRef, InitLoc, VType, ".omp.comb.ub");
4800 CombUB = buildDeclRefExpr(SemaRef, CombUBDecl, VType, InitLoc);
4801 SemaRef.AddInitializerToDecl(CombUBDecl, LastIteration.get(),
4802 /*DirectInit*/ false);
4803
4804 ExprResult CombIsUBGreater = SemaRef.BuildBinOp(
4805 CurScope, InitLoc, BO_GT, CombUB.get(), LastIteration.get());
4806 ExprResult CombCondOp =
4807 SemaRef.ActOnConditionalOp(InitLoc, InitLoc, CombIsUBGreater.get(),
4808 LastIteration.get(), CombUB.get());
4809 CombEUB = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, CombUB.get(),
4810 CombCondOp.get());
4811 CombEUB = SemaRef.ActOnFinishFullExpr(CombEUB.get());
4812
4813 auto *CD = cast<CapturedStmt>(AStmt)->getCapturedDecl();
Carlo Bertolli9925f152016-06-27 14:55:37 +00004814 // We expect to have at least 2 more parameters than the 'parallel'
4815 // directive does - the lower and upper bounds of the previous schedule.
4816 assert(CD->getNumParams() >= 4 &&
4817 "Unexpected number of parameters in loop combined directive");
4818
4819 // Set the proper type for the bounds given what we learned from the
4820 // enclosed loops.
4821 auto *PrevLBDecl = CD->getParam(/*PrevLB=*/2);
4822 auto *PrevUBDecl = CD->getParam(/*PrevUB=*/3);
4823
4824 // Previous lower and upper bounds are obtained from the region
4825 // parameters.
4826 PrevLB =
4827 buildDeclRefExpr(SemaRef, PrevLBDecl, PrevLBDecl->getType(), InitLoc);
4828 PrevUB =
4829 buildDeclRefExpr(SemaRef, PrevUBDecl, PrevUBDecl->getType(), InitLoc);
4830 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004831 }
4832
4833 // Build the iteration variable and its initialization before loop.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004834 ExprResult IV;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004835 ExprResult Init, CombInit;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004836 {
Alexey Bataev7292c292016-04-25 12:22:29 +00004837 VarDecl *IVDecl = buildVarDecl(SemaRef, InitLoc, RealVType, ".omp.iv");
4838 IV = buildDeclRefExpr(SemaRef, IVDecl, RealVType, InitLoc);
David Majnemer9d168222016-08-05 17:44:54 +00004839 Expr *RHS =
4840 (isOpenMPWorksharingDirective(DKind) ||
4841 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
4842 ? LB.get()
4843 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
Alexander Musmanc6388682014-12-15 07:07:06 +00004844 Init = SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), RHS);
4845 Init = SemaRef.ActOnFinishFullExpr(Init.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004846
4847 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4848 Expr *CombRHS =
4849 (isOpenMPWorksharingDirective(DKind) ||
4850 isOpenMPTaskLoopDirective(DKind) ||
4851 isOpenMPDistributeDirective(DKind))
4852 ? CombLB.get()
4853 : SemaRef.ActOnIntegerConstant(SourceLocation(), 0).get();
4854 CombInit =
4855 SemaRef.BuildBinOp(CurScope, InitLoc, BO_Assign, IV.get(), CombRHS);
4856 CombInit = SemaRef.ActOnFinishFullExpr(CombInit.get());
4857 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004858 }
4859
Alexander Musmanc6388682014-12-15 07:07:06 +00004860 // Loop condition (IV < NumIterations) or (IV <= UB) for worksharing loops.
Alexander Musmana5f070a2014-10-01 06:03:56 +00004861 SourceLocation CondLoc;
Alexander Musmanc6388682014-12-15 07:07:06 +00004862 ExprResult Cond =
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004863 (isOpenMPWorksharingDirective(DKind) ||
4864 isOpenMPTaskLoopDirective(DKind) || isOpenMPDistributeDirective(DKind))
Alexander Musmanc6388682014-12-15 07:07:06 +00004865 ? SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get())
4866 : SemaRef.BuildBinOp(CurScope, CondLoc, BO_LT, IV.get(),
4867 NumIterations.get());
Carlo Bertolliffafe102017-04-20 00:39:39 +00004868 ExprResult CombCond;
4869 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4870 CombCond =
4871 SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), CombUB.get());
4872 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004873 // Loop increment (IV = IV + 1)
4874 SourceLocation IncLoc;
4875 ExprResult Inc =
4876 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, IV.get(),
4877 SemaRef.ActOnIntegerConstant(IncLoc, 1).get());
4878 if (!Inc.isUsable())
4879 return 0;
4880 Inc = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, IV.get(), Inc.get());
Alexander Musmanc6388682014-12-15 07:07:06 +00004881 Inc = SemaRef.ActOnFinishFullExpr(Inc.get());
4882 if (!Inc.isUsable())
4883 return 0;
4884
4885 // Increments for worksharing loops (LB = LB + ST; UB = UB + ST).
4886 // Used for directives with static scheduling.
Carlo Bertolliffafe102017-04-20 00:39:39 +00004887 // In combined construct, add combined version that use CombLB and CombUB
4888 // base variables for the update
4889 ExprResult NextLB, NextUB, CombNextLB, CombNextUB;
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00004890 if (isOpenMPWorksharingDirective(DKind) || isOpenMPTaskLoopDirective(DKind) ||
4891 isOpenMPDistributeDirective(DKind)) {
Alexander Musmanc6388682014-12-15 07:07:06 +00004892 // LB + ST
4893 NextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, LB.get(), ST.get());
4894 if (!NextLB.isUsable())
4895 return 0;
4896 // LB = LB + ST
4897 NextLB =
4898 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, LB.get(), NextLB.get());
4899 NextLB = SemaRef.ActOnFinishFullExpr(NextLB.get());
4900 if (!NextLB.isUsable())
4901 return 0;
4902 // UB + ST
4903 NextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, UB.get(), ST.get());
4904 if (!NextUB.isUsable())
4905 return 0;
4906 // UB = UB + ST
4907 NextUB =
4908 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, UB.get(), NextUB.get());
4909 NextUB = SemaRef.ActOnFinishFullExpr(NextUB.get());
4910 if (!NextUB.isUsable())
4911 return 0;
Carlo Bertolliffafe102017-04-20 00:39:39 +00004912 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4913 CombNextLB =
4914 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombLB.get(), ST.get());
4915 if (!NextLB.isUsable())
4916 return 0;
4917 // LB = LB + ST
4918 CombNextLB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombLB.get(),
4919 CombNextLB.get());
4920 CombNextLB = SemaRef.ActOnFinishFullExpr(CombNextLB.get());
4921 if (!CombNextLB.isUsable())
4922 return 0;
4923 // UB + ST
4924 CombNextUB =
4925 SemaRef.BuildBinOp(CurScope, IncLoc, BO_Add, CombUB.get(), ST.get());
4926 if (!CombNextUB.isUsable())
4927 return 0;
4928 // UB = UB + ST
4929 CombNextUB = SemaRef.BuildBinOp(CurScope, IncLoc, BO_Assign, CombUB.get(),
4930 CombNextUB.get());
4931 CombNextUB = SemaRef.ActOnFinishFullExpr(CombNextUB.get());
4932 if (!CombNextUB.isUsable())
4933 return 0;
4934 }
Alexander Musmanc6388682014-12-15 07:07:06 +00004935 }
Alexander Musmana5f070a2014-10-01 06:03:56 +00004936
Carlo Bertolliffafe102017-04-20 00:39:39 +00004937 // Create increment expression for distribute loop when combined in a same
Carlo Bertolli8429d812017-02-17 21:29:13 +00004938 // directive with for as IV = IV + ST; ensure upper bound expression based
4939 // on PrevUB instead of NumIterations - used to implement 'for' when found
4940 // in combination with 'distribute', like in 'distribute parallel for'
4941 SourceLocation DistIncLoc;
4942 ExprResult DistCond, DistInc, PrevEUB;
4943 if (isOpenMPLoopBoundSharingDirective(DKind)) {
4944 DistCond = SemaRef.BuildBinOp(CurScope, CondLoc, BO_LE, IV.get(), UB.get());
4945 assert(DistCond.isUsable() && "distribute cond expr was not built");
4946
4947 DistInc =
4948 SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Add, IV.get(), ST.get());
4949 assert(DistInc.isUsable() && "distribute inc expr was not built");
4950 DistInc = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, IV.get(),
4951 DistInc.get());
4952 DistInc = SemaRef.ActOnFinishFullExpr(DistInc.get());
4953 assert(DistInc.isUsable() && "distribute inc expr was not built");
4954
4955 // Build expression: UB = min(UB, prevUB) for #for in composite or combined
4956 // construct
4957 SourceLocation DistEUBLoc;
4958 ExprResult IsUBGreater =
4959 SemaRef.BuildBinOp(CurScope, DistEUBLoc, BO_GT, UB.get(), PrevUB.get());
4960 ExprResult CondOp = SemaRef.ActOnConditionalOp(
4961 DistEUBLoc, DistEUBLoc, IsUBGreater.get(), PrevUB.get(), UB.get());
4962 PrevEUB = SemaRef.BuildBinOp(CurScope, DistIncLoc, BO_Assign, UB.get(),
4963 CondOp.get());
4964 PrevEUB = SemaRef.ActOnFinishFullExpr(PrevEUB.get());
4965 }
4966
Alexander Musmana5f070a2014-10-01 06:03:56 +00004967 // Build updates and final values of the loop counters.
4968 bool HasErrors = false;
4969 Built.Counters.resize(NestedLoopCount);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00004970 Built.Inits.resize(NestedLoopCount);
Alexander Musmana5f070a2014-10-01 06:03:56 +00004971 Built.Updates.resize(NestedLoopCount);
4972 Built.Finals.resize(NestedLoopCount);
Alexey Bataev8b427062016-05-25 12:36:08 +00004973 SmallVector<Expr *, 4> LoopMultipliers;
Alexander Musmana5f070a2014-10-01 06:03:56 +00004974 {
4975 ExprResult Div;
4976 // Go from inner nested loop to outer.
4977 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
4978 LoopIterationSpace &IS = IterSpaces[Cnt];
4979 SourceLocation UpdLoc = IS.IncSrcRange.getBegin();
4980 // Build: Iter = (IV / Div) % IS.NumIters
4981 // where Div is product of previous iterations' IS.NumIters.
4982 ExprResult Iter;
4983 if (Div.isUsable()) {
4984 Iter =
4985 SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Div, IV.get(), Div.get());
4986 } else {
4987 Iter = IV;
4988 assert((Cnt == (int)NestedLoopCount - 1) &&
4989 "unusable div expected on first iteration only");
4990 }
4991
4992 if (Cnt != 0 && Iter.isUsable())
4993 Iter = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Rem, Iter.get(),
4994 IS.NumIterations);
4995 if (!Iter.isUsable()) {
4996 HasErrors = true;
4997 break;
4998 }
4999
Alexey Bataev39f915b82015-05-08 10:41:21 +00005000 // Build update: IS.CounterVar(Private) = IS.Start + Iter * IS.Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005001 auto *VD = cast<VarDecl>(cast<DeclRefExpr>(IS.CounterVar)->getDecl());
5002 auto *CounterVar = buildDeclRefExpr(SemaRef, VD, IS.CounterVar->getType(),
5003 IS.CounterVar->getExprLoc(),
5004 /*RefersToCapture=*/true);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005005 ExprResult Init = BuildCounterInit(SemaRef, CurScope, UpdLoc, CounterVar,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005006 IS.CounterInit, Captures);
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005007 if (!Init.isUsable()) {
5008 HasErrors = true;
5009 break;
5010 }
Alexey Bataev5a3af132016-03-29 08:58:54 +00005011 ExprResult Update = BuildCounterUpdate(
5012 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit, Iter,
5013 IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005014 if (!Update.isUsable()) {
5015 HasErrors = true;
5016 break;
5017 }
5018
5019 // Build final: IS.CounterVar = IS.Start + IS.NumIters * IS.Step
5020 ExprResult Final = BuildCounterUpdate(
Alexey Bataev39f915b82015-05-08 10:41:21 +00005021 SemaRef, CurScope, UpdLoc, CounterVar, IS.CounterInit,
Alexey Bataev5a3af132016-03-29 08:58:54 +00005022 IS.NumIterations, IS.CounterStep, IS.Subtract, &Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005023 if (!Final.isUsable()) {
5024 HasErrors = true;
5025 break;
5026 }
5027
5028 // Build Div for the next iteration: Div <- Div * IS.NumIters
5029 if (Cnt != 0) {
5030 if (Div.isUnset())
5031 Div = IS.NumIterations;
5032 else
5033 Div = SemaRef.BuildBinOp(CurScope, UpdLoc, BO_Mul, Div.get(),
5034 IS.NumIterations);
5035
5036 // Add parentheses (for debugging purposes only).
5037 if (Div.isUsable())
Alexey Bataev8b427062016-05-25 12:36:08 +00005038 Div = tryBuildCapture(SemaRef, Div.get(), Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005039 if (!Div.isUsable()) {
5040 HasErrors = true;
5041 break;
5042 }
Alexey Bataev8b427062016-05-25 12:36:08 +00005043 LoopMultipliers.push_back(Div.get());
Alexander Musmana5f070a2014-10-01 06:03:56 +00005044 }
5045 if (!Update.isUsable() || !Final.isUsable()) {
5046 HasErrors = true;
5047 break;
5048 }
5049 // Save results
5050 Built.Counters[Cnt] = IS.CounterVar;
Alexey Bataeva8899172015-08-06 12:30:57 +00005051 Built.PrivateCounters[Cnt] = IS.PrivateCounterVar;
Alexey Bataevb08f89f2015-08-14 12:25:37 +00005052 Built.Inits[Cnt] = Init.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005053 Built.Updates[Cnt] = Update.get();
5054 Built.Finals[Cnt] = Final.get();
5055 }
5056 }
5057
5058 if (HasErrors)
5059 return 0;
5060
5061 // Save results
5062 Built.IterationVarRef = IV.get();
5063 Built.LastIteration = LastIteration.get();
Alexander Musman3276a272015-03-21 10:12:56 +00005064 Built.NumIterations = NumIterations.get();
Alexey Bataev3bed68c2015-07-15 12:14:07 +00005065 Built.CalcLastIteration =
5066 SemaRef.ActOnFinishFullExpr(CalcLastIteration.get()).get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005067 Built.PreCond = PreCond.get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00005068 Built.PreInits = buildPreInits(C, Captures);
Alexander Musmana5f070a2014-10-01 06:03:56 +00005069 Built.Cond = Cond.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005070 Built.Init = Init.get();
5071 Built.Inc = Inc.get();
Alexander Musmanc6388682014-12-15 07:07:06 +00005072 Built.LB = LB.get();
5073 Built.UB = UB.get();
5074 Built.IL = IL.get();
5075 Built.ST = ST.get();
5076 Built.EUB = EUB.get();
5077 Built.NLB = NextLB.get();
5078 Built.NUB = NextUB.get();
Carlo Bertolli9925f152016-06-27 14:55:37 +00005079 Built.PrevLB = PrevLB.get();
5080 Built.PrevUB = PrevUB.get();
Carlo Bertolli8429d812017-02-17 21:29:13 +00005081 Built.DistInc = DistInc.get();
5082 Built.PrevEUB = PrevEUB.get();
Carlo Bertolliffafe102017-04-20 00:39:39 +00005083 Built.DistCombinedFields.LB = CombLB.get();
5084 Built.DistCombinedFields.UB = CombUB.get();
5085 Built.DistCombinedFields.EUB = CombEUB.get();
5086 Built.DistCombinedFields.Init = CombInit.get();
5087 Built.DistCombinedFields.Cond = CombCond.get();
5088 Built.DistCombinedFields.NLB = CombNextLB.get();
5089 Built.DistCombinedFields.NUB = CombNextUB.get();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005090
Alexey Bataev8b427062016-05-25 12:36:08 +00005091 Expr *CounterVal = SemaRef.DefaultLvalueConversion(IV.get()).get();
5092 // Fill data for doacross depend clauses.
5093 for (auto Pair : DSA.getDoacrossDependClauses()) {
5094 if (Pair.first->getDependencyKind() == OMPC_DEPEND_source)
5095 Pair.first->setCounterValue(CounterVal);
5096 else {
5097 if (NestedLoopCount != Pair.second.size() ||
5098 NestedLoopCount != LoopMultipliers.size() + 1) {
5099 // Erroneous case - clause has some problems.
5100 Pair.first->setCounterValue(CounterVal);
5101 continue;
5102 }
5103 assert(Pair.first->getDependencyKind() == OMPC_DEPEND_sink);
5104 auto I = Pair.second.rbegin();
5105 auto IS = IterSpaces.rbegin();
5106 auto ILM = LoopMultipliers.rbegin();
5107 Expr *UpCounterVal = CounterVal;
5108 Expr *Multiplier = nullptr;
5109 for (int Cnt = NestedLoopCount - 1; Cnt >= 0; --Cnt) {
5110 if (I->first) {
5111 assert(IS->CounterStep);
5112 Expr *NormalizedOffset =
5113 SemaRef
5114 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Div,
5115 I->first, IS->CounterStep)
5116 .get();
5117 if (Multiplier) {
5118 NormalizedOffset =
5119 SemaRef
5120 .BuildBinOp(CurScope, I->first->getExprLoc(), BO_Mul,
5121 NormalizedOffset, Multiplier)
5122 .get();
5123 }
5124 assert(I->second == OO_Plus || I->second == OO_Minus);
5125 BinaryOperatorKind BOK = (I->second == OO_Plus) ? BO_Add : BO_Sub;
David Majnemer9d168222016-08-05 17:44:54 +00005126 UpCounterVal = SemaRef
5127 .BuildBinOp(CurScope, I->first->getExprLoc(), BOK,
5128 UpCounterVal, NormalizedOffset)
5129 .get();
Alexey Bataev8b427062016-05-25 12:36:08 +00005130 }
5131 Multiplier = *ILM;
5132 ++I;
5133 ++IS;
5134 ++ILM;
5135 }
5136 Pair.first->setCounterValue(UpCounterVal);
5137 }
5138 }
5139
Alexey Bataevabfc0692014-06-25 06:52:00 +00005140 return NestedLoopCount;
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00005141}
5142
Alexey Bataev10e775f2015-07-30 11:36:16 +00005143static Expr *getCollapseNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005144 auto CollapseClauses =
5145 OMPExecutableDirective::getClausesOfKind<OMPCollapseClause>(Clauses);
5146 if (CollapseClauses.begin() != CollapseClauses.end())
5147 return (*CollapseClauses.begin())->getNumForLoops();
Alexey Bataeve2f07d42014-06-24 12:55:56 +00005148 return nullptr;
5149}
5150
Alexey Bataev10e775f2015-07-30 11:36:16 +00005151static Expr *getOrderedNumberExpr(ArrayRef<OMPClause *> Clauses) {
Benjamin Kramerfc600dc2015-08-30 15:12:28 +00005152 auto OrderedClauses =
5153 OMPExecutableDirective::getClausesOfKind<OMPOrderedClause>(Clauses);
5154 if (OrderedClauses.begin() != OrderedClauses.end())
5155 return (*OrderedClauses.begin())->getNumForLoops();
Alexey Bataev10e775f2015-07-30 11:36:16 +00005156 return nullptr;
5157}
5158
Kelvin Lic5609492016-07-15 04:39:07 +00005159static bool checkSimdlenSafelenSpecified(Sema &S,
5160 const ArrayRef<OMPClause *> Clauses) {
5161 OMPSafelenClause *Safelen = nullptr;
5162 OMPSimdlenClause *Simdlen = nullptr;
5163
5164 for (auto *Clause : Clauses) {
5165 if (Clause->getClauseKind() == OMPC_safelen)
5166 Safelen = cast<OMPSafelenClause>(Clause);
5167 else if (Clause->getClauseKind() == OMPC_simdlen)
5168 Simdlen = cast<OMPSimdlenClause>(Clause);
5169 if (Safelen && Simdlen)
5170 break;
5171 }
5172
5173 if (Simdlen && Safelen) {
5174 llvm::APSInt SimdlenRes, SafelenRes;
5175 auto SimdlenLength = Simdlen->getSimdlen();
5176 auto SafelenLength = Safelen->getSafelen();
5177 if (SimdlenLength->isValueDependent() || SimdlenLength->isTypeDependent() ||
5178 SimdlenLength->isInstantiationDependent() ||
5179 SimdlenLength->containsUnexpandedParameterPack())
5180 return false;
5181 if (SafelenLength->isValueDependent() || SafelenLength->isTypeDependent() ||
5182 SafelenLength->isInstantiationDependent() ||
5183 SafelenLength->containsUnexpandedParameterPack())
5184 return false;
5185 SimdlenLength->EvaluateAsInt(SimdlenRes, S.Context);
5186 SafelenLength->EvaluateAsInt(SafelenRes, S.Context);
5187 // OpenMP 4.5 [2.8.1, simd Construct, Restrictions]
5188 // If both simdlen and safelen clauses are specified, the value of the
5189 // simdlen parameter must be less than or equal to the value of the safelen
5190 // parameter.
5191 if (SimdlenRes > SafelenRes) {
5192 S.Diag(SimdlenLength->getExprLoc(),
5193 diag::err_omp_wrong_simdlen_safelen_values)
5194 << SimdlenLength->getSourceRange() << SafelenLength->getSourceRange();
5195 return true;
5196 }
Alexey Bataev66b15b52015-08-21 11:14:16 +00005197 }
5198 return false;
5199}
5200
Alexey Bataev4acb8592014-07-07 13:01:15 +00005201StmtResult Sema::ActOnOpenMPSimdDirective(
5202 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5203 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005204 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005205 if (!AStmt)
5206 return StmtError();
5207
5208 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005209 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005210 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5211 // define the nested loops number.
5212 unsigned NestedLoopCount = CheckOpenMPLoop(
5213 OMPD_simd, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5214 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005215 if (NestedLoopCount == 0)
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005216 return StmtError();
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005217
Alexander Musmana5f070a2014-10-01 06:03:56 +00005218 assert((CurContext->isDependentContext() || B.builtAll()) &&
5219 "omp simd loop exprs were not built");
5220
Alexander Musman3276a272015-03-21 10:12:56 +00005221 if (!CurContext->isDependentContext()) {
5222 // Finalize the clauses that need pre-built expressions for CodeGen.
5223 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005224 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexander Musman3276a272015-03-21 10:12:56 +00005225 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005226 B.NumIterations, *this, CurScope,
5227 DSAStack))
Alexander Musman3276a272015-03-21 10:12:56 +00005228 return StmtError();
5229 }
5230 }
5231
Kelvin Lic5609492016-07-15 04:39:07 +00005232 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005233 return StmtError();
5234
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005235 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005236 return OMPSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5237 Clauses, AStmt, B);
Alexey Bataev1b59ab52014-02-27 08:29:12 +00005238}
5239
Alexey Bataev4acb8592014-07-07 13:01:15 +00005240StmtResult Sema::ActOnOpenMPForDirective(
5241 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5242 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005243 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005244 if (!AStmt)
5245 return StmtError();
5246
5247 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005248 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005249 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5250 // define the nested loops number.
5251 unsigned NestedLoopCount = CheckOpenMPLoop(
5252 OMPD_for, getCollapseNumberExpr(Clauses), getOrderedNumberExpr(Clauses),
5253 AStmt, *this, *DSAStack, VarsWithImplicitDSA, B);
Alexey Bataevabfc0692014-06-25 06:52:00 +00005254 if (NestedLoopCount == 0)
Alexey Bataevf29276e2014-06-18 04:14:57 +00005255 return StmtError();
5256
Alexander Musmana5f070a2014-10-01 06:03:56 +00005257 assert((CurContext->isDependentContext() || B.builtAll()) &&
5258 "omp for loop exprs were not built");
5259
Alexey Bataev54acd402015-08-04 11:18:19 +00005260 if (!CurContext->isDependentContext()) {
5261 // Finalize the clauses that need pre-built expressions for CodeGen.
5262 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005263 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005264 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005265 B.NumIterations, *this, CurScope,
5266 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005267 return StmtError();
5268 }
5269 }
5270
Alexey Bataevf29276e2014-06-18 04:14:57 +00005271 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005272 return OMPForDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005273 Clauses, AStmt, B, DSAStack->isCancelRegion());
Alexey Bataevf29276e2014-06-18 04:14:57 +00005274}
5275
Alexander Musmanf82886e2014-09-18 05:12:34 +00005276StmtResult Sema::ActOnOpenMPForSimdDirective(
5277 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5278 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005279 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005280 if (!AStmt)
5281 return StmtError();
5282
5283 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmanc6388682014-12-15 07:07:06 +00005284 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005285 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5286 // define the nested loops number.
Alexander Musmanf82886e2014-09-18 05:12:34 +00005287 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005288 CheckOpenMPLoop(OMPD_for_simd, getCollapseNumberExpr(Clauses),
5289 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5290 VarsWithImplicitDSA, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005291 if (NestedLoopCount == 0)
5292 return StmtError();
5293
Alexander Musmanc6388682014-12-15 07:07:06 +00005294 assert((CurContext->isDependentContext() || B.builtAll()) &&
5295 "omp for simd loop exprs were not built");
5296
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005297 if (!CurContext->isDependentContext()) {
5298 // Finalize the clauses that need pre-built expressions for CodeGen.
5299 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005300 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005301 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005302 B.NumIterations, *this, CurScope,
5303 DSAStack))
Alexey Bataev58e5bdb2015-06-18 04:45:29 +00005304 return StmtError();
5305 }
5306 }
5307
Kelvin Lic5609492016-07-15 04:39:07 +00005308 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005309 return StmtError();
5310
Alexander Musmanf82886e2014-09-18 05:12:34 +00005311 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005312 return OMPForSimdDirective::Create(Context, StartLoc, EndLoc, NestedLoopCount,
5313 Clauses, AStmt, B);
Alexander Musmanf82886e2014-09-18 05:12:34 +00005314}
5315
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005316StmtResult Sema::ActOnOpenMPSectionsDirective(ArrayRef<OMPClause *> Clauses,
5317 Stmt *AStmt,
5318 SourceLocation StartLoc,
5319 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005320 if (!AStmt)
5321 return StmtError();
5322
5323 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005324 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005325 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005326 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005327 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005328 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005329 if (S.begin() == S.end())
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005330 return StmtError();
5331 // All associated statements must be '#pragma omp section' except for
5332 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005333 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005334 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5335 if (SectionStmt)
5336 Diag(SectionStmt->getLocStart(),
5337 diag::err_omp_sections_substmt_not_section);
5338 return StmtError();
5339 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005340 cast<OMPSectionDirective>(SectionStmt)
5341 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005342 }
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005343 } else {
5344 Diag(AStmt->getLocStart(), diag::err_omp_sections_not_compound_stmt);
5345 return StmtError();
5346 }
5347
5348 getCurFunction()->setHasBranchProtectedScope();
5349
Alexey Bataev25e5b442015-09-15 12:52:43 +00005350 return OMPSectionsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5351 DSAStack->isCancelRegion());
Alexey Bataevd3f8dd22014-06-25 11:44:49 +00005352}
5353
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005354StmtResult Sema::ActOnOpenMPSectionDirective(Stmt *AStmt,
5355 SourceLocation StartLoc,
5356 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005357 if (!AStmt)
5358 return StmtError();
5359
5360 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005361
5362 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev25e5b442015-09-15 12:52:43 +00005363 DSAStack->setParentCancelRegion(DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005364
Alexey Bataev25e5b442015-09-15 12:52:43 +00005365 return OMPSectionDirective::Create(Context, StartLoc, EndLoc, AStmt,
5366 DSAStack->isCancelRegion());
Alexey Bataev1e0498a2014-06-26 08:21:58 +00005367}
5368
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005369StmtResult Sema::ActOnOpenMPSingleDirective(ArrayRef<OMPClause *> Clauses,
5370 Stmt *AStmt,
5371 SourceLocation StartLoc,
5372 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005373 if (!AStmt)
5374 return StmtError();
5375
5376 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev74a05c92014-07-15 02:55:09 +00005377
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005378 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataev74a05c92014-07-15 02:55:09 +00005379
Alexey Bataev3255bf32015-01-19 05:20:46 +00005380 // OpenMP [2.7.3, single Construct, Restrictions]
5381 // The copyprivate clause must not be used with the nowait clause.
5382 OMPClause *Nowait = nullptr;
5383 OMPClause *Copyprivate = nullptr;
5384 for (auto *Clause : Clauses) {
5385 if (Clause->getClauseKind() == OMPC_nowait)
5386 Nowait = Clause;
5387 else if (Clause->getClauseKind() == OMPC_copyprivate)
5388 Copyprivate = Clause;
5389 if (Copyprivate && Nowait) {
5390 Diag(Copyprivate->getLocStart(),
5391 diag::err_omp_single_copyprivate_with_nowait);
5392 Diag(Nowait->getLocStart(), diag::note_omp_nowait_clause_here);
5393 return StmtError();
5394 }
5395 }
5396
Alexey Bataevd1e40fb2014-06-26 12:05:45 +00005397 return OMPSingleDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
5398}
5399
Alexander Musman80c22892014-07-17 08:54:58 +00005400StmtResult Sema::ActOnOpenMPMasterDirective(Stmt *AStmt,
5401 SourceLocation StartLoc,
5402 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005403 if (!AStmt)
5404 return StmtError();
5405
5406 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musman80c22892014-07-17 08:54:58 +00005407
5408 getCurFunction()->setHasBranchProtectedScope();
5409
5410 return OMPMasterDirective::Create(Context, StartLoc, EndLoc, AStmt);
5411}
5412
Alexey Bataev28c75412015-12-15 08:19:24 +00005413StmtResult Sema::ActOnOpenMPCriticalDirective(
5414 const DeclarationNameInfo &DirName, ArrayRef<OMPClause *> Clauses,
5415 Stmt *AStmt, SourceLocation StartLoc, SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005416 if (!AStmt)
5417 return StmtError();
5418
5419 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005420
Alexey Bataev28c75412015-12-15 08:19:24 +00005421 bool ErrorFound = false;
5422 llvm::APSInt Hint;
5423 SourceLocation HintLoc;
5424 bool DependentHint = false;
5425 for (auto *C : Clauses) {
5426 if (C->getClauseKind() == OMPC_hint) {
5427 if (!DirName.getName()) {
5428 Diag(C->getLocStart(), diag::err_omp_hint_clause_no_name);
5429 ErrorFound = true;
5430 }
5431 Expr *E = cast<OMPHintClause>(C)->getHint();
5432 if (E->isTypeDependent() || E->isValueDependent() ||
5433 E->isInstantiationDependent())
5434 DependentHint = true;
5435 else {
5436 Hint = E->EvaluateKnownConstInt(Context);
5437 HintLoc = C->getLocStart();
5438 }
5439 }
5440 }
5441 if (ErrorFound)
5442 return StmtError();
5443 auto Pair = DSAStack->getCriticalWithHint(DirName);
5444 if (Pair.first && DirName.getName() && !DependentHint) {
5445 if (llvm::APSInt::compareValues(Hint, Pair.second) != 0) {
5446 Diag(StartLoc, diag::err_omp_critical_with_hint);
5447 if (HintLoc.isValid()) {
5448 Diag(HintLoc, diag::note_omp_critical_hint_here)
5449 << 0 << Hint.toString(/*Radix=*/10, /*Signed=*/false);
5450 } else
5451 Diag(StartLoc, diag::note_omp_critical_no_hint) << 0;
5452 if (auto *C = Pair.first->getSingleClause<OMPHintClause>()) {
5453 Diag(C->getLocStart(), diag::note_omp_critical_hint_here)
5454 << 1
5455 << C->getHint()->EvaluateKnownConstInt(Context).toString(
5456 /*Radix=*/10, /*Signed=*/false);
5457 } else
5458 Diag(Pair.first->getLocStart(), diag::note_omp_critical_no_hint) << 1;
5459 }
5460 }
5461
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005462 getCurFunction()->setHasBranchProtectedScope();
5463
Alexey Bataev28c75412015-12-15 08:19:24 +00005464 auto *Dir = OMPCriticalDirective::Create(Context, DirName, StartLoc, EndLoc,
5465 Clauses, AStmt);
5466 if (!Pair.first && DirName.getName() && !DependentHint)
5467 DSAStack->addCriticalWithHint(Dir, Hint);
5468 return Dir;
Alexander Musmand9ed09f2014-07-21 09:42:05 +00005469}
5470
Alexey Bataev4acb8592014-07-07 13:01:15 +00005471StmtResult Sema::ActOnOpenMPParallelForDirective(
5472 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5473 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005474 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005475 if (!AStmt)
5476 return StmtError();
5477
Alexey Bataev4acb8592014-07-07 13:01:15 +00005478 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5479 // 1.2.2 OpenMP Language Terminology
5480 // Structured block - An executable statement with a single entry at the
5481 // top and a single exit at the bottom.
5482 // The point of exit cannot be a branch out of the structured block.
5483 // longjmp() and throw() must not violate the entry/exit criteria.
5484 CS->getCapturedDecl()->setNothrow();
5485
Alexander Musmanc6388682014-12-15 07:07:06 +00005486 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005487 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5488 // define the nested loops number.
Alexey Bataev4acb8592014-07-07 13:01:15 +00005489 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005490 CheckOpenMPLoop(OMPD_parallel_for, getCollapseNumberExpr(Clauses),
5491 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5492 VarsWithImplicitDSA, B);
Alexey Bataev4acb8592014-07-07 13:01:15 +00005493 if (NestedLoopCount == 0)
5494 return StmtError();
5495
Alexander Musmana5f070a2014-10-01 06:03:56 +00005496 assert((CurContext->isDependentContext() || B.builtAll()) &&
5497 "omp parallel for loop exprs were not built");
5498
Alexey Bataev54acd402015-08-04 11:18:19 +00005499 if (!CurContext->isDependentContext()) {
5500 // Finalize the clauses that need pre-built expressions for CodeGen.
5501 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005502 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev54acd402015-08-04 11:18:19 +00005503 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005504 B.NumIterations, *this, CurScope,
5505 DSAStack))
Alexey Bataev54acd402015-08-04 11:18:19 +00005506 return StmtError();
5507 }
5508 }
5509
Alexey Bataev4acb8592014-07-07 13:01:15 +00005510 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmanc6388682014-12-15 07:07:06 +00005511 return OMPParallelForDirective::Create(Context, StartLoc, EndLoc,
Alexey Bataev25e5b442015-09-15 12:52:43 +00005512 NestedLoopCount, Clauses, AStmt, B,
5513 DSAStack->isCancelRegion());
Alexey Bataev4acb8592014-07-07 13:01:15 +00005514}
5515
Alexander Musmane4e893b2014-09-23 09:33:00 +00005516StmtResult Sema::ActOnOpenMPParallelForSimdDirective(
5517 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
5518 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00005519 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005520 if (!AStmt)
5521 return StmtError();
5522
Alexander Musmane4e893b2014-09-23 09:33:00 +00005523 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
5524 // 1.2.2 OpenMP Language Terminology
5525 // Structured block - An executable statement with a single entry at the
5526 // top and a single exit at the bottom.
5527 // The point of exit cannot be a branch out of the structured block.
5528 // longjmp() and throw() must not violate the entry/exit criteria.
5529 CS->getCapturedDecl()->setNothrow();
5530
Alexander Musmanc6388682014-12-15 07:07:06 +00005531 OMPLoopDirective::HelperExprs B;
Alexey Bataev10e775f2015-07-30 11:36:16 +00005532 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
5533 // define the nested loops number.
Alexander Musmane4e893b2014-09-23 09:33:00 +00005534 unsigned NestedLoopCount =
Alexey Bataev10e775f2015-07-30 11:36:16 +00005535 CheckOpenMPLoop(OMPD_parallel_for_simd, getCollapseNumberExpr(Clauses),
5536 getOrderedNumberExpr(Clauses), AStmt, *this, *DSAStack,
5537 VarsWithImplicitDSA, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005538 if (NestedLoopCount == 0)
5539 return StmtError();
5540
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005541 if (!CurContext->isDependentContext()) {
5542 // Finalize the clauses that need pre-built expressions for CodeGen.
5543 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00005544 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005545 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00005546 B.NumIterations, *this, CurScope,
5547 DSAStack))
Alexey Bataev3b5b5c42015-06-18 10:10:12 +00005548 return StmtError();
5549 }
5550 }
5551
Kelvin Lic5609492016-07-15 04:39:07 +00005552 if (checkSimdlenSafelenSpecified(*this, Clauses))
Alexey Bataev66b15b52015-08-21 11:14:16 +00005553 return StmtError();
5554
Alexander Musmane4e893b2014-09-23 09:33:00 +00005555 getCurFunction()->setHasBranchProtectedScope();
Alexander Musmana5f070a2014-10-01 06:03:56 +00005556 return OMPParallelForSimdDirective::Create(
Alexander Musmanc6388682014-12-15 07:07:06 +00005557 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Alexander Musmane4e893b2014-09-23 09:33:00 +00005558}
5559
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005560StmtResult
5561Sema::ActOnOpenMPParallelSectionsDirective(ArrayRef<OMPClause *> Clauses,
5562 Stmt *AStmt, SourceLocation StartLoc,
5563 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005564 if (!AStmt)
5565 return StmtError();
5566
5567 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005568 auto BaseStmt = AStmt;
David Majnemer9d168222016-08-05 17:44:54 +00005569 while (auto *CS = dyn_cast_or_null<CapturedStmt>(BaseStmt))
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005570 BaseStmt = CS->getCapturedStmt();
David Majnemer9d168222016-08-05 17:44:54 +00005571 if (auto *C = dyn_cast_or_null<CompoundStmt>(BaseStmt)) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005572 auto S = C->children();
Benjamin Kramer5733e352015-07-18 17:09:36 +00005573 if (S.begin() == S.end())
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005574 return StmtError();
5575 // All associated statements must be '#pragma omp section' except for
5576 // the first one.
Benjamin Kramer5733e352015-07-18 17:09:36 +00005577 for (Stmt *SectionStmt : llvm::make_range(std::next(S.begin()), S.end())) {
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005578 if (!SectionStmt || !isa<OMPSectionDirective>(SectionStmt)) {
5579 if (SectionStmt)
5580 Diag(SectionStmt->getLocStart(),
5581 diag::err_omp_parallel_sections_substmt_not_section);
5582 return StmtError();
5583 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00005584 cast<OMPSectionDirective>(SectionStmt)
5585 ->setHasCancel(DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005586 }
5587 } else {
5588 Diag(AStmt->getLocStart(),
5589 diag::err_omp_parallel_sections_not_compound_stmt);
5590 return StmtError();
5591 }
5592
5593 getCurFunction()->setHasBranchProtectedScope();
5594
Alexey Bataev25e5b442015-09-15 12:52:43 +00005595 return OMPParallelSectionsDirective::Create(
5596 Context, StartLoc, EndLoc, Clauses, AStmt, DSAStack->isCancelRegion());
Alexey Bataev84d0b3e2014-07-08 08:12:03 +00005597}
5598
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005599StmtResult Sema::ActOnOpenMPTaskDirective(ArrayRef<OMPClause *> Clauses,
5600 Stmt *AStmt, SourceLocation StartLoc,
5601 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005602 if (!AStmt)
5603 return StmtError();
5604
David Majnemer9d168222016-08-05 17:44:54 +00005605 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005606 // 1.2.2 OpenMP Language Terminology
5607 // Structured block - An executable statement with a single entry at the
5608 // top and a single exit at the bottom.
5609 // The point of exit cannot be a branch out of the structured block.
5610 // longjmp() and throw() must not violate the entry/exit criteria.
5611 CS->getCapturedDecl()->setNothrow();
5612
5613 getCurFunction()->setHasBranchProtectedScope();
5614
Alexey Bataev25e5b442015-09-15 12:52:43 +00005615 return OMPTaskDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
5616 DSAStack->isCancelRegion());
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00005617}
5618
Alexey Bataev68446b72014-07-18 07:47:19 +00005619StmtResult Sema::ActOnOpenMPTaskyieldDirective(SourceLocation StartLoc,
5620 SourceLocation EndLoc) {
5621 return OMPTaskyieldDirective::Create(Context, StartLoc, EndLoc);
5622}
5623
Alexey Bataev4d1dfea2014-07-18 09:11:51 +00005624StmtResult Sema::ActOnOpenMPBarrierDirective(SourceLocation StartLoc,
5625 SourceLocation EndLoc) {
5626 return OMPBarrierDirective::Create(Context, StartLoc, EndLoc);
5627}
5628
Alexey Bataev2df347a2014-07-18 10:17:07 +00005629StmtResult Sema::ActOnOpenMPTaskwaitDirective(SourceLocation StartLoc,
5630 SourceLocation EndLoc) {
5631 return OMPTaskwaitDirective::Create(Context, StartLoc, EndLoc);
5632}
5633
Alexey Bataev169d96a2017-07-18 20:17:46 +00005634StmtResult Sema::ActOnOpenMPTaskgroupDirective(ArrayRef<OMPClause *> Clauses,
5635 Stmt *AStmt,
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005636 SourceLocation StartLoc,
5637 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005638 if (!AStmt)
5639 return StmtError();
5640
5641 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005642
5643 getCurFunction()->setHasBranchProtectedScope();
5644
Alexey Bataev169d96a2017-07-18 20:17:46 +00005645 return OMPTaskgroupDirective::Create(Context, StartLoc, EndLoc, Clauses,
Alexey Bataev3b1b8952017-07-25 15:53:26 +00005646 AStmt,
5647 DSAStack->getTaskgroupReductionRef());
Alexey Bataevc30dd2d2015-06-18 12:14:09 +00005648}
5649
Alexey Bataev6125da92014-07-21 11:26:11 +00005650StmtResult Sema::ActOnOpenMPFlushDirective(ArrayRef<OMPClause *> Clauses,
5651 SourceLocation StartLoc,
5652 SourceLocation EndLoc) {
5653 assert(Clauses.size() <= 1 && "Extra clauses in flush directive");
5654 return OMPFlushDirective::Create(Context, StartLoc, EndLoc, Clauses);
5655}
5656
Alexey Bataev346265e2015-09-25 10:37:12 +00005657StmtResult Sema::ActOnOpenMPOrderedDirective(ArrayRef<OMPClause *> Clauses,
5658 Stmt *AStmt,
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005659 SourceLocation StartLoc,
5660 SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +00005661 OMPClause *DependFound = nullptr;
5662 OMPClause *DependSourceClause = nullptr;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005663 OMPClause *DependSinkClause = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005664 bool ErrorFound = false;
Alexey Bataev346265e2015-09-25 10:37:12 +00005665 OMPThreadsClause *TC = nullptr;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005666 OMPSIMDClause *SC = nullptr;
Alexey Bataeveb482352015-12-18 05:05:56 +00005667 for (auto *C : Clauses) {
5668 if (auto *DC = dyn_cast<OMPDependClause>(C)) {
5669 DependFound = C;
5670 if (DC->getDependencyKind() == OMPC_DEPEND_source) {
5671 if (DependSourceClause) {
5672 Diag(C->getLocStart(), diag::err_omp_more_one_clause)
5673 << getOpenMPDirectiveName(OMPD_ordered)
5674 << getOpenMPClauseName(OMPC_depend) << 2;
5675 ErrorFound = true;
5676 } else
5677 DependSourceClause = C;
Alexey Bataeva636c7f2015-12-23 10:27:45 +00005678 if (DependSinkClause) {
5679 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5680 << 0;
5681 ErrorFound = true;
5682 }
5683 } else if (DC->getDependencyKind() == OMPC_DEPEND_sink) {
5684 if (DependSourceClause) {
5685 Diag(C->getLocStart(), diag::err_omp_depend_sink_source_not_allowed)
5686 << 1;
5687 ErrorFound = true;
5688 }
5689 DependSinkClause = C;
Alexey Bataeveb482352015-12-18 05:05:56 +00005690 }
5691 } else if (C->getClauseKind() == OMPC_threads)
Alexey Bataev346265e2015-09-25 10:37:12 +00005692 TC = cast<OMPThreadsClause>(C);
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005693 else if (C->getClauseKind() == OMPC_simd)
5694 SC = cast<OMPSIMDClause>(C);
Alexey Bataev346265e2015-09-25 10:37:12 +00005695 }
Alexey Bataeveb482352015-12-18 05:05:56 +00005696 if (!ErrorFound && !SC &&
5697 isOpenMPSimdDirective(DSAStack->getParentDirective())) {
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005698 // OpenMP [2.8.1,simd Construct, Restrictions]
5699 // An ordered construct with the simd clause is the only OpenMP construct
5700 // that can appear in the simd region.
5701 Diag(StartLoc, diag::err_omp_prohibited_region_simd);
Alexey Bataeveb482352015-12-18 05:05:56 +00005702 ErrorFound = true;
5703 } else if (DependFound && (TC || SC)) {
5704 Diag(DependFound->getLocStart(), diag::err_omp_depend_clause_thread_simd)
5705 << getOpenMPClauseName(TC ? TC->getClauseKind() : SC->getClauseKind());
5706 ErrorFound = true;
5707 } else if (DependFound && !DSAStack->getParentOrderedRegionParam()) {
5708 Diag(DependFound->getLocStart(),
5709 diag::err_omp_ordered_directive_without_param);
5710 ErrorFound = true;
5711 } else if (TC || Clauses.empty()) {
5712 if (auto *Param = DSAStack->getParentOrderedRegionParam()) {
5713 SourceLocation ErrLoc = TC ? TC->getLocStart() : StartLoc;
5714 Diag(ErrLoc, diag::err_omp_ordered_directive_with_param)
5715 << (TC != nullptr);
5716 Diag(Param->getLocStart(), diag::note_omp_ordered_param);
5717 ErrorFound = true;
5718 }
5719 }
5720 if ((!AStmt && !DependFound) || ErrorFound)
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005721 return StmtError();
Alexey Bataeveb482352015-12-18 05:05:56 +00005722
5723 if (AStmt) {
5724 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
5725
5726 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevd14d1e62015-09-28 06:39:35 +00005727 }
Alexey Bataev346265e2015-09-25 10:37:12 +00005728
5729 return OMPOrderedDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
Alexey Bataev9fb6e642014-07-22 06:45:04 +00005730}
5731
Alexey Bataev1d160b12015-03-13 12:27:31 +00005732namespace {
5733/// \brief Helper class for checking expression in 'omp atomic [update]'
5734/// construct.
5735class OpenMPAtomicUpdateChecker {
5736 /// \brief Error results for atomic update expressions.
5737 enum ExprAnalysisErrorCode {
5738 /// \brief A statement is not an expression statement.
5739 NotAnExpression,
5740 /// \brief Expression is not builtin binary or unary operation.
5741 NotABinaryOrUnaryExpression,
5742 /// \brief Unary operation is not post-/pre- increment/decrement operation.
5743 NotAnUnaryIncDecExpression,
5744 /// \brief An expression is not of scalar type.
5745 NotAScalarType,
5746 /// \brief A binary operation is not an assignment operation.
5747 NotAnAssignmentOp,
5748 /// \brief RHS part of the binary operation is not a binary expression.
5749 NotABinaryExpression,
5750 /// \brief RHS part is not additive/multiplicative/shift/biwise binary
5751 /// expression.
5752 NotABinaryOperator,
5753 /// \brief RHS binary operation does not have reference to the updated LHS
5754 /// part.
5755 NotAnUpdateExpression,
5756 /// \brief No errors is found.
5757 NoError
5758 };
5759 /// \brief Reference to Sema.
5760 Sema &SemaRef;
5761 /// \brief A location for note diagnostics (when error is found).
5762 SourceLocation NoteLoc;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005763 /// \brief 'x' lvalue part of the source atomic expression.
5764 Expr *X;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005765 /// \brief 'expr' rvalue part of the source atomic expression.
5766 Expr *E;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005767 /// \brief Helper expression of the form
5768 /// 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5769 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5770 Expr *UpdateExpr;
5771 /// \brief Is 'x' a LHS in a RHS part of full update expression. It is
5772 /// important for non-associative operations.
5773 bool IsXLHSInRHSPart;
5774 BinaryOperatorKind Op;
5775 SourceLocation OpLoc;
Alexey Bataevb78ca832015-04-01 03:33:17 +00005776 /// \brief true if the source expression is a postfix unary operation, false
5777 /// if it is a prefix unary operation.
5778 bool IsPostfixUpdate;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005779
5780public:
5781 OpenMPAtomicUpdateChecker(Sema &SemaRef)
Alexey Bataevb4505a72015-03-30 05:20:59 +00005782 : SemaRef(SemaRef), X(nullptr), E(nullptr), UpdateExpr(nullptr),
Alexey Bataevb78ca832015-04-01 03:33:17 +00005783 IsXLHSInRHSPart(false), Op(BO_PtrMemD), IsPostfixUpdate(false) {}
Alexey Bataev1d160b12015-03-13 12:27:31 +00005784 /// \brief Check specified statement that it is suitable for 'atomic update'
5785 /// constructs and extract 'x', 'expr' and Operation from the original
Alexey Bataevb78ca832015-04-01 03:33:17 +00005786 /// expression. If DiagId and NoteId == 0, then only check is performed
5787 /// without error notification.
Alexey Bataev1d160b12015-03-13 12:27:31 +00005788 /// \param DiagId Diagnostic which should be emitted if error is found.
5789 /// \param NoteId Diagnostic note for the main error message.
5790 /// \return true if statement is not an update expression, false otherwise.
Alexey Bataevb78ca832015-04-01 03:33:17 +00005791 bool checkStatement(Stmt *S, unsigned DiagId = 0, unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005792 /// \brief Return the 'x' lvalue part of the source atomic expression.
5793 Expr *getX() const { return X; }
Alexey Bataev1d160b12015-03-13 12:27:31 +00005794 /// \brief Return the 'expr' rvalue part of the source atomic expression.
5795 Expr *getExpr() const { return E; }
Alexey Bataevb4505a72015-03-30 05:20:59 +00005796 /// \brief Return the update expression used in calculation of the updated
5797 /// value. Always has form 'OpaqueValueExpr(x) binop OpaqueValueExpr(expr)' or
5798 /// 'OpaqueValueExpr(expr) binop OpaqueValueExpr(x)'.
5799 Expr *getUpdateExpr() const { return UpdateExpr; }
5800 /// \brief Return true if 'x' is LHS in RHS part of full update expression,
5801 /// false otherwise.
5802 bool isXLHSInRHSPart() const { return IsXLHSInRHSPart; }
5803
Alexey Bataevb78ca832015-04-01 03:33:17 +00005804 /// \brief true if the source expression is a postfix unary operation, false
5805 /// if it is a prefix unary operation.
5806 bool isPostfixUpdate() const { return IsPostfixUpdate; }
5807
Alexey Bataev1d160b12015-03-13 12:27:31 +00005808private:
Alexey Bataevb78ca832015-04-01 03:33:17 +00005809 bool checkBinaryOperation(BinaryOperator *AtomicBinOp, unsigned DiagId = 0,
5810 unsigned NoteId = 0);
Alexey Bataev1d160b12015-03-13 12:27:31 +00005811};
5812} // namespace
5813
5814bool OpenMPAtomicUpdateChecker::checkBinaryOperation(
5815 BinaryOperator *AtomicBinOp, unsigned DiagId, unsigned NoteId) {
5816 ExprAnalysisErrorCode ErrorFound = NoError;
5817 SourceLocation ErrorLoc, NoteLoc;
5818 SourceRange ErrorRange, NoteRange;
5819 // Allowed constructs are:
5820 // x = x binop expr;
5821 // x = expr binop x;
5822 if (AtomicBinOp->getOpcode() == BO_Assign) {
5823 X = AtomicBinOp->getLHS();
5824 if (auto *AtomicInnerBinOp = dyn_cast<BinaryOperator>(
5825 AtomicBinOp->getRHS()->IgnoreParenImpCasts())) {
5826 if (AtomicInnerBinOp->isMultiplicativeOp() ||
5827 AtomicInnerBinOp->isAdditiveOp() || AtomicInnerBinOp->isShiftOp() ||
5828 AtomicInnerBinOp->isBitwiseOp()) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005829 Op = AtomicInnerBinOp->getOpcode();
5830 OpLoc = AtomicInnerBinOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005831 auto *LHS = AtomicInnerBinOp->getLHS();
5832 auto *RHS = AtomicInnerBinOp->getRHS();
5833 llvm::FoldingSetNodeID XId, LHSId, RHSId;
5834 X->IgnoreParenImpCasts()->Profile(XId, SemaRef.getASTContext(),
5835 /*Canonical=*/true);
5836 LHS->IgnoreParenImpCasts()->Profile(LHSId, SemaRef.getASTContext(),
5837 /*Canonical=*/true);
5838 RHS->IgnoreParenImpCasts()->Profile(RHSId, SemaRef.getASTContext(),
5839 /*Canonical=*/true);
5840 if (XId == LHSId) {
5841 E = RHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005842 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005843 } else if (XId == RHSId) {
5844 E = LHS;
Alexey Bataevb4505a72015-03-30 05:20:59 +00005845 IsXLHSInRHSPart = false;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005846 } else {
5847 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5848 ErrorRange = AtomicInnerBinOp->getSourceRange();
5849 NoteLoc = X->getExprLoc();
5850 NoteRange = X->getSourceRange();
5851 ErrorFound = NotAnUpdateExpression;
5852 }
5853 } else {
5854 ErrorLoc = AtomicInnerBinOp->getExprLoc();
5855 ErrorRange = AtomicInnerBinOp->getSourceRange();
5856 NoteLoc = AtomicInnerBinOp->getOperatorLoc();
5857 NoteRange = SourceRange(NoteLoc, NoteLoc);
5858 ErrorFound = NotABinaryOperator;
5859 }
5860 } else {
5861 NoteLoc = ErrorLoc = AtomicBinOp->getRHS()->getExprLoc();
5862 NoteRange = ErrorRange = AtomicBinOp->getRHS()->getSourceRange();
5863 ErrorFound = NotABinaryExpression;
5864 }
5865 } else {
5866 ErrorLoc = AtomicBinOp->getExprLoc();
5867 ErrorRange = AtomicBinOp->getSourceRange();
5868 NoteLoc = AtomicBinOp->getOperatorLoc();
5869 NoteRange = SourceRange(NoteLoc, NoteLoc);
5870 ErrorFound = NotAnAssignmentOp;
5871 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005872 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005873 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5874 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5875 return true;
5876 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005877 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005878 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005879}
5880
5881bool OpenMPAtomicUpdateChecker::checkStatement(Stmt *S, unsigned DiagId,
5882 unsigned NoteId) {
5883 ExprAnalysisErrorCode ErrorFound = NoError;
5884 SourceLocation ErrorLoc, NoteLoc;
5885 SourceRange ErrorRange, NoteRange;
5886 // Allowed constructs are:
5887 // x++;
5888 // x--;
5889 // ++x;
5890 // --x;
5891 // x binop= expr;
5892 // x = x binop expr;
5893 // x = expr binop x;
5894 if (auto *AtomicBody = dyn_cast<Expr>(S)) {
5895 AtomicBody = AtomicBody->IgnoreParenImpCasts();
5896 if (AtomicBody->getType()->isScalarType() ||
5897 AtomicBody->isInstantiationDependent()) {
5898 if (auto *AtomicCompAssignOp = dyn_cast<CompoundAssignOperator>(
5899 AtomicBody->IgnoreParenImpCasts())) {
5900 // Check for Compound Assignment Operation
Alexey Bataevb4505a72015-03-30 05:20:59 +00005901 Op = BinaryOperator::getOpForCompoundAssignment(
Alexey Bataev1d160b12015-03-13 12:27:31 +00005902 AtomicCompAssignOp->getOpcode());
Alexey Bataevb4505a72015-03-30 05:20:59 +00005903 OpLoc = AtomicCompAssignOp->getOperatorLoc();
Alexey Bataev1d160b12015-03-13 12:27:31 +00005904 E = AtomicCompAssignOp->getRHS();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005905 X = AtomicCompAssignOp->getLHS()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005906 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005907 } else if (auto *AtomicBinOp = dyn_cast<BinaryOperator>(
5908 AtomicBody->IgnoreParenImpCasts())) {
5909 // Check for Binary Operation
David Majnemer9d168222016-08-05 17:44:54 +00005910 if (checkBinaryOperation(AtomicBinOp, DiagId, NoteId))
Alexey Bataevb4505a72015-03-30 05:20:59 +00005911 return true;
David Majnemer9d168222016-08-05 17:44:54 +00005912 } else if (auto *AtomicUnaryOp = dyn_cast<UnaryOperator>(
5913 AtomicBody->IgnoreParenImpCasts())) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005914 // Check for Unary Operation
5915 if (AtomicUnaryOp->isIncrementDecrementOp()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00005916 IsPostfixUpdate = AtomicUnaryOp->isPostfix();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005917 Op = AtomicUnaryOp->isIncrementOp() ? BO_Add : BO_Sub;
5918 OpLoc = AtomicUnaryOp->getOperatorLoc();
Kelvin Li4f161cf2016-07-20 19:41:17 +00005919 X = AtomicUnaryOp->getSubExpr()->IgnoreParens();
Alexey Bataevb4505a72015-03-30 05:20:59 +00005920 E = SemaRef.ActOnIntegerConstant(OpLoc, /*uint64_t Val=*/1).get();
5921 IsXLHSInRHSPart = true;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005922 } else {
5923 ErrorFound = NotAnUnaryIncDecExpression;
5924 ErrorLoc = AtomicUnaryOp->getExprLoc();
5925 ErrorRange = AtomicUnaryOp->getSourceRange();
5926 NoteLoc = AtomicUnaryOp->getOperatorLoc();
5927 NoteRange = SourceRange(NoteLoc, NoteLoc);
5928 }
Alexey Bataev5a195472015-09-04 12:55:50 +00005929 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005930 ErrorFound = NotABinaryOrUnaryExpression;
5931 NoteLoc = ErrorLoc = AtomicBody->getExprLoc();
5932 NoteRange = ErrorRange = AtomicBody->getSourceRange();
5933 }
5934 } else {
5935 ErrorFound = NotAScalarType;
5936 NoteLoc = ErrorLoc = AtomicBody->getLocStart();
5937 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5938 }
5939 } else {
5940 ErrorFound = NotAnExpression;
5941 NoteLoc = ErrorLoc = S->getLocStart();
5942 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
5943 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00005944 if (ErrorFound != NoError && DiagId != 0 && NoteId != 0) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00005945 SemaRef.Diag(ErrorLoc, DiagId) << ErrorRange;
5946 SemaRef.Diag(NoteLoc, NoteId) << ErrorFound << NoteRange;
5947 return true;
5948 } else if (SemaRef.CurContext->isDependentContext())
Alexey Bataevb4505a72015-03-30 05:20:59 +00005949 E = X = UpdateExpr = nullptr;
Alexey Bataev5e018f92015-04-23 06:35:10 +00005950 if (ErrorFound == NoError && E && X) {
Alexey Bataevb4505a72015-03-30 05:20:59 +00005951 // Build an update expression of form 'OpaqueValueExpr(x) binop
5952 // OpaqueValueExpr(expr)' or 'OpaqueValueExpr(expr) binop
5953 // OpaqueValueExpr(x)' and then cast it to the type of the 'x' expression.
5954 auto *OVEX = new (SemaRef.getASTContext())
5955 OpaqueValueExpr(X->getExprLoc(), X->getType(), VK_RValue);
5956 auto *OVEExpr = new (SemaRef.getASTContext())
5957 OpaqueValueExpr(E->getExprLoc(), E->getType(), VK_RValue);
5958 auto Update =
5959 SemaRef.CreateBuiltinBinOp(OpLoc, Op, IsXLHSInRHSPart ? OVEX : OVEExpr,
5960 IsXLHSInRHSPart ? OVEExpr : OVEX);
5961 if (Update.isInvalid())
5962 return true;
5963 Update = SemaRef.PerformImplicitConversion(Update.get(), X->getType(),
5964 Sema::AA_Casting);
5965 if (Update.isInvalid())
5966 return true;
5967 UpdateExpr = Update.get();
5968 }
Alexey Bataev5e018f92015-04-23 06:35:10 +00005969 return ErrorFound != NoError;
Alexey Bataev1d160b12015-03-13 12:27:31 +00005970}
5971
Alexey Bataev0162e452014-07-22 10:10:35 +00005972StmtResult Sema::ActOnOpenMPAtomicDirective(ArrayRef<OMPClause *> Clauses,
5973 Stmt *AStmt,
5974 SourceLocation StartLoc,
5975 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00005976 if (!AStmt)
5977 return StmtError();
5978
David Majnemer9d168222016-08-05 17:44:54 +00005979 auto *CS = cast<CapturedStmt>(AStmt);
Alexey Bataev0162e452014-07-22 10:10:35 +00005980 // 1.2.2 OpenMP Language Terminology
5981 // Structured block - An executable statement with a single entry at the
5982 // top and a single exit at the bottom.
5983 // The point of exit cannot be a branch out of the structured block.
5984 // longjmp() and throw() must not violate the entry/exit criteria.
Alexey Bataevdea47612014-07-23 07:46:59 +00005985 OpenMPClauseKind AtomicKind = OMPC_unknown;
5986 SourceLocation AtomicKindLoc;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005987 for (auto *C : Clauses) {
Alexey Bataev67a4f222014-07-23 10:25:33 +00005988 if (C->getClauseKind() == OMPC_read || C->getClauseKind() == OMPC_write ||
Alexey Bataev459dec02014-07-24 06:46:57 +00005989 C->getClauseKind() == OMPC_update ||
5990 C->getClauseKind() == OMPC_capture) {
Alexey Bataevdea47612014-07-23 07:46:59 +00005991 if (AtomicKind != OMPC_unknown) {
5992 Diag(C->getLocStart(), diag::err_omp_atomic_several_clauses)
5993 << SourceRange(C->getLocStart(), C->getLocEnd());
5994 Diag(AtomicKindLoc, diag::note_omp_atomic_previous_clause)
5995 << getOpenMPClauseName(AtomicKind);
5996 } else {
5997 AtomicKind = C->getClauseKind();
5998 AtomicKindLoc = C->getLocStart();
Alexey Bataevf98b00c2014-07-23 02:27:21 +00005999 }
6000 }
6001 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006002
Alexey Bataev459dec02014-07-24 06:46:57 +00006003 auto Body = CS->getCapturedStmt();
Alexey Bataev10fec572015-03-11 04:48:56 +00006004 if (auto *EWC = dyn_cast<ExprWithCleanups>(Body))
6005 Body = EWC->getSubExpr();
6006
Alexey Bataev62cec442014-11-18 10:14:22 +00006007 Expr *X = nullptr;
6008 Expr *V = nullptr;
6009 Expr *E = nullptr;
Alexey Bataevb4505a72015-03-30 05:20:59 +00006010 Expr *UE = nullptr;
6011 bool IsXLHSInRHSPart = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006012 bool IsPostfixUpdate = false;
Alexey Bataev62cec442014-11-18 10:14:22 +00006013 // OpenMP [2.12.6, atomic Construct]
6014 // In the next expressions:
6015 // * x and v (as applicable) are both l-value expressions with scalar type.
6016 // * During the execution of an atomic region, multiple syntactic
6017 // occurrences of x must designate the same storage location.
6018 // * Neither of v and expr (as applicable) may access the storage location
6019 // designated by x.
6020 // * Neither of x and expr (as applicable) may access the storage location
6021 // designated by v.
6022 // * expr is an expression with scalar type.
6023 // * binop is one of +, *, -, /, &, ^, |, <<, or >>.
6024 // * binop, binop=, ++, and -- are not overloaded operators.
6025 // * The expression x binop expr must be numerically equivalent to x binop
6026 // (expr). This requirement is satisfied if the operators in expr have
6027 // precedence greater than binop, or by using parentheses around expr or
6028 // subexpressions of expr.
6029 // * The expression expr binop x must be numerically equivalent to (expr)
6030 // binop x. This requirement is satisfied if the operators in expr have
6031 // precedence equal to or greater than binop, or by using parentheses around
6032 // expr or subexpressions of expr.
6033 // * For forms that allow multiple occurrences of x, the number of times
6034 // that x is evaluated is unspecified.
Alexey Bataevdea47612014-07-23 07:46:59 +00006035 if (AtomicKind == OMPC_read) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006036 enum {
6037 NotAnExpression,
6038 NotAnAssignmentOp,
6039 NotAScalarType,
6040 NotAnLValue,
6041 NoError
6042 } ErrorFound = NoError;
Alexey Bataev62cec442014-11-18 10:14:22 +00006043 SourceLocation ErrorLoc, NoteLoc;
6044 SourceRange ErrorRange, NoteRange;
6045 // If clause is read:
6046 // v = x;
David Majnemer9d168222016-08-05 17:44:54 +00006047 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6048 auto *AtomicBinOp =
Alexey Bataev62cec442014-11-18 10:14:22 +00006049 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6050 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6051 X = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6052 V = AtomicBinOp->getLHS()->IgnoreParenImpCasts();
6053 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6054 (V->isInstantiationDependent() || V->getType()->isScalarType())) {
6055 if (!X->isLValue() || !V->isLValue()) {
6056 auto NotLValueExpr = X->isLValue() ? V : X;
6057 ErrorFound = NotAnLValue;
6058 ErrorLoc = AtomicBinOp->getExprLoc();
6059 ErrorRange = AtomicBinOp->getSourceRange();
6060 NoteLoc = NotLValueExpr->getExprLoc();
6061 NoteRange = NotLValueExpr->getSourceRange();
6062 }
6063 } else if (!X->isInstantiationDependent() ||
6064 !V->isInstantiationDependent()) {
6065 auto NotScalarExpr =
6066 (X->isInstantiationDependent() || X->getType()->isScalarType())
6067 ? V
6068 : X;
6069 ErrorFound = NotAScalarType;
6070 ErrorLoc = AtomicBinOp->getExprLoc();
6071 ErrorRange = AtomicBinOp->getSourceRange();
6072 NoteLoc = NotScalarExpr->getExprLoc();
6073 NoteRange = NotScalarExpr->getSourceRange();
6074 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006075 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataev62cec442014-11-18 10:14:22 +00006076 ErrorFound = NotAnAssignmentOp;
6077 ErrorLoc = AtomicBody->getExprLoc();
6078 ErrorRange = AtomicBody->getSourceRange();
6079 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6080 : AtomicBody->getExprLoc();
6081 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6082 : AtomicBody->getSourceRange();
6083 }
6084 } else {
6085 ErrorFound = NotAnExpression;
6086 NoteLoc = ErrorLoc = Body->getLocStart();
6087 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006088 }
Alexey Bataev62cec442014-11-18 10:14:22 +00006089 if (ErrorFound != NoError) {
6090 Diag(ErrorLoc, diag::err_omp_atomic_read_not_expression_statement)
6091 << ErrorRange;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006092 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6093 << NoteRange;
Alexey Bataev62cec442014-11-18 10:14:22 +00006094 return StmtError();
6095 } else if (CurContext->isDependentContext())
6096 V = X = nullptr;
Alexey Bataevdea47612014-07-23 07:46:59 +00006097 } else if (AtomicKind == OMPC_write) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006098 enum {
6099 NotAnExpression,
6100 NotAnAssignmentOp,
6101 NotAScalarType,
6102 NotAnLValue,
6103 NoError
6104 } ErrorFound = NoError;
Alexey Bataevf33eba62014-11-28 07:21:40 +00006105 SourceLocation ErrorLoc, NoteLoc;
6106 SourceRange ErrorRange, NoteRange;
6107 // If clause is write:
6108 // x = expr;
David Majnemer9d168222016-08-05 17:44:54 +00006109 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6110 auto *AtomicBinOp =
Alexey Bataevf33eba62014-11-28 07:21:40 +00006111 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6112 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
Alexey Bataevb8329262015-02-27 06:33:30 +00006113 X = AtomicBinOp->getLHS();
6114 E = AtomicBinOp->getRHS();
Alexey Bataevf33eba62014-11-28 07:21:40 +00006115 if ((X->isInstantiationDependent() || X->getType()->isScalarType()) &&
6116 (E->isInstantiationDependent() || E->getType()->isScalarType())) {
6117 if (!X->isLValue()) {
6118 ErrorFound = NotAnLValue;
6119 ErrorLoc = AtomicBinOp->getExprLoc();
6120 ErrorRange = AtomicBinOp->getSourceRange();
6121 NoteLoc = X->getExprLoc();
6122 NoteRange = X->getSourceRange();
6123 }
6124 } else if (!X->isInstantiationDependent() ||
6125 !E->isInstantiationDependent()) {
6126 auto NotScalarExpr =
6127 (X->isInstantiationDependent() || X->getType()->isScalarType())
6128 ? E
6129 : X;
6130 ErrorFound = NotAScalarType;
6131 ErrorLoc = AtomicBinOp->getExprLoc();
6132 ErrorRange = AtomicBinOp->getSourceRange();
6133 NoteLoc = NotScalarExpr->getExprLoc();
6134 NoteRange = NotScalarExpr->getSourceRange();
6135 }
Alexey Bataev5a195472015-09-04 12:55:50 +00006136 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevf33eba62014-11-28 07:21:40 +00006137 ErrorFound = NotAnAssignmentOp;
6138 ErrorLoc = AtomicBody->getExprLoc();
6139 ErrorRange = AtomicBody->getSourceRange();
6140 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6141 : AtomicBody->getExprLoc();
6142 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6143 : AtomicBody->getSourceRange();
6144 }
6145 } else {
6146 ErrorFound = NotAnExpression;
6147 NoteLoc = ErrorLoc = Body->getLocStart();
6148 NoteRange = ErrorRange = SourceRange(NoteLoc, NoteLoc);
Alexey Bataevdea47612014-07-23 07:46:59 +00006149 }
Alexey Bataevf33eba62014-11-28 07:21:40 +00006150 if (ErrorFound != NoError) {
6151 Diag(ErrorLoc, diag::err_omp_atomic_write_not_expression_statement)
6152 << ErrorRange;
6153 Diag(NoteLoc, diag::note_omp_atomic_read_write) << ErrorFound
6154 << NoteRange;
6155 return StmtError();
6156 } else if (CurContext->isDependentContext())
6157 E = X = nullptr;
Alexey Bataev67a4f222014-07-23 10:25:33 +00006158 } else if (AtomicKind == OMPC_update || AtomicKind == OMPC_unknown) {
Alexey Bataev1d160b12015-03-13 12:27:31 +00006159 // If clause is update:
6160 // x++;
6161 // x--;
6162 // ++x;
6163 // --x;
6164 // x binop= expr;
6165 // x = x binop expr;
6166 // x = expr binop x;
6167 OpenMPAtomicUpdateChecker Checker(*this);
6168 if (Checker.checkStatement(
6169 Body, (AtomicKind == OMPC_update)
6170 ? diag::err_omp_atomic_update_not_expression_statement
6171 : diag::err_omp_atomic_not_expression_statement,
6172 diag::note_omp_atomic_update))
Alexey Bataev67a4f222014-07-23 10:25:33 +00006173 return StmtError();
Alexey Bataev1d160b12015-03-13 12:27:31 +00006174 if (!CurContext->isDependentContext()) {
6175 E = Checker.getExpr();
6176 X = Checker.getX();
Alexey Bataevb4505a72015-03-30 05:20:59 +00006177 UE = Checker.getUpdateExpr();
6178 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev67a4f222014-07-23 10:25:33 +00006179 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006180 } else if (AtomicKind == OMPC_capture) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006181 enum {
6182 NotAnAssignmentOp,
6183 NotACompoundStatement,
6184 NotTwoSubstatements,
6185 NotASpecificExpression,
6186 NoError
6187 } ErrorFound = NoError;
6188 SourceLocation ErrorLoc, NoteLoc;
6189 SourceRange ErrorRange, NoteRange;
6190 if (auto *AtomicBody = dyn_cast<Expr>(Body)) {
6191 // If clause is a capture:
6192 // v = x++;
6193 // v = x--;
6194 // v = ++x;
6195 // v = --x;
6196 // v = x binop= expr;
6197 // v = x = x binop expr;
6198 // v = x = expr binop x;
6199 auto *AtomicBinOp =
6200 dyn_cast<BinaryOperator>(AtomicBody->IgnoreParenImpCasts());
6201 if (AtomicBinOp && AtomicBinOp->getOpcode() == BO_Assign) {
6202 V = AtomicBinOp->getLHS();
6203 Body = AtomicBinOp->getRHS()->IgnoreParenImpCasts();
6204 OpenMPAtomicUpdateChecker Checker(*this);
6205 if (Checker.checkStatement(
6206 Body, diag::err_omp_atomic_capture_not_expression_statement,
6207 diag::note_omp_atomic_update))
6208 return StmtError();
6209 E = Checker.getExpr();
6210 X = Checker.getX();
6211 UE = Checker.getUpdateExpr();
6212 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
6213 IsPostfixUpdate = Checker.isPostfixUpdate();
Alexey Bataev5a195472015-09-04 12:55:50 +00006214 } else if (!AtomicBody->isInstantiationDependent()) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006215 ErrorLoc = AtomicBody->getExprLoc();
6216 ErrorRange = AtomicBody->getSourceRange();
6217 NoteLoc = AtomicBinOp ? AtomicBinOp->getOperatorLoc()
6218 : AtomicBody->getExprLoc();
6219 NoteRange = AtomicBinOp ? AtomicBinOp->getSourceRange()
6220 : AtomicBody->getSourceRange();
6221 ErrorFound = NotAnAssignmentOp;
6222 }
6223 if (ErrorFound != NoError) {
6224 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_expression_statement)
6225 << ErrorRange;
6226 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6227 return StmtError();
6228 } else if (CurContext->isDependentContext()) {
6229 UE = V = E = X = nullptr;
6230 }
6231 } else {
6232 // If clause is a capture:
6233 // { v = x; x = expr; }
6234 // { v = x; x++; }
6235 // { v = x; x--; }
6236 // { v = x; ++x; }
6237 // { v = x; --x; }
6238 // { v = x; x binop= expr; }
6239 // { v = x; x = x binop expr; }
6240 // { v = x; x = expr binop x; }
6241 // { x++; v = x; }
6242 // { x--; v = x; }
6243 // { ++x; v = x; }
6244 // { --x; v = x; }
6245 // { x binop= expr; v = x; }
6246 // { x = x binop expr; v = x; }
6247 // { x = expr binop x; v = x; }
6248 if (auto *CS = dyn_cast<CompoundStmt>(Body)) {
6249 // Check that this is { expr1; expr2; }
6250 if (CS->size() == 2) {
6251 auto *First = CS->body_front();
6252 auto *Second = CS->body_back();
6253 if (auto *EWC = dyn_cast<ExprWithCleanups>(First))
6254 First = EWC->getSubExpr()->IgnoreParenImpCasts();
6255 if (auto *EWC = dyn_cast<ExprWithCleanups>(Second))
6256 Second = EWC->getSubExpr()->IgnoreParenImpCasts();
6257 // Need to find what subexpression is 'v' and what is 'x'.
6258 OpenMPAtomicUpdateChecker Checker(*this);
6259 bool IsUpdateExprFound = !Checker.checkStatement(Second);
6260 BinaryOperator *BinOp = nullptr;
6261 if (IsUpdateExprFound) {
6262 BinOp = dyn_cast<BinaryOperator>(First);
6263 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6264 }
6265 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6266 // { v = x; x++; }
6267 // { v = x; x--; }
6268 // { v = x; ++x; }
6269 // { v = x; --x; }
6270 // { v = x; x binop= expr; }
6271 // { v = x; x = x binop expr; }
6272 // { v = x; x = expr binop x; }
6273 // Check that the first expression has form v = x.
6274 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6275 llvm::FoldingSetNodeID XId, PossibleXId;
6276 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6277 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6278 IsUpdateExprFound = XId == PossibleXId;
6279 if (IsUpdateExprFound) {
6280 V = BinOp->getLHS();
6281 X = Checker.getX();
6282 E = Checker.getExpr();
6283 UE = Checker.getUpdateExpr();
6284 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006285 IsPostfixUpdate = true;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006286 }
6287 }
6288 if (!IsUpdateExprFound) {
6289 IsUpdateExprFound = !Checker.checkStatement(First);
6290 BinOp = nullptr;
6291 if (IsUpdateExprFound) {
6292 BinOp = dyn_cast<BinaryOperator>(Second);
6293 IsUpdateExprFound = BinOp && BinOp->getOpcode() == BO_Assign;
6294 }
6295 if (IsUpdateExprFound && !CurContext->isDependentContext()) {
6296 // { x++; v = x; }
6297 // { x--; v = x; }
6298 // { ++x; v = x; }
6299 // { --x; v = x; }
6300 // { x binop= expr; v = x; }
6301 // { x = x binop expr; v = x; }
6302 // { x = expr binop x; v = x; }
6303 // Check that the second expression has form v = x.
6304 auto *PossibleX = BinOp->getRHS()->IgnoreParenImpCasts();
6305 llvm::FoldingSetNodeID XId, PossibleXId;
6306 Checker.getX()->Profile(XId, Context, /*Canonical=*/true);
6307 PossibleX->Profile(PossibleXId, Context, /*Canonical=*/true);
6308 IsUpdateExprFound = XId == PossibleXId;
6309 if (IsUpdateExprFound) {
6310 V = BinOp->getLHS();
6311 X = Checker.getX();
6312 E = Checker.getExpr();
6313 UE = Checker.getUpdateExpr();
6314 IsXLHSInRHSPart = Checker.isXLHSInRHSPart();
Alexey Bataev5e018f92015-04-23 06:35:10 +00006315 IsPostfixUpdate = false;
Alexey Bataevb78ca832015-04-01 03:33:17 +00006316 }
6317 }
6318 }
6319 if (!IsUpdateExprFound) {
6320 // { v = x; x = expr; }
Alexey Bataev5a195472015-09-04 12:55:50 +00006321 auto *FirstExpr = dyn_cast<Expr>(First);
6322 auto *SecondExpr = dyn_cast<Expr>(Second);
6323 if (!FirstExpr || !SecondExpr ||
6324 !(FirstExpr->isInstantiationDependent() ||
6325 SecondExpr->isInstantiationDependent())) {
6326 auto *FirstBinOp = dyn_cast<BinaryOperator>(First);
6327 if (!FirstBinOp || FirstBinOp->getOpcode() != BO_Assign) {
Alexey Bataevb78ca832015-04-01 03:33:17 +00006328 ErrorFound = NotAnAssignmentOp;
Alexey Bataev5a195472015-09-04 12:55:50 +00006329 NoteLoc = ErrorLoc = FirstBinOp ? FirstBinOp->getOperatorLoc()
6330 : First->getLocStart();
6331 NoteRange = ErrorRange = FirstBinOp
6332 ? FirstBinOp->getSourceRange()
Alexey Bataevb78ca832015-04-01 03:33:17 +00006333 : SourceRange(ErrorLoc, ErrorLoc);
6334 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006335 auto *SecondBinOp = dyn_cast<BinaryOperator>(Second);
6336 if (!SecondBinOp || SecondBinOp->getOpcode() != BO_Assign) {
6337 ErrorFound = NotAnAssignmentOp;
6338 NoteLoc = ErrorLoc = SecondBinOp
6339 ? SecondBinOp->getOperatorLoc()
6340 : Second->getLocStart();
6341 NoteRange = ErrorRange =
6342 SecondBinOp ? SecondBinOp->getSourceRange()
6343 : SourceRange(ErrorLoc, ErrorLoc);
Alexey Bataevb78ca832015-04-01 03:33:17 +00006344 } else {
Alexey Bataev5a195472015-09-04 12:55:50 +00006345 auto *PossibleXRHSInFirst =
6346 FirstBinOp->getRHS()->IgnoreParenImpCasts();
6347 auto *PossibleXLHSInSecond =
6348 SecondBinOp->getLHS()->IgnoreParenImpCasts();
6349 llvm::FoldingSetNodeID X1Id, X2Id;
6350 PossibleXRHSInFirst->Profile(X1Id, Context,
6351 /*Canonical=*/true);
6352 PossibleXLHSInSecond->Profile(X2Id, Context,
6353 /*Canonical=*/true);
6354 IsUpdateExprFound = X1Id == X2Id;
6355 if (IsUpdateExprFound) {
6356 V = FirstBinOp->getLHS();
6357 X = SecondBinOp->getLHS();
6358 E = SecondBinOp->getRHS();
6359 UE = nullptr;
6360 IsXLHSInRHSPart = false;
6361 IsPostfixUpdate = true;
6362 } else {
6363 ErrorFound = NotASpecificExpression;
6364 ErrorLoc = FirstBinOp->getExprLoc();
6365 ErrorRange = FirstBinOp->getSourceRange();
6366 NoteLoc = SecondBinOp->getLHS()->getExprLoc();
6367 NoteRange = SecondBinOp->getRHS()->getSourceRange();
6368 }
Alexey Bataevb78ca832015-04-01 03:33:17 +00006369 }
6370 }
6371 }
6372 }
6373 } else {
6374 NoteLoc = ErrorLoc = Body->getLocStart();
6375 NoteRange = ErrorRange =
6376 SourceRange(Body->getLocStart(), Body->getLocStart());
6377 ErrorFound = NotTwoSubstatements;
6378 }
6379 } else {
6380 NoteLoc = ErrorLoc = Body->getLocStart();
6381 NoteRange = ErrorRange =
6382 SourceRange(Body->getLocStart(), Body->getLocStart());
6383 ErrorFound = NotACompoundStatement;
6384 }
6385 if (ErrorFound != NoError) {
6386 Diag(ErrorLoc, diag::err_omp_atomic_capture_not_compound_statement)
6387 << ErrorRange;
6388 Diag(NoteLoc, diag::note_omp_atomic_capture) << ErrorFound << NoteRange;
6389 return StmtError();
6390 } else if (CurContext->isDependentContext()) {
6391 UE = V = E = X = nullptr;
6392 }
Alexey Bataev459dec02014-07-24 06:46:57 +00006393 }
Alexey Bataevdea47612014-07-23 07:46:59 +00006394 }
Alexey Bataev0162e452014-07-22 10:10:35 +00006395
6396 getCurFunction()->setHasBranchProtectedScope();
6397
Alexey Bataev62cec442014-11-18 10:14:22 +00006398 return OMPAtomicDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt,
Alexey Bataevb78ca832015-04-01 03:33:17 +00006399 X, V, E, UE, IsXLHSInRHSPart,
6400 IsPostfixUpdate);
Alexey Bataev0162e452014-07-22 10:10:35 +00006401}
6402
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006403StmtResult Sema::ActOnOpenMPTargetDirective(ArrayRef<OMPClause *> Clauses,
6404 Stmt *AStmt,
6405 SourceLocation StartLoc,
6406 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006407 if (!AStmt)
6408 return StmtError();
6409
Samuel Antao4af1b7b2015-12-02 17:44:43 +00006410 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6411 // 1.2.2 OpenMP Language Terminology
6412 // Structured block - An executable statement with a single entry at the
6413 // top and a single exit at the bottom.
6414 // The point of exit cannot be a branch out of the structured block.
6415 // longjmp() and throw() must not violate the entry/exit criteria.
6416 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00006417 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target);
6418 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6419 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6420 // 1.2.2 OpenMP Language Terminology
6421 // Structured block - An executable statement with a single entry at the
6422 // top and a single exit at the bottom.
6423 // The point of exit cannot be a branch out of the structured block.
6424 // longjmp() and throw() must not violate the entry/exit criteria.
6425 CS->getCapturedDecl()->setNothrow();
6426 }
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006427
Alexey Bataev13314bf2014-10-09 04:18:56 +00006428 // OpenMP [2.16, Nesting of Regions]
6429 // If specified, a teams construct must be contained within a target
6430 // construct. That target construct must contain no statements or directives
6431 // outside of the teams construct.
6432 if (DSAStack->hasInnerTeamsRegion()) {
Alexey Bataev8451efa2018-01-15 19:06:12 +00006433 Stmt *S = CS->IgnoreContainers(/*IgnoreCaptured=*/true);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006434 bool OMPTeamsFound = true;
6435 if (auto *CS = dyn_cast<CompoundStmt>(S)) {
6436 auto I = CS->body_begin();
6437 while (I != CS->body_end()) {
David Majnemer9d168222016-08-05 17:44:54 +00006438 auto *OED = dyn_cast<OMPExecutableDirective>(*I);
Alexey Bataev13314bf2014-10-09 04:18:56 +00006439 if (!OED || !isOpenMPTeamsDirective(OED->getDirectiveKind())) {
6440 OMPTeamsFound = false;
6441 break;
6442 }
6443 ++I;
6444 }
6445 assert(I != CS->body_end() && "Not found statement");
6446 S = *I;
Kelvin Li3834dce2016-06-27 19:15:43 +00006447 } else {
6448 auto *OED = dyn_cast<OMPExecutableDirective>(S);
6449 OMPTeamsFound = OED && isOpenMPTeamsDirective(OED->getDirectiveKind());
Alexey Bataev13314bf2014-10-09 04:18:56 +00006450 }
6451 if (!OMPTeamsFound) {
6452 Diag(StartLoc, diag::err_omp_target_contains_not_only_teams);
6453 Diag(DSAStack->getInnerTeamsRegionLoc(),
6454 diag::note_omp_nested_teams_construct_here);
6455 Diag(S->getLocStart(), diag::note_omp_nested_statement_here)
6456 << isa<OMPExecutableDirective>(S);
6457 return StmtError();
6458 }
6459 }
6460
Alexey Bataev0bd520b2014-09-19 08:19:49 +00006461 getCurFunction()->setHasBranchProtectedScope();
6462
6463 return OMPTargetDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6464}
6465
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006466StmtResult
6467Sema::ActOnOpenMPTargetParallelDirective(ArrayRef<OMPClause *> Clauses,
6468 Stmt *AStmt, SourceLocation StartLoc,
6469 SourceLocation EndLoc) {
6470 if (!AStmt)
6471 return StmtError();
6472
6473 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6474 // 1.2.2 OpenMP Language Terminology
6475 // Structured block - An executable statement with a single entry at the
6476 // top and a single exit at the bottom.
6477 // The point of exit cannot be a branch out of the structured block.
6478 // longjmp() and throw() must not violate the entry/exit criteria.
6479 CS->getCapturedDecl()->setNothrow();
Alexey Bataev8451efa2018-01-15 19:06:12 +00006480 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel);
6481 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6482 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6483 // 1.2.2 OpenMP Language Terminology
6484 // Structured block - An executable statement with a single entry at the
6485 // top and a single exit at the bottom.
6486 // The point of exit cannot be a branch out of the structured block.
6487 // longjmp() and throw() must not violate the entry/exit criteria.
6488 CS->getCapturedDecl()->setNothrow();
6489 }
Arpith Chacko Jacobe955b3d2016-01-26 18:48:41 +00006490
6491 getCurFunction()->setHasBranchProtectedScope();
6492
6493 return OMPTargetParallelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6494 AStmt);
6495}
6496
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006497StmtResult Sema::ActOnOpenMPTargetParallelForDirective(
6498 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6499 SourceLocation EndLoc,
6500 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6501 if (!AStmt)
6502 return StmtError();
6503
6504 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6505 // 1.2.2 OpenMP Language Terminology
6506 // Structured block - An executable statement with a single entry at the
6507 // top and a single exit at the bottom.
6508 // The point of exit cannot be a branch out of the structured block.
6509 // longjmp() and throw() must not violate the entry/exit criteria.
6510 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006511 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
6512 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6513 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6514 // 1.2.2 OpenMP Language Terminology
6515 // Structured block - An executable statement with a single entry at the
6516 // top and a single exit at the bottom.
6517 // The point of exit cannot be a branch out of the structured block.
6518 // longjmp() and throw() must not violate the entry/exit criteria.
6519 CS->getCapturedDecl()->setNothrow();
6520 }
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006521
6522 OMPLoopDirective::HelperExprs B;
6523 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6524 // define the nested loops number.
6525 unsigned NestedLoopCount =
6526 CheckOpenMPLoop(OMPD_target_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00006527 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006528 VarsWithImplicitDSA, B);
6529 if (NestedLoopCount == 0)
6530 return StmtError();
6531
6532 assert((CurContext->isDependentContext() || B.builtAll()) &&
6533 "omp target parallel for loop exprs were not built");
6534
6535 if (!CurContext->isDependentContext()) {
6536 // Finalize the clauses that need pre-built expressions for CodeGen.
6537 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006538 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006539 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006540 B.NumIterations, *this, CurScope,
6541 DSAStack))
Arpith Chacko Jacob05bebb52016-02-03 15:46:42 +00006542 return StmtError();
6543 }
6544 }
6545
6546 getCurFunction()->setHasBranchProtectedScope();
6547 return OMPTargetParallelForDirective::Create(Context, StartLoc, EndLoc,
6548 NestedLoopCount, Clauses, AStmt,
6549 B, DSAStack->isCancelRegion());
6550}
6551
Alexey Bataev95b64a92017-05-30 16:00:04 +00006552/// Check for existence of a map clause in the list of clauses.
6553static bool hasClauses(ArrayRef<OMPClause *> Clauses,
6554 const OpenMPClauseKind K) {
6555 return llvm::any_of(
6556 Clauses, [K](const OMPClause *C) { return C->getClauseKind() == K; });
6557}
Samuel Antaodf67fc42016-01-19 19:15:56 +00006558
Alexey Bataev95b64a92017-05-30 16:00:04 +00006559template <typename... Params>
6560static bool hasClauses(ArrayRef<OMPClause *> Clauses, const OpenMPClauseKind K,
6561 const Params... ClauseTypes) {
6562 return hasClauses(Clauses, K) || hasClauses(Clauses, ClauseTypes...);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006563}
6564
Michael Wong65f367f2015-07-21 13:44:28 +00006565StmtResult Sema::ActOnOpenMPTargetDataDirective(ArrayRef<OMPClause *> Clauses,
6566 Stmt *AStmt,
6567 SourceLocation StartLoc,
6568 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006569 if (!AStmt)
6570 return StmtError();
6571
6572 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6573
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006574 // OpenMP [2.10.1, Restrictions, p. 97]
6575 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006576 if (!hasClauses(Clauses, OMPC_map, OMPC_use_device_ptr)) {
6577 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6578 << "'map' or 'use_device_ptr'"
David Majnemer9d168222016-08-05 17:44:54 +00006579 << getOpenMPDirectiveName(OMPD_target_data);
Arpith Chacko Jacob46a04bb2016-01-21 19:57:55 +00006580 return StmtError();
6581 }
6582
Michael Wong65f367f2015-07-21 13:44:28 +00006583 getCurFunction()->setHasBranchProtectedScope();
6584
6585 return OMPTargetDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6586 AStmt);
6587}
6588
Samuel Antaodf67fc42016-01-19 19:15:56 +00006589StmtResult
6590Sema::ActOnOpenMPTargetEnterDataDirective(ArrayRef<OMPClause *> Clauses,
6591 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006592 SourceLocation EndLoc, Stmt *AStmt) {
6593 if (!AStmt)
6594 return StmtError();
6595
6596 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6597 // 1.2.2 OpenMP Language Terminology
6598 // Structured block - An executable statement with a single entry at the
6599 // top and a single exit at the bottom.
6600 // The point of exit cannot be a branch out of the structured block.
6601 // longjmp() and throw() must not violate the entry/exit criteria.
6602 CS->getCapturedDecl()->setNothrow();
6603 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_enter_data);
6604 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6605 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6606 // 1.2.2 OpenMP Language Terminology
6607 // Structured block - An executable statement with a single entry at the
6608 // top and a single exit at the bottom.
6609 // The point of exit cannot be a branch out of the structured block.
6610 // longjmp() and throw() must not violate the entry/exit criteria.
6611 CS->getCapturedDecl()->setNothrow();
6612 }
6613
Samuel Antaodf67fc42016-01-19 19:15:56 +00006614 // OpenMP [2.10.2, Restrictions, p. 99]
6615 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006616 if (!hasClauses(Clauses, OMPC_map)) {
6617 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6618 << "'map'" << getOpenMPDirectiveName(OMPD_target_enter_data);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006619 return StmtError();
6620 }
6621
Alexey Bataev7828b252017-11-21 17:08:48 +00006622 return OMPTargetEnterDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6623 AStmt);
Samuel Antaodf67fc42016-01-19 19:15:56 +00006624}
6625
Samuel Antao72590762016-01-19 20:04:50 +00006626StmtResult
6627Sema::ActOnOpenMPTargetExitDataDirective(ArrayRef<OMPClause *> Clauses,
6628 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006629 SourceLocation EndLoc, Stmt *AStmt) {
6630 if (!AStmt)
6631 return StmtError();
6632
6633 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6634 // 1.2.2 OpenMP Language Terminology
6635 // Structured block - An executable statement with a single entry at the
6636 // top and a single exit at the bottom.
6637 // The point of exit cannot be a branch out of the structured block.
6638 // longjmp() and throw() must not violate the entry/exit criteria.
6639 CS->getCapturedDecl()->setNothrow();
6640 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_exit_data);
6641 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6642 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6643 // 1.2.2 OpenMP Language Terminology
6644 // Structured block - An executable statement with a single entry at the
6645 // top and a single exit at the bottom.
6646 // The point of exit cannot be a branch out of the structured block.
6647 // longjmp() and throw() must not violate the entry/exit criteria.
6648 CS->getCapturedDecl()->setNothrow();
6649 }
6650
Samuel Antao72590762016-01-19 20:04:50 +00006651 // OpenMP [2.10.3, Restrictions, p. 102]
6652 // At least one map clause must appear on the directive.
Alexey Bataev95b64a92017-05-30 16:00:04 +00006653 if (!hasClauses(Clauses, OMPC_map)) {
6654 Diag(StartLoc, diag::err_omp_no_clause_for_directive)
6655 << "'map'" << getOpenMPDirectiveName(OMPD_target_exit_data);
Samuel Antao72590762016-01-19 20:04:50 +00006656 return StmtError();
6657 }
6658
Alexey Bataev7828b252017-11-21 17:08:48 +00006659 return OMPTargetExitDataDirective::Create(Context, StartLoc, EndLoc, Clauses,
6660 AStmt);
Samuel Antao72590762016-01-19 20:04:50 +00006661}
6662
Samuel Antao686c70c2016-05-26 17:30:50 +00006663StmtResult Sema::ActOnOpenMPTargetUpdateDirective(ArrayRef<OMPClause *> Clauses,
6664 SourceLocation StartLoc,
Alexey Bataev7828b252017-11-21 17:08:48 +00006665 SourceLocation EndLoc,
6666 Stmt *AStmt) {
6667 if (!AStmt)
6668 return StmtError();
6669
6670 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6671 // 1.2.2 OpenMP Language Terminology
6672 // Structured block - An executable statement with a single entry at the
6673 // top and a single exit at the bottom.
6674 // The point of exit cannot be a branch out of the structured block.
6675 // longjmp() and throw() must not violate the entry/exit criteria.
6676 CS->getCapturedDecl()->setNothrow();
6677 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_update);
6678 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6679 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6680 // 1.2.2 OpenMP Language Terminology
6681 // Structured block - An executable statement with a single entry at the
6682 // top and a single exit at the bottom.
6683 // The point of exit cannot be a branch out of the structured block.
6684 // longjmp() and throw() must not violate the entry/exit criteria.
6685 CS->getCapturedDecl()->setNothrow();
6686 }
6687
Alexey Bataev95b64a92017-05-30 16:00:04 +00006688 if (!hasClauses(Clauses, OMPC_to, OMPC_from)) {
Samuel Antao686c70c2016-05-26 17:30:50 +00006689 Diag(StartLoc, diag::err_omp_at_least_one_motion_clause_required);
6690 return StmtError();
6691 }
Alexey Bataev7828b252017-11-21 17:08:48 +00006692 return OMPTargetUpdateDirective::Create(Context, StartLoc, EndLoc, Clauses,
6693 AStmt);
Samuel Antao686c70c2016-05-26 17:30:50 +00006694}
6695
Alexey Bataev13314bf2014-10-09 04:18:56 +00006696StmtResult Sema::ActOnOpenMPTeamsDirective(ArrayRef<OMPClause *> Clauses,
6697 Stmt *AStmt, SourceLocation StartLoc,
6698 SourceLocation EndLoc) {
Alexey Bataev6b8046a2015-09-03 07:23:48 +00006699 if (!AStmt)
6700 return StmtError();
6701
Alexey Bataev13314bf2014-10-09 04:18:56 +00006702 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6703 // 1.2.2 OpenMP Language Terminology
6704 // Structured block - An executable statement with a single entry at the
6705 // top and a single exit at the bottom.
6706 // The point of exit cannot be a branch out of the structured block.
6707 // longjmp() and throw() must not violate the entry/exit criteria.
6708 CS->getCapturedDecl()->setNothrow();
6709
6710 getCurFunction()->setHasBranchProtectedScope();
6711
Alexey Bataevceabd412017-11-30 18:01:54 +00006712 DSAStack->setParentTeamsRegionLoc(StartLoc);
6713
Alexey Bataev13314bf2014-10-09 04:18:56 +00006714 return OMPTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses, AStmt);
6715}
6716
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006717StmtResult
6718Sema::ActOnOpenMPCancellationPointDirective(SourceLocation StartLoc,
6719 SourceLocation EndLoc,
6720 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00006721 if (DSAStack->isParentNowaitRegion()) {
6722 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 0;
6723 return StmtError();
6724 }
6725 if (DSAStack->isParentOrderedRegion()) {
6726 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 0;
6727 return StmtError();
6728 }
6729 return OMPCancellationPointDirective::Create(Context, StartLoc, EndLoc,
6730 CancelRegion);
6731}
6732
Alexey Bataev87933c72015-09-18 08:07:34 +00006733StmtResult Sema::ActOnOpenMPCancelDirective(ArrayRef<OMPClause *> Clauses,
6734 SourceLocation StartLoc,
Alexey Bataev80909872015-07-02 11:25:17 +00006735 SourceLocation EndLoc,
6736 OpenMPDirectiveKind CancelRegion) {
Alexey Bataev80909872015-07-02 11:25:17 +00006737 if (DSAStack->isParentNowaitRegion()) {
6738 Diag(StartLoc, diag::err_omp_parent_cancel_region_nowait) << 1;
6739 return StmtError();
6740 }
6741 if (DSAStack->isParentOrderedRegion()) {
6742 Diag(StartLoc, diag::err_omp_parent_cancel_region_ordered) << 1;
6743 return StmtError();
6744 }
Alexey Bataev25e5b442015-09-15 12:52:43 +00006745 DSAStack->setParentCancelRegion(/*Cancel=*/true);
Alexey Bataev87933c72015-09-18 08:07:34 +00006746 return OMPCancelDirective::Create(Context, StartLoc, EndLoc, Clauses,
6747 CancelRegion);
Alexey Bataev80909872015-07-02 11:25:17 +00006748}
6749
Alexey Bataev382967a2015-12-08 12:06:20 +00006750static bool checkGrainsizeNumTasksClauses(Sema &S,
6751 ArrayRef<OMPClause *> Clauses) {
6752 OMPClause *PrevClause = nullptr;
6753 bool ErrorFound = false;
6754 for (auto *C : Clauses) {
6755 if (C->getClauseKind() == OMPC_grainsize ||
6756 C->getClauseKind() == OMPC_num_tasks) {
6757 if (!PrevClause)
6758 PrevClause = C;
6759 else if (PrevClause->getClauseKind() != C->getClauseKind()) {
6760 S.Diag(C->getLocStart(),
6761 diag::err_omp_grainsize_num_tasks_mutually_exclusive)
6762 << getOpenMPClauseName(C->getClauseKind())
6763 << getOpenMPClauseName(PrevClause->getClauseKind());
6764 S.Diag(PrevClause->getLocStart(),
6765 diag::note_omp_previous_grainsize_num_tasks)
6766 << getOpenMPClauseName(PrevClause->getClauseKind());
6767 ErrorFound = true;
6768 }
6769 }
6770 }
6771 return ErrorFound;
6772}
6773
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006774static bool checkReductionClauseWithNogroup(Sema &S,
6775 ArrayRef<OMPClause *> Clauses) {
6776 OMPClause *ReductionClause = nullptr;
6777 OMPClause *NogroupClause = nullptr;
6778 for (auto *C : Clauses) {
6779 if (C->getClauseKind() == OMPC_reduction) {
6780 ReductionClause = C;
6781 if (NogroupClause)
6782 break;
6783 continue;
6784 }
6785 if (C->getClauseKind() == OMPC_nogroup) {
6786 NogroupClause = C;
6787 if (ReductionClause)
6788 break;
6789 continue;
6790 }
6791 }
6792 if (ReductionClause && NogroupClause) {
6793 S.Diag(ReductionClause->getLocStart(), diag::err_omp_reduction_with_nogroup)
6794 << SourceRange(NogroupClause->getLocStart(),
6795 NogroupClause->getLocEnd());
6796 return true;
6797 }
6798 return false;
6799}
6800
Alexey Bataev49f6e782015-12-01 04:18:41 +00006801StmtResult Sema::ActOnOpenMPTaskLoopDirective(
6802 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6803 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006804 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev49f6e782015-12-01 04:18:41 +00006805 if (!AStmt)
6806 return StmtError();
6807
6808 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6809 OMPLoopDirective::HelperExprs B;
6810 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6811 // define the nested loops number.
6812 unsigned NestedLoopCount =
6813 CheckOpenMPLoop(OMPD_taskloop, getCollapseNumberExpr(Clauses),
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006814 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
Alexey Bataev49f6e782015-12-01 04:18:41 +00006815 VarsWithImplicitDSA, B);
6816 if (NestedLoopCount == 0)
6817 return StmtError();
6818
6819 assert((CurContext->isDependentContext() || B.builtAll()) &&
6820 "omp for loop exprs were not built");
6821
Alexey Bataev382967a2015-12-08 12:06:20 +00006822 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6823 // The grainsize clause and num_tasks clause are mutually exclusive and may
6824 // not appear on the same taskloop directive.
6825 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6826 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006827 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6828 // If a reduction clause is present on the taskloop directive, the nogroup
6829 // clause must not be specified.
6830 if (checkReductionClauseWithNogroup(*this, Clauses))
6831 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006832
Alexey Bataev49f6e782015-12-01 04:18:41 +00006833 getCurFunction()->setHasBranchProtectedScope();
6834 return OMPTaskLoopDirective::Create(Context, StartLoc, EndLoc,
6835 NestedLoopCount, Clauses, AStmt, B);
6836}
6837
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006838StmtResult Sema::ActOnOpenMPTaskLoopSimdDirective(
6839 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6840 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006841 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006842 if (!AStmt)
6843 return StmtError();
6844
6845 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6846 OMPLoopDirective::HelperExprs B;
6847 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
6848 // define the nested loops number.
6849 unsigned NestedLoopCount =
6850 CheckOpenMPLoop(OMPD_taskloop_simd, getCollapseNumberExpr(Clauses),
6851 /*OrderedLoopCountExpr=*/nullptr, AStmt, *this, *DSAStack,
6852 VarsWithImplicitDSA, B);
6853 if (NestedLoopCount == 0)
6854 return StmtError();
6855
6856 assert((CurContext->isDependentContext() || B.builtAll()) &&
6857 "omp for loop exprs were not built");
6858
Alexey Bataev5a3af132016-03-29 08:58:54 +00006859 if (!CurContext->isDependentContext()) {
6860 // Finalize the clauses that need pre-built expressions for CodeGen.
6861 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00006862 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006863 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
Alexey Bataev5dff95c2016-04-22 03:56:56 +00006864 B.NumIterations, *this, CurScope,
6865 DSAStack))
Alexey Bataev5a3af132016-03-29 08:58:54 +00006866 return StmtError();
6867 }
6868 }
6869
Alexey Bataev382967a2015-12-08 12:06:20 +00006870 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6871 // The grainsize clause and num_tasks clause are mutually exclusive and may
6872 // not appear on the same taskloop directive.
6873 if (checkGrainsizeNumTasksClauses(*this, Clauses))
6874 return StmtError();
Alexey Bataevbcd0ae02017-07-11 19:16:44 +00006875 // OpenMP, [2.9.2 taskloop Construct, Restrictions]
6876 // If a reduction clause is present on the taskloop directive, the nogroup
6877 // clause must not be specified.
6878 if (checkReductionClauseWithNogroup(*this, Clauses))
6879 return StmtError();
Alexey Bataev438388c2017-11-22 18:34:02 +00006880 if (checkSimdlenSafelenSpecified(*this, Clauses))
6881 return StmtError();
Alexey Bataev382967a2015-12-08 12:06:20 +00006882
Alexey Bataev0a6ed842015-12-03 09:40:15 +00006883 getCurFunction()->setHasBranchProtectedScope();
6884 return OMPTaskLoopSimdDirective::Create(Context, StartLoc, EndLoc,
6885 NestedLoopCount, Clauses, AStmt, B);
6886}
6887
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006888StmtResult Sema::ActOnOpenMPDistributeDirective(
6889 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6890 SourceLocation EndLoc,
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00006891 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00006892 if (!AStmt)
6893 return StmtError();
6894
6895 assert(isa<CapturedStmt>(AStmt) && "Captured statement expected");
6896 OMPLoopDirective::HelperExprs B;
6897 // In presence of clause 'collapse' with number of loops, it will
6898 // define the nested loops number.
6899 unsigned NestedLoopCount =
6900 CheckOpenMPLoop(OMPD_distribute, getCollapseNumberExpr(Clauses),
6901 nullptr /*ordered not a clause on distribute*/, AStmt,
6902 *this, *DSAStack, VarsWithImplicitDSA, B);
6903 if (NestedLoopCount == 0)
6904 return StmtError();
6905
6906 assert((CurContext->isDependentContext() || B.builtAll()) &&
6907 "omp for loop exprs were not built");
6908
6909 getCurFunction()->setHasBranchProtectedScope();
6910 return OMPDistributeDirective::Create(Context, StartLoc, EndLoc,
6911 NestedLoopCount, Clauses, AStmt, B);
6912}
6913
Carlo Bertolli9925f152016-06-27 14:55:37 +00006914StmtResult Sema::ActOnOpenMPDistributeParallelForDirective(
6915 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6916 SourceLocation EndLoc,
6917 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6918 if (!AStmt)
6919 return StmtError();
6920
6921 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6922 // 1.2.2 OpenMP Language Terminology
6923 // Structured block - An executable statement with a single entry at the
6924 // top and a single exit at the bottom.
6925 // The point of exit cannot be a branch out of the structured block.
6926 // longjmp() and throw() must not violate the entry/exit criteria.
6927 CS->getCapturedDecl()->setNothrow();
Alexey Bataev7f96c372017-11-22 17:19:31 +00006928 for (int ThisCaptureLevel =
6929 getOpenMPCaptureLevels(OMPD_distribute_parallel_for);
6930 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6931 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6932 // 1.2.2 OpenMP Language Terminology
6933 // Structured block - An executable statement with a single entry at the
6934 // top and a single exit at the bottom.
6935 // The point of exit cannot be a branch out of the structured block.
6936 // longjmp() and throw() must not violate the entry/exit criteria.
6937 CS->getCapturedDecl()->setNothrow();
6938 }
Carlo Bertolli9925f152016-06-27 14:55:37 +00006939
6940 OMPLoopDirective::HelperExprs B;
6941 // In presence of clause 'collapse' with number of loops, it will
6942 // define the nested loops number.
6943 unsigned NestedLoopCount = CheckOpenMPLoop(
6944 OMPD_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Alexey Bataev7f96c372017-11-22 17:19:31 +00006945 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Carlo Bertolli9925f152016-06-27 14:55:37 +00006946 VarsWithImplicitDSA, B);
6947 if (NestedLoopCount == 0)
6948 return StmtError();
6949
6950 assert((CurContext->isDependentContext() || B.builtAll()) &&
6951 "omp for loop exprs were not built");
6952
6953 getCurFunction()->setHasBranchProtectedScope();
6954 return OMPDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00006955 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
6956 DSAStack->isCancelRegion());
Carlo Bertolli9925f152016-06-27 14:55:37 +00006957}
6958
Kelvin Li4a39add2016-07-05 05:00:15 +00006959StmtResult Sema::ActOnOpenMPDistributeParallelForSimdDirective(
6960 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
6961 SourceLocation EndLoc,
6962 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
6963 if (!AStmt)
6964 return StmtError();
6965
6966 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
6967 // 1.2.2 OpenMP Language Terminology
6968 // Structured block - An executable statement with a single entry at the
6969 // top and a single exit at the bottom.
6970 // The point of exit cannot be a branch out of the structured block.
6971 // longjmp() and throw() must not violate the entry/exit criteria.
6972 CS->getCapturedDecl()->setNothrow();
Alexey Bataev974acd62017-11-27 19:38:52 +00006973 for (int ThisCaptureLevel =
6974 getOpenMPCaptureLevels(OMPD_distribute_parallel_for_simd);
6975 ThisCaptureLevel > 1; --ThisCaptureLevel) {
6976 CS = cast<CapturedStmt>(CS->getCapturedStmt());
6977 // 1.2.2 OpenMP Language Terminology
6978 // Structured block - An executable statement with a single entry at the
6979 // top and a single exit at the bottom.
6980 // The point of exit cannot be a branch out of the structured block.
6981 // longjmp() and throw() must not violate the entry/exit criteria.
6982 CS->getCapturedDecl()->setNothrow();
6983 }
Kelvin Li4a39add2016-07-05 05:00:15 +00006984
6985 OMPLoopDirective::HelperExprs B;
6986 // In presence of clause 'collapse' with number of loops, it will
6987 // define the nested loops number.
6988 unsigned NestedLoopCount = CheckOpenMPLoop(
6989 OMPD_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev974acd62017-11-27 19:38:52 +00006990 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li4a39add2016-07-05 05:00:15 +00006991 VarsWithImplicitDSA, B);
6992 if (NestedLoopCount == 0)
6993 return StmtError();
6994
6995 assert((CurContext->isDependentContext() || B.builtAll()) &&
6996 "omp for loop exprs were not built");
6997
Alexey Bataev438388c2017-11-22 18:34:02 +00006998 if (!CurContext->isDependentContext()) {
6999 // Finalize the clauses that need pre-built expressions for CodeGen.
7000 for (auto C : Clauses) {
7001 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7002 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7003 B.NumIterations, *this, CurScope,
7004 DSAStack))
7005 return StmtError();
7006 }
7007 }
7008
Kelvin Lic5609492016-07-15 04:39:07 +00007009 if (checkSimdlenSafelenSpecified(*this, Clauses))
7010 return StmtError();
7011
Kelvin Li4a39add2016-07-05 05:00:15 +00007012 getCurFunction()->setHasBranchProtectedScope();
7013 return OMPDistributeParallelForSimdDirective::Create(
7014 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7015}
7016
Kelvin Li787f3fc2016-07-06 04:45:38 +00007017StmtResult Sema::ActOnOpenMPDistributeSimdDirective(
7018 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7019 SourceLocation EndLoc,
7020 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7021 if (!AStmt)
7022 return StmtError();
7023
7024 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7025 // 1.2.2 OpenMP Language Terminology
7026 // Structured block - An executable statement with a single entry at the
7027 // top and a single exit at the bottom.
7028 // The point of exit cannot be a branch out of the structured block.
7029 // longjmp() and throw() must not violate the entry/exit criteria.
7030 CS->getCapturedDecl()->setNothrow();
Alexey Bataev617db5f2017-12-04 15:38:33 +00007031 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_distribute_simd);
7032 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7033 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7034 // 1.2.2 OpenMP Language Terminology
7035 // Structured block - An executable statement with a single entry at the
7036 // top and a single exit at the bottom.
7037 // The point of exit cannot be a branch out of the structured block.
7038 // longjmp() and throw() must not violate the entry/exit criteria.
7039 CS->getCapturedDecl()->setNothrow();
7040 }
Kelvin Li787f3fc2016-07-06 04:45:38 +00007041
7042 OMPLoopDirective::HelperExprs B;
7043 // In presence of clause 'collapse' with number of loops, it will
7044 // define the nested loops number.
7045 unsigned NestedLoopCount =
7046 CheckOpenMPLoop(OMPD_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev617db5f2017-12-04 15:38:33 +00007047 nullptr /*ordered not a clause on distribute*/, CS, *this,
7048 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li787f3fc2016-07-06 04:45:38 +00007049 if (NestedLoopCount == 0)
7050 return StmtError();
7051
7052 assert((CurContext->isDependentContext() || B.builtAll()) &&
7053 "omp for loop exprs were not built");
7054
Alexey Bataev438388c2017-11-22 18:34:02 +00007055 if (!CurContext->isDependentContext()) {
7056 // Finalize the clauses that need pre-built expressions for CodeGen.
7057 for (auto C : Clauses) {
7058 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7059 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7060 B.NumIterations, *this, CurScope,
7061 DSAStack))
7062 return StmtError();
7063 }
7064 }
7065
Kelvin Lic5609492016-07-15 04:39:07 +00007066 if (checkSimdlenSafelenSpecified(*this, Clauses))
7067 return StmtError();
7068
Kelvin Li787f3fc2016-07-06 04:45:38 +00007069 getCurFunction()->setHasBranchProtectedScope();
7070 return OMPDistributeSimdDirective::Create(Context, StartLoc, EndLoc,
7071 NestedLoopCount, Clauses, AStmt, B);
7072}
7073
Kelvin Lia579b912016-07-14 02:54:56 +00007074StmtResult Sema::ActOnOpenMPTargetParallelForSimdDirective(
7075 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7076 SourceLocation EndLoc,
7077 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7078 if (!AStmt)
7079 return StmtError();
7080
7081 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7082 // 1.2.2 OpenMP Language Terminology
7083 // Structured block - An executable statement with a single entry at the
7084 // top and a single exit at the bottom.
7085 // The point of exit cannot be a branch out of the structured block.
7086 // longjmp() and throw() must not violate the entry/exit criteria.
7087 CS->getCapturedDecl()->setNothrow();
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007088 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_parallel_for);
7089 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7090 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7091 // 1.2.2 OpenMP Language Terminology
7092 // Structured block - An executable statement with a single entry at the
7093 // top and a single exit at the bottom.
7094 // The point of exit cannot be a branch out of the structured block.
7095 // longjmp() and throw() must not violate the entry/exit criteria.
7096 CS->getCapturedDecl()->setNothrow();
7097 }
Kelvin Lia579b912016-07-14 02:54:56 +00007098
7099 OMPLoopDirective::HelperExprs B;
7100 // In presence of clause 'collapse' or 'ordered' with number of loops, it will
7101 // define the nested loops number.
7102 unsigned NestedLoopCount = CheckOpenMPLoop(
7103 OMPD_target_parallel_for_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007104 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Lia579b912016-07-14 02:54:56 +00007105 VarsWithImplicitDSA, B);
7106 if (NestedLoopCount == 0)
7107 return StmtError();
7108
7109 assert((CurContext->isDependentContext() || B.builtAll()) &&
7110 "omp target parallel for simd loop exprs were not built");
7111
7112 if (!CurContext->isDependentContext()) {
7113 // Finalize the clauses that need pre-built expressions for CodeGen.
7114 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007115 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Lia579b912016-07-14 02:54:56 +00007116 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7117 B.NumIterations, *this, CurScope,
7118 DSAStack))
7119 return StmtError();
7120 }
7121 }
Kelvin Lic5609492016-07-15 04:39:07 +00007122 if (checkSimdlenSafelenSpecified(*this, Clauses))
Kelvin Lia579b912016-07-14 02:54:56 +00007123 return StmtError();
7124
7125 getCurFunction()->setHasBranchProtectedScope();
7126 return OMPTargetParallelForSimdDirective::Create(
7127 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7128}
7129
Kelvin Li986330c2016-07-20 22:57:10 +00007130StmtResult Sema::ActOnOpenMPTargetSimdDirective(
7131 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7132 SourceLocation EndLoc,
7133 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7134 if (!AStmt)
7135 return StmtError();
7136
7137 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7138 // 1.2.2 OpenMP Language Terminology
7139 // Structured block - An executable statement with a single entry at the
7140 // top and a single exit at the bottom.
7141 // The point of exit cannot be a branch out of the structured block.
7142 // longjmp() and throw() must not violate the entry/exit criteria.
7143 CS->getCapturedDecl()->setNothrow();
Alexey Bataevf8365372017-11-17 17:57:25 +00007144 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_simd);
7145 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7146 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7147 // 1.2.2 OpenMP Language Terminology
7148 // Structured block - An executable statement with a single entry at the
7149 // top and a single exit at the bottom.
7150 // The point of exit cannot be a branch out of the structured block.
7151 // longjmp() and throw() must not violate the entry/exit criteria.
7152 CS->getCapturedDecl()->setNothrow();
7153 }
7154
Kelvin Li986330c2016-07-20 22:57:10 +00007155 OMPLoopDirective::HelperExprs B;
7156 // In presence of clause 'collapse' with number of loops, it will define the
7157 // nested loops number.
David Majnemer9d168222016-08-05 17:44:54 +00007158 unsigned NestedLoopCount =
Kelvin Li986330c2016-07-20 22:57:10 +00007159 CheckOpenMPLoop(OMPD_target_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevf8365372017-11-17 17:57:25 +00007160 getOrderedNumberExpr(Clauses), CS, *this, *DSAStack,
Kelvin Li986330c2016-07-20 22:57:10 +00007161 VarsWithImplicitDSA, B);
7162 if (NestedLoopCount == 0)
7163 return StmtError();
7164
7165 assert((CurContext->isDependentContext() || B.builtAll()) &&
7166 "omp target simd loop exprs were not built");
7167
7168 if (!CurContext->isDependentContext()) {
7169 // Finalize the clauses that need pre-built expressions for CodeGen.
7170 for (auto C : Clauses) {
David Majnemer9d168222016-08-05 17:44:54 +00007171 if (auto *LC = dyn_cast<OMPLinearClause>(C))
Kelvin Li986330c2016-07-20 22:57:10 +00007172 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7173 B.NumIterations, *this, CurScope,
7174 DSAStack))
7175 return StmtError();
7176 }
7177 }
7178
7179 if (checkSimdlenSafelenSpecified(*this, Clauses))
7180 return StmtError();
7181
7182 getCurFunction()->setHasBranchProtectedScope();
7183 return OMPTargetSimdDirective::Create(Context, StartLoc, EndLoc,
7184 NestedLoopCount, Clauses, AStmt, B);
7185}
7186
Kelvin Li02532872016-08-05 14:37:37 +00007187StmtResult Sema::ActOnOpenMPTeamsDistributeDirective(
7188 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7189 SourceLocation EndLoc,
7190 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7191 if (!AStmt)
7192 return StmtError();
7193
7194 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7195 // 1.2.2 OpenMP Language Terminology
7196 // Structured block - An executable statement with a single entry at the
7197 // top and a single exit at the bottom.
7198 // The point of exit cannot be a branch out of the structured block.
7199 // longjmp() and throw() must not violate the entry/exit criteria.
7200 CS->getCapturedDecl()->setNothrow();
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007201 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_teams_distribute);
7202 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7203 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7204 // 1.2.2 OpenMP Language Terminology
7205 // Structured block - An executable statement with a single entry at the
7206 // top and a single exit at the bottom.
7207 // The point of exit cannot be a branch out of the structured block.
7208 // longjmp() and throw() must not violate the entry/exit criteria.
7209 CS->getCapturedDecl()->setNothrow();
7210 }
Kelvin Li02532872016-08-05 14:37:37 +00007211
7212 OMPLoopDirective::HelperExprs B;
7213 // In presence of clause 'collapse' with number of loops, it will
7214 // define the nested loops number.
7215 unsigned NestedLoopCount =
7216 CheckOpenMPLoop(OMPD_teams_distribute, getCollapseNumberExpr(Clauses),
Alexey Bataev95c6dd42017-11-29 15:14:16 +00007217 nullptr /*ordered not a clause on distribute*/, CS, *this,
7218 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li02532872016-08-05 14:37:37 +00007219 if (NestedLoopCount == 0)
7220 return StmtError();
7221
7222 assert((CurContext->isDependentContext() || B.builtAll()) &&
7223 "omp teams distribute loop exprs were not built");
7224
7225 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007226
7227 DSAStack->setParentTeamsRegionLoc(StartLoc);
7228
David Majnemer9d168222016-08-05 17:44:54 +00007229 return OMPTeamsDistributeDirective::Create(
7230 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
Kelvin Li02532872016-08-05 14:37:37 +00007231}
7232
Kelvin Li4e325f72016-10-25 12:50:55 +00007233StmtResult Sema::ActOnOpenMPTeamsDistributeSimdDirective(
7234 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7235 SourceLocation EndLoc,
7236 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7237 if (!AStmt)
7238 return StmtError();
7239
7240 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7241 // 1.2.2 OpenMP Language Terminology
7242 // Structured block - An executable statement with a single entry at the
7243 // top and a single exit at the bottom.
7244 // The point of exit cannot be a branch out of the structured block.
7245 // longjmp() and throw() must not violate the entry/exit criteria.
7246 CS->getCapturedDecl()->setNothrow();
Alexey Bataev999277a2017-12-06 14:31:09 +00007247 for (int ThisCaptureLevel =
7248 getOpenMPCaptureLevels(OMPD_teams_distribute_simd);
7249 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7250 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7251 // 1.2.2 OpenMP Language Terminology
7252 // Structured block - An executable statement with a single entry at the
7253 // top and a single exit at the bottom.
7254 // The point of exit cannot be a branch out of the structured block.
7255 // longjmp() and throw() must not violate the entry/exit criteria.
7256 CS->getCapturedDecl()->setNothrow();
7257 }
7258
Kelvin Li4e325f72016-10-25 12:50:55 +00007259
7260 OMPLoopDirective::HelperExprs B;
7261 // In presence of clause 'collapse' with number of loops, it will
7262 // define the nested loops number.
Samuel Antao4c8035b2016-12-12 18:00:20 +00007263 unsigned NestedLoopCount = CheckOpenMPLoop(
7264 OMPD_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataev999277a2017-12-06 14:31:09 +00007265 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Samuel Antao4c8035b2016-12-12 18:00:20 +00007266 VarsWithImplicitDSA, B);
Kelvin Li4e325f72016-10-25 12:50:55 +00007267
7268 if (NestedLoopCount == 0)
7269 return StmtError();
7270
7271 assert((CurContext->isDependentContext() || B.builtAll()) &&
7272 "omp teams distribute simd loop exprs were not built");
7273
7274 if (!CurContext->isDependentContext()) {
7275 // Finalize the clauses that need pre-built expressions for CodeGen.
7276 for (auto C : Clauses) {
7277 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7278 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7279 B.NumIterations, *this, CurScope,
7280 DSAStack))
7281 return StmtError();
7282 }
7283 }
7284
7285 if (checkSimdlenSafelenSpecified(*this, Clauses))
7286 return StmtError();
7287
7288 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007289
7290 DSAStack->setParentTeamsRegionLoc(StartLoc);
7291
Kelvin Li4e325f72016-10-25 12:50:55 +00007292 return OMPTeamsDistributeSimdDirective::Create(
7293 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7294}
7295
Kelvin Li579e41c2016-11-30 23:51:03 +00007296StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForSimdDirective(
7297 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7298 SourceLocation EndLoc,
7299 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7300 if (!AStmt)
7301 return StmtError();
7302
7303 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7304 // 1.2.2 OpenMP Language Terminology
7305 // Structured block - An executable statement with a single entry at the
7306 // top and a single exit at the bottom.
7307 // The point of exit cannot be a branch out of the structured block.
7308 // longjmp() and throw() must not violate the entry/exit criteria.
7309 CS->getCapturedDecl()->setNothrow();
7310
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007311 for (int ThisCaptureLevel =
7312 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for_simd);
7313 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7314 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7315 // 1.2.2 OpenMP Language Terminology
7316 // Structured block - An executable statement with a single entry at the
7317 // top and a single exit at the bottom.
7318 // The point of exit cannot be a branch out of the structured block.
7319 // longjmp() and throw() must not violate the entry/exit criteria.
7320 CS->getCapturedDecl()->setNothrow();
7321 }
7322
Kelvin Li579e41c2016-11-30 23:51:03 +00007323 OMPLoopDirective::HelperExprs B;
7324 // In presence of clause 'collapse' with number of loops, it will
7325 // define the nested loops number.
7326 auto NestedLoopCount = CheckOpenMPLoop(
7327 OMPD_teams_distribute_parallel_for_simd, getCollapseNumberExpr(Clauses),
Carlo Bertolli56a2aa42017-12-04 20:57:19 +00007328 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li579e41c2016-11-30 23:51:03 +00007329 VarsWithImplicitDSA, B);
7330
7331 if (NestedLoopCount == 0)
7332 return StmtError();
7333
7334 assert((CurContext->isDependentContext() || B.builtAll()) &&
7335 "omp for loop exprs were not built");
7336
7337 if (!CurContext->isDependentContext()) {
7338 // Finalize the clauses that need pre-built expressions for CodeGen.
7339 for (auto C : Clauses) {
7340 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7341 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7342 B.NumIterations, *this, CurScope,
7343 DSAStack))
7344 return StmtError();
7345 }
7346 }
7347
7348 if (checkSimdlenSafelenSpecified(*this, Clauses))
7349 return StmtError();
7350
7351 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007352
7353 DSAStack->setParentTeamsRegionLoc(StartLoc);
7354
Kelvin Li579e41c2016-11-30 23:51:03 +00007355 return OMPTeamsDistributeParallelForSimdDirective::Create(
7356 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7357}
7358
Kelvin Li7ade93f2016-12-09 03:24:30 +00007359StmtResult Sema::ActOnOpenMPTeamsDistributeParallelForDirective(
7360 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7361 SourceLocation EndLoc,
7362 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7363 if (!AStmt)
7364 return StmtError();
7365
7366 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7367 // 1.2.2 OpenMP Language Terminology
7368 // Structured block - An executable statement with a single entry at the
7369 // top and a single exit at the bottom.
7370 // The point of exit cannot be a branch out of the structured block.
7371 // longjmp() and throw() must not violate the entry/exit criteria.
7372 CS->getCapturedDecl()->setNothrow();
7373
Carlo Bertolli62fae152017-11-20 20:46:39 +00007374 for (int ThisCaptureLevel =
7375 getOpenMPCaptureLevels(OMPD_teams_distribute_parallel_for);
7376 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7377 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7378 // 1.2.2 OpenMP Language Terminology
7379 // Structured block - An executable statement with a single entry at the
7380 // top and a single exit at the bottom.
7381 // The point of exit cannot be a branch out of the structured block.
7382 // longjmp() and throw() must not violate the entry/exit criteria.
7383 CS->getCapturedDecl()->setNothrow();
7384 }
7385
Kelvin Li7ade93f2016-12-09 03:24:30 +00007386 OMPLoopDirective::HelperExprs B;
7387 // In presence of clause 'collapse' with number of loops, it will
7388 // define the nested loops number.
7389 unsigned NestedLoopCount = CheckOpenMPLoop(
7390 OMPD_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
Carlo Bertolli62fae152017-11-20 20:46:39 +00007391 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li7ade93f2016-12-09 03:24:30 +00007392 VarsWithImplicitDSA, B);
7393
7394 if (NestedLoopCount == 0)
7395 return StmtError();
7396
7397 assert((CurContext->isDependentContext() || B.builtAll()) &&
7398 "omp for loop exprs were not built");
7399
Kelvin Li7ade93f2016-12-09 03:24:30 +00007400 getCurFunction()->setHasBranchProtectedScope();
Alexey Bataevceabd412017-11-30 18:01:54 +00007401
7402 DSAStack->setParentTeamsRegionLoc(StartLoc);
7403
Kelvin Li7ade93f2016-12-09 03:24:30 +00007404 return OMPTeamsDistributeParallelForDirective::Create(
Alexey Bataevdcb4b8fb2017-11-22 20:19:50 +00007405 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7406 DSAStack->isCancelRegion());
Kelvin Li7ade93f2016-12-09 03:24:30 +00007407}
7408
Kelvin Libf594a52016-12-17 05:48:59 +00007409StmtResult Sema::ActOnOpenMPTargetTeamsDirective(ArrayRef<OMPClause *> Clauses,
7410 Stmt *AStmt,
7411 SourceLocation StartLoc,
7412 SourceLocation EndLoc) {
7413 if (!AStmt)
7414 return StmtError();
7415
7416 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7417 // 1.2.2 OpenMP Language Terminology
7418 // Structured block - An executable statement with a single entry at the
7419 // top and a single exit at the bottom.
7420 // The point of exit cannot be a branch out of the structured block.
7421 // longjmp() and throw() must not violate the entry/exit criteria.
7422 CS->getCapturedDecl()->setNothrow();
7423
Alexey Bataevf9fc42e2017-11-22 14:25:55 +00007424 for (int ThisCaptureLevel = getOpenMPCaptureLevels(OMPD_target_teams);
7425 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7426 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7427 // 1.2.2 OpenMP Language Terminology
7428 // Structured block - An executable statement with a single entry at the
7429 // top and a single exit at the bottom.
7430 // The point of exit cannot be a branch out of the structured block.
7431 // longjmp() and throw() must not violate the entry/exit criteria.
7432 CS->getCapturedDecl()->setNothrow();
7433 }
Kelvin Libf594a52016-12-17 05:48:59 +00007434 getCurFunction()->setHasBranchProtectedScope();
7435
7436 return OMPTargetTeamsDirective::Create(Context, StartLoc, EndLoc, Clauses,
7437 AStmt);
7438}
7439
Kelvin Li83c451e2016-12-25 04:52:54 +00007440StmtResult Sema::ActOnOpenMPTargetTeamsDistributeDirective(
7441 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7442 SourceLocation EndLoc,
7443 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7444 if (!AStmt)
7445 return StmtError();
7446
7447 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7448 // 1.2.2 OpenMP Language Terminology
7449 // Structured block - An executable statement with a single entry at the
7450 // top and a single exit at the bottom.
7451 // The point of exit cannot be a branch out of the structured block.
7452 // longjmp() and throw() must not violate the entry/exit criteria.
7453 CS->getCapturedDecl()->setNothrow();
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007454 for (int ThisCaptureLevel =
7455 getOpenMPCaptureLevels(OMPD_target_teams_distribute);
7456 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7457 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7458 // 1.2.2 OpenMP Language Terminology
7459 // Structured block - An executable statement with a single entry at the
7460 // top and a single exit at the bottom.
7461 // The point of exit cannot be a branch out of the structured block.
7462 // longjmp() and throw() must not violate the entry/exit criteria.
7463 CS->getCapturedDecl()->setNothrow();
7464 }
Kelvin Li83c451e2016-12-25 04:52:54 +00007465
7466 OMPLoopDirective::HelperExprs B;
7467 // In presence of clause 'collapse' with number of loops, it will
7468 // define the nested loops number.
7469 auto NestedLoopCount = CheckOpenMPLoop(
Alexey Bataevdfa430f2017-12-08 15:03:50 +00007470 OMPD_target_teams_distribute, getCollapseNumberExpr(Clauses),
7471 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li83c451e2016-12-25 04:52:54 +00007472 VarsWithImplicitDSA, B);
7473 if (NestedLoopCount == 0)
7474 return StmtError();
7475
7476 assert((CurContext->isDependentContext() || B.builtAll()) &&
7477 "omp target teams distribute loop exprs were not built");
7478
7479 getCurFunction()->setHasBranchProtectedScope();
7480 return OMPTargetTeamsDistributeDirective::Create(
7481 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7482}
7483
Kelvin Li80e8f562016-12-29 22:16:30 +00007484StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForDirective(
7485 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7486 SourceLocation EndLoc,
7487 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7488 if (!AStmt)
7489 return StmtError();
7490
7491 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7492 // 1.2.2 OpenMP Language Terminology
7493 // Structured block - An executable statement with a single entry at the
7494 // top and a single exit at the bottom.
7495 // The point of exit cannot be a branch out of the structured block.
7496 // longjmp() and throw() must not violate the entry/exit criteria.
7497 CS->getCapturedDecl()->setNothrow();
Carlo Bertolli52978c32018-01-03 21:12:44 +00007498 for (int ThisCaptureLevel =
7499 getOpenMPCaptureLevels(OMPD_target_teams_distribute_parallel_for);
7500 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7501 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7502 // 1.2.2 OpenMP Language Terminology
7503 // Structured block - An executable statement with a single entry at the
7504 // top and a single exit at the bottom.
7505 // The point of exit cannot be a branch out of the structured block.
7506 // longjmp() and throw() must not violate the entry/exit criteria.
7507 CS->getCapturedDecl()->setNothrow();
7508 }
7509
Kelvin Li80e8f562016-12-29 22:16:30 +00007510 OMPLoopDirective::HelperExprs B;
7511 // In presence of clause 'collapse' with number of loops, it will
7512 // define the nested loops number.
7513 auto NestedLoopCount = CheckOpenMPLoop(
Carlo Bertolli52978c32018-01-03 21:12:44 +00007514 OMPD_target_teams_distribute_parallel_for, getCollapseNumberExpr(Clauses),
7515 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Li80e8f562016-12-29 22:16:30 +00007516 VarsWithImplicitDSA, B);
7517 if (NestedLoopCount == 0)
7518 return StmtError();
7519
7520 assert((CurContext->isDependentContext() || B.builtAll()) &&
7521 "omp target teams distribute parallel for loop exprs were not built");
7522
Alexey Bataev647dd842018-01-15 20:59:40 +00007523 if (!CurContext->isDependentContext()) {
7524 // Finalize the clauses that need pre-built expressions for CodeGen.
7525 for (auto C : Clauses) {
7526 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7527 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7528 B.NumIterations, *this, CurScope,
7529 DSAStack))
7530 return StmtError();
7531 }
7532 }
7533
Kelvin Li80e8f562016-12-29 22:16:30 +00007534 getCurFunction()->setHasBranchProtectedScope();
7535 return OMPTargetTeamsDistributeParallelForDirective::Create(
Alexey Bataev16e79882017-11-22 21:12:03 +00007536 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B,
7537 DSAStack->isCancelRegion());
Kelvin Li80e8f562016-12-29 22:16:30 +00007538}
7539
Kelvin Li1851df52017-01-03 05:23:48 +00007540StmtResult Sema::ActOnOpenMPTargetTeamsDistributeParallelForSimdDirective(
7541 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7542 SourceLocation EndLoc,
7543 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7544 if (!AStmt)
7545 return StmtError();
7546
7547 CapturedStmt *CS = cast<CapturedStmt>(AStmt);
7548 // 1.2.2 OpenMP Language Terminology
7549 // Structured block - An executable statement with a single entry at the
7550 // top and a single exit at the bottom.
7551 // The point of exit cannot be a branch out of the structured block.
7552 // longjmp() and throw() must not violate the entry/exit criteria.
7553 CS->getCapturedDecl()->setNothrow();
Alexey Bataev647dd842018-01-15 20:59:40 +00007554 for (int ThisCaptureLevel = getOpenMPCaptureLevels(
7555 OMPD_target_teams_distribute_parallel_for_simd);
7556 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7557 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7558 // 1.2.2 OpenMP Language Terminology
7559 // Structured block - An executable statement with a single entry at the
7560 // top and a single exit at the bottom.
7561 // The point of exit cannot be a branch out of the structured block.
7562 // longjmp() and throw() must not violate the entry/exit criteria.
7563 CS->getCapturedDecl()->setNothrow();
7564 }
Kelvin Li1851df52017-01-03 05:23:48 +00007565
7566 OMPLoopDirective::HelperExprs B;
7567 // In presence of clause 'collapse' with number of loops, it will
7568 // define the nested loops number.
Alexey Bataev647dd842018-01-15 20:59:40 +00007569 auto NestedLoopCount =
7570 CheckOpenMPLoop(OMPD_target_teams_distribute_parallel_for_simd,
7571 getCollapseNumberExpr(Clauses),
7572 nullptr /*ordered not a clause on distribute*/, CS, *this,
7573 *DSAStack, VarsWithImplicitDSA, B);
Kelvin Li1851df52017-01-03 05:23:48 +00007574 if (NestedLoopCount == 0)
7575 return StmtError();
7576
7577 assert((CurContext->isDependentContext() || B.builtAll()) &&
7578 "omp target teams distribute parallel for simd loop exprs were not "
7579 "built");
7580
7581 if (!CurContext->isDependentContext()) {
7582 // Finalize the clauses that need pre-built expressions for CodeGen.
7583 for (auto C : Clauses) {
7584 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7585 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7586 B.NumIterations, *this, CurScope,
7587 DSAStack))
7588 return StmtError();
7589 }
7590 }
7591
Alexey Bataev438388c2017-11-22 18:34:02 +00007592 if (checkSimdlenSafelenSpecified(*this, Clauses))
7593 return StmtError();
7594
Kelvin Li1851df52017-01-03 05:23:48 +00007595 getCurFunction()->setHasBranchProtectedScope();
7596 return OMPTargetTeamsDistributeParallelForSimdDirective::Create(
7597 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7598}
7599
Kelvin Lida681182017-01-10 18:08:18 +00007600StmtResult Sema::ActOnOpenMPTargetTeamsDistributeSimdDirective(
7601 ArrayRef<OMPClause *> Clauses, Stmt *AStmt, SourceLocation StartLoc,
7602 SourceLocation EndLoc,
7603 llvm::DenseMap<ValueDecl *, Expr *> &VarsWithImplicitDSA) {
7604 if (!AStmt)
7605 return StmtError();
7606
7607 auto *CS = cast<CapturedStmt>(AStmt);
7608 // 1.2.2 OpenMP Language Terminology
7609 // Structured block - An executable statement with a single entry at the
7610 // top and a single exit at the bottom.
7611 // The point of exit cannot be a branch out of the structured block.
7612 // longjmp() and throw() must not violate the entry/exit criteria.
7613 CS->getCapturedDecl()->setNothrow();
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007614 for (int ThisCaptureLevel =
7615 getOpenMPCaptureLevels(OMPD_target_teams_distribute_simd);
7616 ThisCaptureLevel > 1; --ThisCaptureLevel) {
7617 CS = cast<CapturedStmt>(CS->getCapturedStmt());
7618 // 1.2.2 OpenMP Language Terminology
7619 // Structured block - An executable statement with a single entry at the
7620 // top and a single exit at the bottom.
7621 // The point of exit cannot be a branch out of the structured block.
7622 // longjmp() and throw() must not violate the entry/exit criteria.
7623 CS->getCapturedDecl()->setNothrow();
7624 }
Kelvin Lida681182017-01-10 18:08:18 +00007625
7626 OMPLoopDirective::HelperExprs B;
7627 // In presence of clause 'collapse' with number of loops, it will
7628 // define the nested loops number.
7629 auto NestedLoopCount = CheckOpenMPLoop(
7630 OMPD_target_teams_distribute_simd, getCollapseNumberExpr(Clauses),
Alexey Bataevfbe17fb2017-12-13 19:45:06 +00007631 nullptr /*ordered not a clause on distribute*/, CS, *this, *DSAStack,
Kelvin Lida681182017-01-10 18:08:18 +00007632 VarsWithImplicitDSA, B);
7633 if (NestedLoopCount == 0)
7634 return StmtError();
7635
7636 assert((CurContext->isDependentContext() || B.builtAll()) &&
7637 "omp target teams distribute simd loop exprs were not built");
7638
Alexey Bataev438388c2017-11-22 18:34:02 +00007639 if (!CurContext->isDependentContext()) {
7640 // Finalize the clauses that need pre-built expressions for CodeGen.
7641 for (auto C : Clauses) {
7642 if (auto *LC = dyn_cast<OMPLinearClause>(C))
7643 if (FinishOpenMPLinearClause(*LC, cast<DeclRefExpr>(B.IterationVarRef),
7644 B.NumIterations, *this, CurScope,
7645 DSAStack))
7646 return StmtError();
7647 }
7648 }
7649
7650 if (checkSimdlenSafelenSpecified(*this, Clauses))
7651 return StmtError();
7652
Kelvin Lida681182017-01-10 18:08:18 +00007653 getCurFunction()->setHasBranchProtectedScope();
7654 return OMPTargetTeamsDistributeSimdDirective::Create(
7655 Context, StartLoc, EndLoc, NestedLoopCount, Clauses, AStmt, B);
7656}
7657
Alexey Bataeved09d242014-05-28 05:53:51 +00007658OMPClause *Sema::ActOnOpenMPSingleExprClause(OpenMPClauseKind Kind, Expr *Expr,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007659 SourceLocation StartLoc,
7660 SourceLocation LParenLoc,
7661 SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00007662 OMPClause *Res = nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007663 switch (Kind) {
Alexey Bataev3778b602014-07-17 07:32:53 +00007664 case OMPC_final:
7665 Res = ActOnOpenMPFinalClause(Expr, StartLoc, LParenLoc, EndLoc);
7666 break;
Alexey Bataev568a8332014-03-06 06:15:19 +00007667 case OMPC_num_threads:
7668 Res = ActOnOpenMPNumThreadsClause(Expr, StartLoc, LParenLoc, EndLoc);
7669 break;
Alexey Bataev62c87d22014-03-21 04:51:18 +00007670 case OMPC_safelen:
7671 Res = ActOnOpenMPSafelenClause(Expr, StartLoc, LParenLoc, EndLoc);
7672 break;
Alexey Bataev66b15b52015-08-21 11:14:16 +00007673 case OMPC_simdlen:
7674 Res = ActOnOpenMPSimdlenClause(Expr, StartLoc, LParenLoc, EndLoc);
7675 break;
Alexander Musman8bd31e62014-05-27 15:12:19 +00007676 case OMPC_collapse:
7677 Res = ActOnOpenMPCollapseClause(Expr, StartLoc, LParenLoc, EndLoc);
7678 break;
Alexey Bataev10e775f2015-07-30 11:36:16 +00007679 case OMPC_ordered:
7680 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc, LParenLoc, Expr);
7681 break;
Michael Wonge710d542015-08-07 16:16:36 +00007682 case OMPC_device:
7683 Res = ActOnOpenMPDeviceClause(Expr, StartLoc, LParenLoc, EndLoc);
7684 break;
Kelvin Li099bb8c2015-11-24 20:50:12 +00007685 case OMPC_num_teams:
7686 Res = ActOnOpenMPNumTeamsClause(Expr, StartLoc, LParenLoc, EndLoc);
7687 break;
Kelvin Lia15fb1a2015-11-27 18:47:36 +00007688 case OMPC_thread_limit:
7689 Res = ActOnOpenMPThreadLimitClause(Expr, StartLoc, LParenLoc, EndLoc);
7690 break;
Alexey Bataeva0569352015-12-01 10:17:31 +00007691 case OMPC_priority:
7692 Res = ActOnOpenMPPriorityClause(Expr, StartLoc, LParenLoc, EndLoc);
7693 break;
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00007694 case OMPC_grainsize:
7695 Res = ActOnOpenMPGrainsizeClause(Expr, StartLoc, LParenLoc, EndLoc);
7696 break;
Alexey Bataev382967a2015-12-08 12:06:20 +00007697 case OMPC_num_tasks:
7698 Res = ActOnOpenMPNumTasksClause(Expr, StartLoc, LParenLoc, EndLoc);
7699 break;
Alexey Bataev28c75412015-12-15 08:19:24 +00007700 case OMPC_hint:
7701 Res = ActOnOpenMPHintClause(Expr, StartLoc, LParenLoc, EndLoc);
7702 break;
Alexey Bataev6b8046a2015-09-03 07:23:48 +00007703 case OMPC_if:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007704 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00007705 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00007706 case OMPC_schedule:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007707 case OMPC_private:
7708 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00007709 case OMPC_lastprivate:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007710 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00007711 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00007712 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00007713 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00007714 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00007715 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00007716 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00007717 case OMPC_copyprivate:
Alexey Bataev236070f2014-06-20 11:19:47 +00007718 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00007719 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00007720 case OMPC_mergeable:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007721 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00007722 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00007723 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00007724 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00007725 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00007726 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00007727 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00007728 case OMPC_depend:
Alexey Bataev346265e2015-09-25 10:37:12 +00007729 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00007730 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00007731 case OMPC_map:
Alexey Bataevb825de12015-12-07 10:51:44 +00007732 case OMPC_nogroup:
Carlo Bertollib4adf552016-01-15 18:50:31 +00007733 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00007734 case OMPC_defaultmap:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007735 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00007736 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00007737 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00007738 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00007739 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00007740 case OMPC_is_device_ptr:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00007741 llvm_unreachable("Clause is not allowed.");
7742 }
7743 return Res;
7744}
7745
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007746// An OpenMP directive such as 'target parallel' has two captured regions:
7747// for the 'target' and 'parallel' respectively. This function returns
7748// the region in which to capture expressions associated with a clause.
7749// A return value of OMPD_unknown signifies that the expression should not
7750// be captured.
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007751static OpenMPDirectiveKind getOpenMPCaptureRegionForClause(
7752 OpenMPDirectiveKind DKind, OpenMPClauseKind CKind,
7753 OpenMPDirectiveKind NameModifier = OMPD_unknown) {
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007754 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007755 switch (CKind) {
7756 case OMPC_if:
7757 switch (DKind) {
7758 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007759 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007760 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007761 // If this clause applies to the nested 'parallel' region, capture within
7762 // the 'target' region, otherwise do not capture.
7763 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7764 CaptureRegion = OMPD_target;
7765 break;
Carlo Bertolli52978c32018-01-03 21:12:44 +00007766 case OMPD_target_teams_distribute_parallel_for:
7767 case OMPD_target_teams_distribute_parallel_for_simd:
7768 // If this clause applies to the nested 'parallel' region, capture within
7769 // the 'teams' region, otherwise do not capture.
7770 if (NameModifier == OMPD_unknown || NameModifier == OMPD_parallel)
7771 CaptureRegion = OMPD_teams;
7772 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007773 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007774 case OMPD_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007775 CaptureRegion = OMPD_teams;
7776 break;
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007777 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00007778 case OMPD_target_enter_data:
7779 case OMPD_target_exit_data:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00007780 CaptureRegion = OMPD_task;
7781 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007782 case OMPD_cancel:
7783 case OMPD_parallel:
7784 case OMPD_parallel_sections:
7785 case OMPD_parallel_for:
7786 case OMPD_parallel_for_simd:
7787 case OMPD_target:
7788 case OMPD_target_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007789 case OMPD_target_teams:
7790 case OMPD_target_teams_distribute:
7791 case OMPD_target_teams_distribute_simd:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007792 case OMPD_distribute_parallel_for:
7793 case OMPD_distribute_parallel_for_simd:
7794 case OMPD_task:
7795 case OMPD_taskloop:
7796 case OMPD_taskloop_simd:
7797 case OMPD_target_data:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00007798 // Do not capture if-clause expressions.
7799 break;
7800 case OMPD_threadprivate:
7801 case OMPD_taskyield:
7802 case OMPD_barrier:
7803 case OMPD_taskwait:
7804 case OMPD_cancellation_point:
7805 case OMPD_flush:
7806 case OMPD_declare_reduction:
7807 case OMPD_declare_simd:
7808 case OMPD_declare_target:
7809 case OMPD_end_declare_target:
7810 case OMPD_teams:
7811 case OMPD_simd:
7812 case OMPD_for:
7813 case OMPD_for_simd:
7814 case OMPD_sections:
7815 case OMPD_section:
7816 case OMPD_single:
7817 case OMPD_master:
7818 case OMPD_critical:
7819 case OMPD_taskgroup:
7820 case OMPD_distribute:
7821 case OMPD_ordered:
7822 case OMPD_atomic:
7823 case OMPD_distribute_simd:
7824 case OMPD_teams_distribute:
7825 case OMPD_teams_distribute_simd:
7826 llvm_unreachable("Unexpected OpenMP directive with if-clause");
7827 case OMPD_unknown:
7828 llvm_unreachable("Unknown OpenMP directive");
7829 }
7830 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007831 case OMPC_num_threads:
7832 switch (DKind) {
7833 case OMPD_target_parallel:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00007834 case OMPD_target_parallel_for:
Alexey Bataev5d7edca2017-11-09 17:32:15 +00007835 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007836 CaptureRegion = OMPD_target;
7837 break;
Carlo Bertolli62fae152017-11-20 20:46:39 +00007838 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007839 case OMPD_teams_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00007840 case OMPD_target_teams_distribute_parallel_for:
7841 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00007842 CaptureRegion = OMPD_teams;
7843 break;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007844 case OMPD_parallel:
7845 case OMPD_parallel_sections:
7846 case OMPD_parallel_for:
7847 case OMPD_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007848 case OMPD_distribute_parallel_for:
7849 case OMPD_distribute_parallel_for_simd:
7850 // Do not capture num_threads-clause expressions.
7851 break;
7852 case OMPD_target_data:
7853 case OMPD_target_enter_data:
7854 case OMPD_target_exit_data:
7855 case OMPD_target_update:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007856 case OMPD_target:
7857 case OMPD_target_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007858 case OMPD_target_teams:
7859 case OMPD_target_teams_distribute:
7860 case OMPD_target_teams_distribute_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007861 case OMPD_cancel:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007862 case OMPD_task:
7863 case OMPD_taskloop:
7864 case OMPD_taskloop_simd:
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00007865 case OMPD_threadprivate:
7866 case OMPD_taskyield:
7867 case OMPD_barrier:
7868 case OMPD_taskwait:
7869 case OMPD_cancellation_point:
7870 case OMPD_flush:
7871 case OMPD_declare_reduction:
7872 case OMPD_declare_simd:
7873 case OMPD_declare_target:
7874 case OMPD_end_declare_target:
7875 case OMPD_teams:
7876 case OMPD_simd:
7877 case OMPD_for:
7878 case OMPD_for_simd:
7879 case OMPD_sections:
7880 case OMPD_section:
7881 case OMPD_single:
7882 case OMPD_master:
7883 case OMPD_critical:
7884 case OMPD_taskgroup:
7885 case OMPD_distribute:
7886 case OMPD_ordered:
7887 case OMPD_atomic:
7888 case OMPD_distribute_simd:
7889 case OMPD_teams_distribute:
7890 case OMPD_teams_distribute_simd:
7891 llvm_unreachable("Unexpected OpenMP directive with num_threads-clause");
7892 case OMPD_unknown:
7893 llvm_unreachable("Unknown OpenMP directive");
7894 }
7895 break;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007896 case OMPC_num_teams:
7897 switch (DKind) {
7898 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007899 case OMPD_target_teams_distribute:
7900 case OMPD_target_teams_distribute_simd:
7901 case OMPD_target_teams_distribute_parallel_for:
7902 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007903 CaptureRegion = OMPD_target;
7904 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007905 case OMPD_teams_distribute_parallel_for:
7906 case OMPD_teams_distribute_parallel_for_simd:
7907 case OMPD_teams:
7908 case OMPD_teams_distribute:
7909 case OMPD_teams_distribute_simd:
7910 // Do not capture num_teams-clause expressions.
7911 break;
7912 case OMPD_distribute_parallel_for:
7913 case OMPD_distribute_parallel_for_simd:
7914 case OMPD_task:
7915 case OMPD_taskloop:
7916 case OMPD_taskloop_simd:
7917 case OMPD_target_data:
7918 case OMPD_target_enter_data:
7919 case OMPD_target_exit_data:
7920 case OMPD_target_update:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007921 case OMPD_cancel:
7922 case OMPD_parallel:
7923 case OMPD_parallel_sections:
7924 case OMPD_parallel_for:
7925 case OMPD_parallel_for_simd:
7926 case OMPD_target:
7927 case OMPD_target_simd:
7928 case OMPD_target_parallel:
7929 case OMPD_target_parallel_for:
7930 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +00007931 case OMPD_threadprivate:
7932 case OMPD_taskyield:
7933 case OMPD_barrier:
7934 case OMPD_taskwait:
7935 case OMPD_cancellation_point:
7936 case OMPD_flush:
7937 case OMPD_declare_reduction:
7938 case OMPD_declare_simd:
7939 case OMPD_declare_target:
7940 case OMPD_end_declare_target:
7941 case OMPD_simd:
7942 case OMPD_for:
7943 case OMPD_for_simd:
7944 case OMPD_sections:
7945 case OMPD_section:
7946 case OMPD_single:
7947 case OMPD_master:
7948 case OMPD_critical:
7949 case OMPD_taskgroup:
7950 case OMPD_distribute:
7951 case OMPD_ordered:
7952 case OMPD_atomic:
7953 case OMPD_distribute_simd:
7954 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
7955 case OMPD_unknown:
7956 llvm_unreachable("Unknown OpenMP directive");
7957 }
7958 break;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007959 case OMPC_thread_limit:
7960 switch (DKind) {
7961 case OMPD_target_teams:
Alexey Bataev2ba67042017-11-28 21:11:44 +00007962 case OMPD_target_teams_distribute:
7963 case OMPD_target_teams_distribute_simd:
7964 case OMPD_target_teams_distribute_parallel_for:
7965 case OMPD_target_teams_distribute_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007966 CaptureRegion = OMPD_target;
7967 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00007968 case OMPD_teams_distribute_parallel_for:
7969 case OMPD_teams_distribute_parallel_for_simd:
7970 case OMPD_teams:
7971 case OMPD_teams_distribute:
7972 case OMPD_teams_distribute_simd:
7973 // Do not capture thread_limit-clause expressions.
7974 break;
7975 case OMPD_distribute_parallel_for:
7976 case OMPD_distribute_parallel_for_simd:
7977 case OMPD_task:
7978 case OMPD_taskloop:
7979 case OMPD_taskloop_simd:
7980 case OMPD_target_data:
7981 case OMPD_target_enter_data:
7982 case OMPD_target_exit_data:
7983 case OMPD_target_update:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007984 case OMPD_cancel:
7985 case OMPD_parallel:
7986 case OMPD_parallel_sections:
7987 case OMPD_parallel_for:
7988 case OMPD_parallel_for_simd:
7989 case OMPD_target:
7990 case OMPD_target_simd:
7991 case OMPD_target_parallel:
7992 case OMPD_target_parallel_for:
7993 case OMPD_target_parallel_for_simd:
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +00007994 case OMPD_threadprivate:
7995 case OMPD_taskyield:
7996 case OMPD_barrier:
7997 case OMPD_taskwait:
7998 case OMPD_cancellation_point:
7999 case OMPD_flush:
8000 case OMPD_declare_reduction:
8001 case OMPD_declare_simd:
8002 case OMPD_declare_target:
8003 case OMPD_end_declare_target:
8004 case OMPD_simd:
8005 case OMPD_for:
8006 case OMPD_for_simd:
8007 case OMPD_sections:
8008 case OMPD_section:
8009 case OMPD_single:
8010 case OMPD_master:
8011 case OMPD_critical:
8012 case OMPD_taskgroup:
8013 case OMPD_distribute:
8014 case OMPD_ordered:
8015 case OMPD_atomic:
8016 case OMPD_distribute_simd:
8017 llvm_unreachable("Unexpected OpenMP directive with thread_limit-clause");
8018 case OMPD_unknown:
8019 llvm_unreachable("Unknown OpenMP directive");
8020 }
8021 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008022 case OMPC_schedule:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008023 switch (DKind) {
Alexey Bataev2ba67042017-11-28 21:11:44 +00008024 case OMPD_parallel_for:
8025 case OMPD_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008026 case OMPD_distribute_parallel_for:
Alexey Bataev974acd62017-11-27 19:38:52 +00008027 case OMPD_distribute_parallel_for_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008028 case OMPD_teams_distribute_parallel_for:
8029 case OMPD_teams_distribute_parallel_for_simd:
8030 case OMPD_target_parallel_for:
8031 case OMPD_target_parallel_for_simd:
8032 case OMPD_target_teams_distribute_parallel_for:
8033 case OMPD_target_teams_distribute_parallel_for_simd:
Alexey Bataev7f96c372017-11-22 17:19:31 +00008034 CaptureRegion = OMPD_parallel;
8035 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008036 case OMPD_for:
8037 case OMPD_for_simd:
8038 // Do not capture schedule-clause expressions.
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008039 break;
8040 case OMPD_task:
8041 case OMPD_taskloop:
8042 case OMPD_taskloop_simd:
8043 case OMPD_target_data:
8044 case OMPD_target_enter_data:
8045 case OMPD_target_exit_data:
8046 case OMPD_target_update:
8047 case OMPD_teams:
8048 case OMPD_teams_distribute:
8049 case OMPD_teams_distribute_simd:
8050 case OMPD_target_teams_distribute:
8051 case OMPD_target_teams_distribute_simd:
8052 case OMPD_target:
8053 case OMPD_target_simd:
8054 case OMPD_target_parallel:
8055 case OMPD_cancel:
8056 case OMPD_parallel:
8057 case OMPD_parallel_sections:
8058 case OMPD_threadprivate:
8059 case OMPD_taskyield:
8060 case OMPD_barrier:
8061 case OMPD_taskwait:
8062 case OMPD_cancellation_point:
8063 case OMPD_flush:
8064 case OMPD_declare_reduction:
8065 case OMPD_declare_simd:
8066 case OMPD_declare_target:
8067 case OMPD_end_declare_target:
8068 case OMPD_simd:
Alexey Bataevfb0ebec2017-11-08 20:16:14 +00008069 case OMPD_sections:
8070 case OMPD_section:
8071 case OMPD_single:
8072 case OMPD_master:
8073 case OMPD_critical:
8074 case OMPD_taskgroup:
8075 case OMPD_distribute:
8076 case OMPD_ordered:
8077 case OMPD_atomic:
8078 case OMPD_distribute_simd:
8079 case OMPD_target_teams:
8080 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8081 case OMPD_unknown:
8082 llvm_unreachable("Unknown OpenMP directive");
8083 }
8084 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008085 case OMPC_dist_schedule:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008086 switch (DKind) {
8087 case OMPD_teams_distribute_parallel_for:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008088 case OMPD_teams_distribute_parallel_for_simd:
8089 case OMPD_teams_distribute:
8090 case OMPD_teams_distribute_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008091 case OMPD_target_teams_distribute_parallel_for:
8092 case OMPD_target_teams_distribute_parallel_for_simd:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008093 case OMPD_target_teams_distribute:
8094 case OMPD_target_teams_distribute_simd:
Alexey Bataevfd9b2af2018-01-04 20:50:08 +00008095 CaptureRegion = OMPD_teams;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008096 break;
8097 case OMPD_distribute_parallel_for:
8098 case OMPD_distribute_parallel_for_simd:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008099 case OMPD_distribute:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008100 case OMPD_distribute_simd:
8101 // Do not capture thread_limit-clause expressions.
8102 break;
8103 case OMPD_parallel_for:
8104 case OMPD_parallel_for_simd:
8105 case OMPD_target_parallel_for_simd:
8106 case OMPD_target_parallel_for:
8107 case OMPD_task:
8108 case OMPD_taskloop:
8109 case OMPD_taskloop_simd:
8110 case OMPD_target_data:
8111 case OMPD_target_enter_data:
8112 case OMPD_target_exit_data:
8113 case OMPD_target_update:
8114 case OMPD_teams:
8115 case OMPD_target:
8116 case OMPD_target_simd:
8117 case OMPD_target_parallel:
8118 case OMPD_cancel:
8119 case OMPD_parallel:
8120 case OMPD_parallel_sections:
8121 case OMPD_threadprivate:
8122 case OMPD_taskyield:
8123 case OMPD_barrier:
8124 case OMPD_taskwait:
8125 case OMPD_cancellation_point:
8126 case OMPD_flush:
8127 case OMPD_declare_reduction:
8128 case OMPD_declare_simd:
8129 case OMPD_declare_target:
8130 case OMPD_end_declare_target:
8131 case OMPD_simd:
8132 case OMPD_for:
8133 case OMPD_for_simd:
8134 case OMPD_sections:
8135 case OMPD_section:
8136 case OMPD_single:
8137 case OMPD_master:
8138 case OMPD_critical:
8139 case OMPD_taskgroup:
Carlo Bertolli62fae152017-11-20 20:46:39 +00008140 case OMPD_ordered:
8141 case OMPD_atomic:
8142 case OMPD_target_teams:
8143 llvm_unreachable("Unexpected OpenMP directive with schedule clause");
8144 case OMPD_unknown:
8145 llvm_unreachable("Unknown OpenMP directive");
8146 }
8147 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008148 case OMPC_device:
8149 switch (DKind) {
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008150 case OMPD_target_update:
Alexey Bataevfab20e42017-12-27 18:49:38 +00008151 case OMPD_target_enter_data:
8152 case OMPD_target_exit_data:
Alexey Bataev8451efa2018-01-15 19:06:12 +00008153 case OMPD_target:
Alexey Bataevf41c88f2018-01-16 15:05:16 +00008154 case OMPD_target_simd:
Alexey Bataev0c869ef2018-01-16 15:57:07 +00008155 case OMPD_target_teams:
Alexey Bataev54d5c7d2018-01-16 16:27:49 +00008156 case OMPD_target_parallel:
Alexey Bataev79df7562018-01-16 16:46:46 +00008157 case OMPD_target_teams_distribute:
Alexey Bataev8d16a432018-01-16 17:22:50 +00008158 case OMPD_target_teams_distribute_simd:
Alexey Bataev8ed895512018-01-16 17:41:04 +00008159 case OMPD_target_parallel_for:
Alexey Bataevd2202ca2017-12-27 17:58:32 +00008160 CaptureRegion = OMPD_task;
8161 break;
Alexey Bataev2ba67042017-11-28 21:11:44 +00008162 case OMPD_target_teams_distribute_parallel_for:
8163 case OMPD_target_teams_distribute_parallel_for_simd:
8164 case OMPD_target_data:
Alexey Bataev2ba67042017-11-28 21:11:44 +00008165 case OMPD_target_parallel_for_simd:
8166 // Do not capture device-clause expressions.
8167 break;
8168 case OMPD_teams_distribute_parallel_for:
8169 case OMPD_teams_distribute_parallel_for_simd:
8170 case OMPD_teams:
8171 case OMPD_teams_distribute:
8172 case OMPD_teams_distribute_simd:
8173 case OMPD_distribute_parallel_for:
8174 case OMPD_distribute_parallel_for_simd:
8175 case OMPD_task:
8176 case OMPD_taskloop:
8177 case OMPD_taskloop_simd:
8178 case OMPD_cancel:
8179 case OMPD_parallel:
8180 case OMPD_parallel_sections:
8181 case OMPD_parallel_for:
8182 case OMPD_parallel_for_simd:
8183 case OMPD_threadprivate:
8184 case OMPD_taskyield:
8185 case OMPD_barrier:
8186 case OMPD_taskwait:
8187 case OMPD_cancellation_point:
8188 case OMPD_flush:
8189 case OMPD_declare_reduction:
8190 case OMPD_declare_simd:
8191 case OMPD_declare_target:
8192 case OMPD_end_declare_target:
8193 case OMPD_simd:
8194 case OMPD_for:
8195 case OMPD_for_simd:
8196 case OMPD_sections:
8197 case OMPD_section:
8198 case OMPD_single:
8199 case OMPD_master:
8200 case OMPD_critical:
8201 case OMPD_taskgroup:
8202 case OMPD_distribute:
8203 case OMPD_ordered:
8204 case OMPD_atomic:
8205 case OMPD_distribute_simd:
8206 llvm_unreachable("Unexpected OpenMP directive with num_teams-clause");
8207 case OMPD_unknown:
8208 llvm_unreachable("Unknown OpenMP directive");
8209 }
8210 break;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008211 case OMPC_firstprivate:
8212 case OMPC_lastprivate:
8213 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008214 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008215 case OMPC_in_reduction:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008216 case OMPC_linear:
8217 case OMPC_default:
8218 case OMPC_proc_bind:
8219 case OMPC_final:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008220 case OMPC_safelen:
8221 case OMPC_simdlen:
8222 case OMPC_collapse:
8223 case OMPC_private:
8224 case OMPC_shared:
8225 case OMPC_aligned:
8226 case OMPC_copyin:
8227 case OMPC_copyprivate:
8228 case OMPC_ordered:
8229 case OMPC_nowait:
8230 case OMPC_untied:
8231 case OMPC_mergeable:
8232 case OMPC_threadprivate:
8233 case OMPC_flush:
8234 case OMPC_read:
8235 case OMPC_write:
8236 case OMPC_update:
8237 case OMPC_capture:
8238 case OMPC_seq_cst:
8239 case OMPC_depend:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008240 case OMPC_threads:
8241 case OMPC_simd:
8242 case OMPC_map:
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008243 case OMPC_priority:
8244 case OMPC_grainsize:
8245 case OMPC_nogroup:
8246 case OMPC_num_tasks:
8247 case OMPC_hint:
8248 case OMPC_defaultmap:
8249 case OMPC_unknown:
8250 case OMPC_uniform:
8251 case OMPC_to:
8252 case OMPC_from:
8253 case OMPC_use_device_ptr:
8254 case OMPC_is_device_ptr:
8255 llvm_unreachable("Unexpected OpenMP clause.");
8256 }
8257 return CaptureRegion;
8258}
8259
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008260OMPClause *Sema::ActOnOpenMPIfClause(OpenMPDirectiveKind NameModifier,
8261 Expr *Condition, SourceLocation StartLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008262 SourceLocation LParenLoc,
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008263 SourceLocation NameModifierLoc,
8264 SourceLocation ColonLoc,
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008265 SourceLocation EndLoc) {
8266 Expr *ValExpr = Condition;
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008267 Stmt *HelperValStmt = nullptr;
8268 OpenMPDirectiveKind CaptureRegion = OMPD_unknown;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008269 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8270 !Condition->isInstantiationDependent() &&
8271 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008272 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008273 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008274 return nullptr;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008275
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008276 ValExpr = Val.get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008277
8278 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
8279 CaptureRegion =
8280 getOpenMPCaptureRegionForClause(DKind, OMPC_if, NameModifier);
Alexey Bataev2ba67042017-11-28 21:11:44 +00008281 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008282 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008283 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8284 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8285 HelperValStmt = buildPreInits(Context, Captures);
8286 }
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008287 }
8288
Arpith Chacko Jacobfe4890a2017-01-18 20:40:48 +00008289 return new (Context)
8290 OMPIfClause(NameModifier, ValExpr, HelperValStmt, CaptureRegion, StartLoc,
8291 LParenLoc, NameModifierLoc, ColonLoc, EndLoc);
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008292}
8293
Alexey Bataev3778b602014-07-17 07:32:53 +00008294OMPClause *Sema::ActOnOpenMPFinalClause(Expr *Condition,
8295 SourceLocation StartLoc,
8296 SourceLocation LParenLoc,
8297 SourceLocation EndLoc) {
8298 Expr *ValExpr = Condition;
8299 if (!Condition->isValueDependent() && !Condition->isTypeDependent() &&
8300 !Condition->isInstantiationDependent() &&
8301 !Condition->containsUnexpandedParameterPack()) {
Richard Smith03a4aa32016-06-23 19:02:52 +00008302 ExprResult Val = CheckBooleanCondition(StartLoc, Condition);
Alexey Bataev3778b602014-07-17 07:32:53 +00008303 if (Val.isInvalid())
8304 return nullptr;
8305
Richard Smith03a4aa32016-06-23 19:02:52 +00008306 ValExpr = MakeFullExpr(Val.get()).get();
Alexey Bataev3778b602014-07-17 07:32:53 +00008307 }
8308
8309 return new (Context) OMPFinalClause(ValExpr, StartLoc, LParenLoc, EndLoc);
8310}
Alexander Musmana8e9d2e2014-06-03 10:16:47 +00008311ExprResult Sema::PerformOpenMPImplicitIntegerConversion(SourceLocation Loc,
8312 Expr *Op) {
Alexey Bataev568a8332014-03-06 06:15:19 +00008313 if (!Op)
8314 return ExprError();
8315
8316 class IntConvertDiagnoser : public ICEConvertDiagnoser {
8317 public:
8318 IntConvertDiagnoser()
Alexey Bataeved09d242014-05-28 05:53:51 +00008319 : ICEConvertDiagnoser(/*AllowScopedEnumerations*/ false, false, true) {}
Craig Toppere14c0f82014-03-12 04:55:44 +00008320 SemaDiagnosticBuilder diagnoseNotInt(Sema &S, SourceLocation Loc,
8321 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008322 return S.Diag(Loc, diag::err_omp_not_integral) << T;
8323 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008324 SemaDiagnosticBuilder diagnoseIncomplete(Sema &S, SourceLocation Loc,
8325 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008326 return S.Diag(Loc, diag::err_omp_incomplete_type) << T;
8327 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008328 SemaDiagnosticBuilder diagnoseExplicitConv(Sema &S, SourceLocation Loc,
8329 QualType T,
8330 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008331 return S.Diag(Loc, diag::err_omp_explicit_conversion) << T << ConvTy;
8332 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008333 SemaDiagnosticBuilder noteExplicitConv(Sema &S, CXXConversionDecl *Conv,
8334 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008335 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008336 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008337 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008338 SemaDiagnosticBuilder diagnoseAmbiguous(Sema &S, SourceLocation Loc,
8339 QualType T) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008340 return S.Diag(Loc, diag::err_omp_ambiguous_conversion) << T;
8341 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008342 SemaDiagnosticBuilder noteAmbiguous(Sema &S, CXXConversionDecl *Conv,
8343 QualType ConvTy) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008344 return S.Diag(Conv->getLocation(), diag::note_omp_conversion_here)
Alexey Bataeved09d242014-05-28 05:53:51 +00008345 << ConvTy->isEnumeralType() << ConvTy;
Alexey Bataev568a8332014-03-06 06:15:19 +00008346 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008347 SemaDiagnosticBuilder diagnoseConversion(Sema &, SourceLocation, QualType,
8348 QualType) override {
Alexey Bataev568a8332014-03-06 06:15:19 +00008349 llvm_unreachable("conversion functions are permitted");
8350 }
8351 } ConvertDiagnoser;
8352 return PerformContextualImplicitConversion(Loc, Op, ConvertDiagnoser);
8353}
8354
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008355static bool IsNonNegativeIntegerValue(Expr *&ValExpr, Sema &SemaRef,
Alexey Bataeva0569352015-12-01 10:17:31 +00008356 OpenMPClauseKind CKind,
8357 bool StrictlyPositive) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008358 if (!ValExpr->isTypeDependent() && !ValExpr->isValueDependent() &&
8359 !ValExpr->isInstantiationDependent()) {
8360 SourceLocation Loc = ValExpr->getExprLoc();
8361 ExprResult Value =
8362 SemaRef.PerformOpenMPImplicitIntegerConversion(Loc, ValExpr);
8363 if (Value.isInvalid())
8364 return false;
8365
8366 ValExpr = Value.get();
8367 // The expression must evaluate to a non-negative integer value.
8368 llvm::APSInt Result;
8369 if (ValExpr->isIntegerConstantExpr(Result, SemaRef.Context) &&
Alexey Bataeva0569352015-12-01 10:17:31 +00008370 Result.isSigned() &&
8371 !((!StrictlyPositive && Result.isNonNegative()) ||
8372 (StrictlyPositive && Result.isStrictlyPositive()))) {
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008373 SemaRef.Diag(Loc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008374 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8375 << ValExpr->getSourceRange();
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008376 return false;
8377 }
8378 }
8379 return true;
8380}
8381
Alexey Bataev568a8332014-03-06 06:15:19 +00008382OMPClause *Sema::ActOnOpenMPNumThreadsClause(Expr *NumThreads,
8383 SourceLocation StartLoc,
8384 SourceLocation LParenLoc,
8385 SourceLocation EndLoc) {
8386 Expr *ValExpr = NumThreads;
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008387 Stmt *HelperValStmt = nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008388
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008389 // OpenMP [2.5, Restrictions]
8390 // The num_threads expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +00008391 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_threads,
8392 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008393 return nullptr;
Alexey Bataev568a8332014-03-06 06:15:19 +00008394
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008395 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +00008396 OpenMPDirectiveKind CaptureRegion =
8397 getOpenMPCaptureRegionForClause(DKind, OMPC_num_threads);
8398 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008399 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacob33c849a2017-01-25 00:57:16 +00008400 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8401 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8402 HelperValStmt = buildPreInits(Context, Captures);
8403 }
8404
8405 return new (Context) OMPNumThreadsClause(
8406 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Alexey Bataev568a8332014-03-06 06:15:19 +00008407}
8408
Alexey Bataev62c87d22014-03-21 04:51:18 +00008409ExprResult Sema::VerifyPositiveIntegerConstantInClause(Expr *E,
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008410 OpenMPClauseKind CKind,
8411 bool StrictlyPositive) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008412 if (!E)
8413 return ExprError();
8414 if (E->isValueDependent() || E->isTypeDependent() ||
8415 E->isInstantiationDependent() || E->containsUnexpandedParameterPack())
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00008416 return E;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008417 llvm::APSInt Result;
8418 ExprResult ICE = VerifyIntegerConstantExpression(E, &Result);
8419 if (ICE.isInvalid())
8420 return ExprError();
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008421 if ((StrictlyPositive && !Result.isStrictlyPositive()) ||
8422 (!StrictlyPositive && !Result.isNonNegative())) {
Alexey Bataev62c87d22014-03-21 04:51:18 +00008423 Diag(E->getExprLoc(), diag::err_omp_negative_expression_in_clause)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008424 << getOpenMPClauseName(CKind) << (StrictlyPositive ? 1 : 0)
8425 << E->getSourceRange();
Alexey Bataev62c87d22014-03-21 04:51:18 +00008426 return ExprError();
8427 }
Alexander Musman09184fe2014-09-30 05:29:28 +00008428 if (CKind == OMPC_aligned && !Result.isPowerOf2()) {
8429 Diag(E->getExprLoc(), diag::warn_omp_alignment_not_power_of_two)
8430 << E->getSourceRange();
8431 return ExprError();
8432 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008433 if (CKind == OMPC_collapse && DSAStack->getAssociatedLoops() == 1)
8434 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev7b6bc882015-11-26 07:50:39 +00008435 else if (CKind == OMPC_ordered)
Alexey Bataeva636c7f2015-12-23 10:27:45 +00008436 DSAStack->setAssociatedLoops(Result.getExtValue());
Alexey Bataev62c87d22014-03-21 04:51:18 +00008437 return ICE;
8438}
8439
8440OMPClause *Sema::ActOnOpenMPSafelenClause(Expr *Len, SourceLocation StartLoc,
8441 SourceLocation LParenLoc,
8442 SourceLocation EndLoc) {
8443 // OpenMP [2.8.1, simd construct, Description]
8444 // The parameter of the safelen clause must be a constant
8445 // positive integer expression.
8446 ExprResult Safelen = VerifyPositiveIntegerConstantInClause(Len, OMPC_safelen);
8447 if (Safelen.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008448 return nullptr;
Alexey Bataev62c87d22014-03-21 04:51:18 +00008449 return new (Context)
Nikola Smiljanic01a75982014-05-29 10:55:11 +00008450 OMPSafelenClause(Safelen.get(), StartLoc, LParenLoc, EndLoc);
Alexey Bataev62c87d22014-03-21 04:51:18 +00008451}
8452
Alexey Bataev66b15b52015-08-21 11:14:16 +00008453OMPClause *Sema::ActOnOpenMPSimdlenClause(Expr *Len, SourceLocation StartLoc,
8454 SourceLocation LParenLoc,
8455 SourceLocation EndLoc) {
8456 // OpenMP [2.8.1, simd construct, Description]
8457 // The parameter of the simdlen clause must be a constant
8458 // positive integer expression.
8459 ExprResult Simdlen = VerifyPositiveIntegerConstantInClause(Len, OMPC_simdlen);
8460 if (Simdlen.isInvalid())
8461 return nullptr;
8462 return new (Context)
8463 OMPSimdlenClause(Simdlen.get(), StartLoc, LParenLoc, EndLoc);
8464}
8465
Alexander Musman64d33f12014-06-04 07:53:32 +00008466OMPClause *Sema::ActOnOpenMPCollapseClause(Expr *NumForLoops,
8467 SourceLocation StartLoc,
Alexander Musman8bd31e62014-05-27 15:12:19 +00008468 SourceLocation LParenLoc,
8469 SourceLocation EndLoc) {
Alexander Musman64d33f12014-06-04 07:53:32 +00008470 // OpenMP [2.7.1, loop construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008471 // OpenMP [2.8.1, simd construct, Description]
Alexander Musman64d33f12014-06-04 07:53:32 +00008472 // OpenMP [2.9.6, distribute construct, Description]
Alexander Musman8bd31e62014-05-27 15:12:19 +00008473 // The parameter of the collapse clause must be a constant
8474 // positive integer expression.
Alexander Musman64d33f12014-06-04 07:53:32 +00008475 ExprResult NumForLoopsResult =
8476 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_collapse);
8477 if (NumForLoopsResult.isInvalid())
Alexander Musman8bd31e62014-05-27 15:12:19 +00008478 return nullptr;
8479 return new (Context)
Alexander Musman64d33f12014-06-04 07:53:32 +00008480 OMPCollapseClause(NumForLoopsResult.get(), StartLoc, LParenLoc, EndLoc);
Alexander Musman8bd31e62014-05-27 15:12:19 +00008481}
8482
Alexey Bataev10e775f2015-07-30 11:36:16 +00008483OMPClause *Sema::ActOnOpenMPOrderedClause(SourceLocation StartLoc,
8484 SourceLocation EndLoc,
8485 SourceLocation LParenLoc,
8486 Expr *NumForLoops) {
Alexey Bataev10e775f2015-07-30 11:36:16 +00008487 // OpenMP [2.7.1, loop construct, Description]
8488 // OpenMP [2.8.1, simd construct, Description]
8489 // OpenMP [2.9.6, distribute construct, Description]
8490 // The parameter of the ordered clause must be a constant
8491 // positive integer expression if any.
8492 if (NumForLoops && LParenLoc.isValid()) {
8493 ExprResult NumForLoopsResult =
8494 VerifyPositiveIntegerConstantInClause(NumForLoops, OMPC_ordered);
8495 if (NumForLoopsResult.isInvalid())
8496 return nullptr;
8497 NumForLoops = NumForLoopsResult.get();
Alexey Bataev346265e2015-09-25 10:37:12 +00008498 } else
8499 NumForLoops = nullptr;
8500 DSAStack->setOrderedRegion(/*IsOrdered=*/true, NumForLoops);
Alexey Bataev10e775f2015-07-30 11:36:16 +00008501 return new (Context)
8502 OMPOrderedClause(NumForLoops, StartLoc, LParenLoc, EndLoc);
8503}
8504
Alexey Bataeved09d242014-05-28 05:53:51 +00008505OMPClause *Sema::ActOnOpenMPSimpleClause(
8506 OpenMPClauseKind Kind, unsigned Argument, SourceLocation ArgumentLoc,
8507 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008508 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008509 switch (Kind) {
8510 case OMPC_default:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008511 Res =
Alexey Bataeved09d242014-05-28 05:53:51 +00008512 ActOnOpenMPDefaultClause(static_cast<OpenMPDefaultClauseKind>(Argument),
8513 ArgumentLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008514 break;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008515 case OMPC_proc_bind:
Alexey Bataeved09d242014-05-28 05:53:51 +00008516 Res = ActOnOpenMPProcBindClause(
8517 static_cast<OpenMPProcBindClauseKind>(Argument), ArgumentLoc, StartLoc,
8518 LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008519 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008520 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008521 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00008522 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00008523 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008524 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00008525 case OMPC_collapse:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008526 case OMPC_schedule:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008527 case OMPC_private:
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008528 case OMPC_firstprivate:
Alexander Musman1bb328c2014-06-04 13:06:39 +00008529 case OMPC_lastprivate:
Alexey Bataev758e55e2013-09-06 18:03:48 +00008530 case OMPC_shared:
Alexey Bataevc5e02582014-06-16 07:08:35 +00008531 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008532 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008533 case OMPC_in_reduction:
Alexander Musman8dba6642014-04-22 13:09:42 +00008534 case OMPC_linear:
Alexander Musmanf0d76e72014-05-29 14:36:25 +00008535 case OMPC_aligned:
Alexey Bataevd48bcd82014-03-31 03:36:38 +00008536 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008537 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008538 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008539 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008540 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008541 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008542 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008543 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008544 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008545 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008546 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008547 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008548 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008549 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008550 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008551 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008552 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008553 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008554 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008555 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008556 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008557 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008558 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008559 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008560 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008561 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008562 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008563 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008564 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008565 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008566 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008567 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008568 case OMPC_is_device_ptr:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008569 llvm_unreachable("Clause is not allowed.");
8570 }
8571 return Res;
8572}
8573
Alexey Bataev6402bca2015-12-28 07:25:51 +00008574static std::string
8575getListOfPossibleValues(OpenMPClauseKind K, unsigned First, unsigned Last,
8576 ArrayRef<unsigned> Exclude = llvm::None) {
8577 std::string Values;
8578 unsigned Bound = Last >= 2 ? Last - 2 : 0;
8579 unsigned Skipped = Exclude.size();
8580 auto S = Exclude.begin(), E = Exclude.end();
8581 for (unsigned i = First; i < Last; ++i) {
8582 if (std::find(S, E, i) != E) {
8583 --Skipped;
8584 continue;
8585 }
8586 Values += "'";
8587 Values += getOpenMPSimpleClauseTypeName(K, i);
8588 Values += "'";
8589 if (i == Bound - Skipped)
8590 Values += " or ";
8591 else if (i != Bound + 1 - Skipped)
8592 Values += ", ";
8593 }
8594 return Values;
8595}
8596
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008597OMPClause *Sema::ActOnOpenMPDefaultClause(OpenMPDefaultClauseKind Kind,
8598 SourceLocation KindKwLoc,
8599 SourceLocation StartLoc,
8600 SourceLocation LParenLoc,
8601 SourceLocation EndLoc) {
8602 if (Kind == OMPC_DEFAULT_unknown) {
Alexey Bataev4ca40ed2014-05-12 04:23:46 +00008603 static_assert(OMPC_DEFAULT_unknown > 0,
8604 "OMPC_DEFAULT_unknown not greater than 0");
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008605 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008606 << getListOfPossibleValues(OMPC_default, /*First=*/0,
8607 /*Last=*/OMPC_DEFAULT_unknown)
8608 << getOpenMPClauseName(OMPC_default);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008609 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008610 }
Alexey Bataev758e55e2013-09-06 18:03:48 +00008611 switch (Kind) {
8612 case OMPC_DEFAULT_none:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008613 DSAStack->setDefaultDSANone(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008614 break;
8615 case OMPC_DEFAULT_shared:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008616 DSAStack->setDefaultDSAShared(KindKwLoc);
Alexey Bataev758e55e2013-09-06 18:03:48 +00008617 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008618 case OMPC_DEFAULT_unknown:
Alexey Bataevaadd52e2014-02-13 05:29:23 +00008619 llvm_unreachable("Clause kind is not allowed.");
Alexey Bataev758e55e2013-09-06 18:03:48 +00008620 break;
8621 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008622 return new (Context)
8623 OMPDefaultClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008624}
8625
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008626OMPClause *Sema::ActOnOpenMPProcBindClause(OpenMPProcBindClauseKind Kind,
8627 SourceLocation KindKwLoc,
8628 SourceLocation StartLoc,
8629 SourceLocation LParenLoc,
8630 SourceLocation EndLoc) {
8631 if (Kind == OMPC_PROC_BIND_unknown) {
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008632 Diag(KindKwLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +00008633 << getListOfPossibleValues(OMPC_proc_bind, /*First=*/0,
8634 /*Last=*/OMPC_PROC_BIND_unknown)
8635 << getOpenMPClauseName(OMPC_proc_bind);
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008636 return nullptr;
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008637 }
Alexey Bataeved09d242014-05-28 05:53:51 +00008638 return new (Context)
8639 OMPProcBindClause(Kind, KindKwLoc, StartLoc, LParenLoc, EndLoc);
Alexey Bataevbcbadb62014-05-06 06:04:14 +00008640}
8641
Alexey Bataev56dafe82014-06-20 07:16:17 +00008642OMPClause *Sema::ActOnOpenMPSingleExprWithArgClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008643 OpenMPClauseKind Kind, ArrayRef<unsigned> Argument, Expr *Expr,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008644 SourceLocation StartLoc, SourceLocation LParenLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008645 ArrayRef<SourceLocation> ArgumentLoc, SourceLocation DelimLoc,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008646 SourceLocation EndLoc) {
8647 OMPClause *Res = nullptr;
8648 switch (Kind) {
8649 case OMPC_schedule:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008650 enum { Modifier1, Modifier2, ScheduleKind, NumberOfElements };
8651 assert(Argument.size() == NumberOfElements &&
8652 ArgumentLoc.size() == NumberOfElements);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008653 Res = ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008654 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier1]),
8655 static_cast<OpenMPScheduleClauseModifier>(Argument[Modifier2]),
8656 static_cast<OpenMPScheduleClauseKind>(Argument[ScheduleKind]), Expr,
8657 StartLoc, LParenLoc, ArgumentLoc[Modifier1], ArgumentLoc[Modifier2],
8658 ArgumentLoc[ScheduleKind], DelimLoc, EndLoc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008659 break;
8660 case OMPC_if:
Alexey Bataev6402bca2015-12-28 07:25:51 +00008661 assert(Argument.size() == 1 && ArgumentLoc.size() == 1);
8662 Res = ActOnOpenMPIfClause(static_cast<OpenMPDirectiveKind>(Argument.back()),
8663 Expr, StartLoc, LParenLoc, ArgumentLoc.back(),
8664 DelimLoc, EndLoc);
Alexey Bataev6b8046a2015-09-03 07:23:48 +00008665 break;
Carlo Bertollib4adf552016-01-15 18:50:31 +00008666 case OMPC_dist_schedule:
8667 Res = ActOnOpenMPDistScheduleClause(
8668 static_cast<OpenMPDistScheduleClauseKind>(Argument.back()), Expr,
8669 StartLoc, LParenLoc, ArgumentLoc.back(), DelimLoc, EndLoc);
8670 break;
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008671 case OMPC_defaultmap:
8672 enum { Modifier, DefaultmapKind };
8673 Res = ActOnOpenMPDefaultmapClause(
8674 static_cast<OpenMPDefaultmapClauseModifier>(Argument[Modifier]),
8675 static_cast<OpenMPDefaultmapClauseKind>(Argument[DefaultmapKind]),
David Majnemer9d168222016-08-05 17:44:54 +00008676 StartLoc, LParenLoc, ArgumentLoc[Modifier], ArgumentLoc[DefaultmapKind],
8677 EndLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008678 break;
Alexey Bataev3778b602014-07-17 07:32:53 +00008679 case OMPC_final:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008680 case OMPC_num_threads:
8681 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008682 case OMPC_simdlen:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008683 case OMPC_collapse:
8684 case OMPC_default:
8685 case OMPC_proc_bind:
8686 case OMPC_private:
8687 case OMPC_firstprivate:
8688 case OMPC_lastprivate:
8689 case OMPC_shared:
8690 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008691 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008692 case OMPC_in_reduction:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008693 case OMPC_linear:
8694 case OMPC_aligned:
8695 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008696 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008697 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00008698 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008699 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008700 case OMPC_mergeable:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008701 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008702 case OMPC_flush:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008703 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00008704 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00008705 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00008706 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008707 case OMPC_seq_cst:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008708 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008709 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00008710 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008711 case OMPC_simd:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008712 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008713 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008714 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008715 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008716 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00008717 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00008718 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008719 case OMPC_hint:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008720 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008721 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008722 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008723 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008724 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008725 case OMPC_is_device_ptr:
Alexey Bataev56dafe82014-06-20 07:16:17 +00008726 llvm_unreachable("Clause is not allowed.");
8727 }
8728 return Res;
8729}
8730
Alexey Bataev6402bca2015-12-28 07:25:51 +00008731static bool checkScheduleModifiers(Sema &S, OpenMPScheduleClauseModifier M1,
8732 OpenMPScheduleClauseModifier M2,
8733 SourceLocation M1Loc, SourceLocation M2Loc) {
8734 if (M1 == OMPC_SCHEDULE_MODIFIER_unknown && M1Loc.isValid()) {
8735 SmallVector<unsigned, 2> Excluded;
8736 if (M2 != OMPC_SCHEDULE_MODIFIER_unknown)
8737 Excluded.push_back(M2);
8738 if (M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic)
8739 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_monotonic);
8740 if (M2 == OMPC_SCHEDULE_MODIFIER_monotonic)
8741 Excluded.push_back(OMPC_SCHEDULE_MODIFIER_nonmonotonic);
8742 S.Diag(M1Loc, diag::err_omp_unexpected_clause_value)
8743 << getListOfPossibleValues(OMPC_schedule,
8744 /*First=*/OMPC_SCHEDULE_MODIFIER_unknown + 1,
8745 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8746 Excluded)
8747 << getOpenMPClauseName(OMPC_schedule);
8748 return true;
8749 }
8750 return false;
8751}
8752
Alexey Bataev56dafe82014-06-20 07:16:17 +00008753OMPClause *Sema::ActOnOpenMPScheduleClause(
Alexey Bataev6402bca2015-12-28 07:25:51 +00008754 OpenMPScheduleClauseModifier M1, OpenMPScheduleClauseModifier M2,
Alexey Bataev56dafe82014-06-20 07:16:17 +00008755 OpenMPScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
Alexey Bataev6402bca2015-12-28 07:25:51 +00008756 SourceLocation LParenLoc, SourceLocation M1Loc, SourceLocation M2Loc,
8757 SourceLocation KindLoc, SourceLocation CommaLoc, SourceLocation EndLoc) {
8758 if (checkScheduleModifiers(*this, M1, M2, M1Loc, M2Loc) ||
8759 checkScheduleModifiers(*this, M2, M1, M2Loc, M1Loc))
8760 return nullptr;
8761 // OpenMP, 2.7.1, Loop Construct, Restrictions
8762 // Either the monotonic modifier or the nonmonotonic modifier can be specified
8763 // but not both.
8764 if ((M1 == M2 && M1 != OMPC_SCHEDULE_MODIFIER_unknown) ||
8765 (M1 == OMPC_SCHEDULE_MODIFIER_monotonic &&
8766 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) ||
8767 (M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic &&
8768 M2 == OMPC_SCHEDULE_MODIFIER_monotonic)) {
8769 Diag(M2Loc, diag::err_omp_unexpected_schedule_modifier)
8770 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M2)
8771 << getOpenMPSimpleClauseTypeName(OMPC_schedule, M1);
8772 return nullptr;
8773 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008774 if (Kind == OMPC_SCHEDULE_unknown) {
8775 std::string Values;
Alexey Bataev6402bca2015-12-28 07:25:51 +00008776 if (M1Loc.isInvalid() && M2Loc.isInvalid()) {
8777 unsigned Exclude[] = {OMPC_SCHEDULE_unknown};
8778 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8779 /*Last=*/OMPC_SCHEDULE_MODIFIER_last,
8780 Exclude);
8781 } else {
8782 Values = getListOfPossibleValues(OMPC_schedule, /*First=*/0,
8783 /*Last=*/OMPC_SCHEDULE_unknown);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008784 }
8785 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
8786 << Values << getOpenMPClauseName(OMPC_schedule);
8787 return nullptr;
8788 }
Alexey Bataev6402bca2015-12-28 07:25:51 +00008789 // OpenMP, 2.7.1, Loop Construct, Restrictions
8790 // The nonmonotonic modifier can only be specified with schedule(dynamic) or
8791 // schedule(guided).
8792 if ((M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ||
8793 M2 == OMPC_SCHEDULE_MODIFIER_nonmonotonic) &&
8794 Kind != OMPC_SCHEDULE_dynamic && Kind != OMPC_SCHEDULE_guided) {
8795 Diag(M1 == OMPC_SCHEDULE_MODIFIER_nonmonotonic ? M1Loc : M2Loc,
8796 diag::err_omp_schedule_nonmonotonic_static);
8797 return nullptr;
8798 }
Alexey Bataev56dafe82014-06-20 07:16:17 +00008799 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +00008800 Stmt *HelperValStmt = nullptr;
Alexey Bataev56dafe82014-06-20 07:16:17 +00008801 if (ChunkSize) {
8802 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
8803 !ChunkSize->isInstantiationDependent() &&
8804 !ChunkSize->containsUnexpandedParameterPack()) {
8805 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
8806 ExprResult Val =
8807 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
8808 if (Val.isInvalid())
8809 return nullptr;
8810
8811 ValExpr = Val.get();
8812
8813 // OpenMP [2.7.1, Restrictions]
8814 // chunk_size must be a loop invariant integer expression with a positive
8815 // value.
8816 llvm::APSInt Result;
Alexey Bataev040d5402015-05-12 08:35:28 +00008817 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
8818 if (Result.isSigned() && !Result.isStrictlyPositive()) {
8819 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
Alexey Bataeva0569352015-12-01 10:17:31 +00008820 << "schedule" << 1 << ChunkSize->getSourceRange();
Alexey Bataev040d5402015-05-12 08:35:28 +00008821 return nullptr;
8822 }
Alexey Bataev2ba67042017-11-28 21:11:44 +00008823 } else if (getOpenMPCaptureRegionForClause(
8824 DSAStack->getCurrentDirective(), OMPC_schedule) !=
8825 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +00008826 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +00008827 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +00008828 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
8829 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
8830 HelperValStmt = buildPreInits(Context, Captures);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008831 }
8832 }
8833 }
8834
Alexey Bataev6402bca2015-12-28 07:25:51 +00008835 return new (Context)
8836 OMPScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc, Kind,
Alexey Bataev3392d762016-02-16 11:18:12 +00008837 ValExpr, HelperValStmt, M1, M1Loc, M2, M2Loc);
Alexey Bataev56dafe82014-06-20 07:16:17 +00008838}
8839
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008840OMPClause *Sema::ActOnOpenMPClause(OpenMPClauseKind Kind,
8841 SourceLocation StartLoc,
8842 SourceLocation EndLoc) {
8843 OMPClause *Res = nullptr;
8844 switch (Kind) {
8845 case OMPC_ordered:
8846 Res = ActOnOpenMPOrderedClause(StartLoc, EndLoc);
8847 break;
Alexey Bataev236070f2014-06-20 11:19:47 +00008848 case OMPC_nowait:
8849 Res = ActOnOpenMPNowaitClause(StartLoc, EndLoc);
8850 break;
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008851 case OMPC_untied:
8852 Res = ActOnOpenMPUntiedClause(StartLoc, EndLoc);
8853 break;
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008854 case OMPC_mergeable:
8855 Res = ActOnOpenMPMergeableClause(StartLoc, EndLoc);
8856 break;
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008857 case OMPC_read:
8858 Res = ActOnOpenMPReadClause(StartLoc, EndLoc);
8859 break;
Alexey Bataevdea47612014-07-23 07:46:59 +00008860 case OMPC_write:
8861 Res = ActOnOpenMPWriteClause(StartLoc, EndLoc);
8862 break;
Alexey Bataev67a4f222014-07-23 10:25:33 +00008863 case OMPC_update:
8864 Res = ActOnOpenMPUpdateClause(StartLoc, EndLoc);
8865 break;
Alexey Bataev459dec02014-07-24 06:46:57 +00008866 case OMPC_capture:
8867 Res = ActOnOpenMPCaptureClause(StartLoc, EndLoc);
8868 break;
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008869 case OMPC_seq_cst:
8870 Res = ActOnOpenMPSeqCstClause(StartLoc, EndLoc);
8871 break;
Alexey Bataev346265e2015-09-25 10:37:12 +00008872 case OMPC_threads:
8873 Res = ActOnOpenMPThreadsClause(StartLoc, EndLoc);
8874 break;
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008875 case OMPC_simd:
8876 Res = ActOnOpenMPSIMDClause(StartLoc, EndLoc);
8877 break;
Alexey Bataevb825de12015-12-07 10:51:44 +00008878 case OMPC_nogroup:
8879 Res = ActOnOpenMPNogroupClause(StartLoc, EndLoc);
8880 break;
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008881 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00008882 case OMPC_final:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008883 case OMPC_num_threads:
8884 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00008885 case OMPC_simdlen:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008886 case OMPC_collapse:
8887 case OMPC_schedule:
8888 case OMPC_private:
8889 case OMPC_firstprivate:
8890 case OMPC_lastprivate:
8891 case OMPC_shared:
8892 case OMPC_reduction:
Alexey Bataev169d96a2017-07-18 20:17:46 +00008893 case OMPC_task_reduction:
Alexey Bataevfa312f32017-07-21 18:48:21 +00008894 case OMPC_in_reduction:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008895 case OMPC_linear:
8896 case OMPC_aligned:
8897 case OMPC_copyin:
Alexey Bataevbae9a792014-06-27 10:37:06 +00008898 case OMPC_copyprivate:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008899 case OMPC_default:
8900 case OMPC_proc_bind:
8901 case OMPC_threadprivate:
Alexey Bataev6125da92014-07-21 11:26:11 +00008902 case OMPC_flush:
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008903 case OMPC_depend:
Michael Wonge710d542015-08-07 16:16:36 +00008904 case OMPC_device:
Kelvin Li0bff7af2015-11-23 05:32:03 +00008905 case OMPC_map:
Kelvin Li099bb8c2015-11-24 20:50:12 +00008906 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00008907 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00008908 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00008909 case OMPC_grainsize:
Alexey Bataev382967a2015-12-08 12:06:20 +00008910 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00008911 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00008912 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00008913 case OMPC_defaultmap:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008914 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00008915 case OMPC_uniform:
Samuel Antao661c0902016-05-26 17:39:58 +00008916 case OMPC_to:
Samuel Antaoec172c62016-05-26 17:49:04 +00008917 case OMPC_from:
Carlo Bertolli2404b172016-07-13 15:37:16 +00008918 case OMPC_use_device_ptr:
Carlo Bertolli70594e92016-07-13 17:16:49 +00008919 case OMPC_is_device_ptr:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00008920 llvm_unreachable("Clause is not allowed.");
8921 }
8922 return Res;
8923}
8924
Alexey Bataev236070f2014-06-20 11:19:47 +00008925OMPClause *Sema::ActOnOpenMPNowaitClause(SourceLocation StartLoc,
8926 SourceLocation EndLoc) {
Alexey Bataev6d4ed052015-07-01 06:57:41 +00008927 DSAStack->setNowaitRegion();
Alexey Bataev236070f2014-06-20 11:19:47 +00008928 return new (Context) OMPNowaitClause(StartLoc, EndLoc);
8929}
8930
Alexey Bataev7aea99a2014-07-17 12:19:31 +00008931OMPClause *Sema::ActOnOpenMPUntiedClause(SourceLocation StartLoc,
8932 SourceLocation EndLoc) {
8933 return new (Context) OMPUntiedClause(StartLoc, EndLoc);
8934}
8935
Alexey Bataev74ba3a52014-07-17 12:47:03 +00008936OMPClause *Sema::ActOnOpenMPMergeableClause(SourceLocation StartLoc,
8937 SourceLocation EndLoc) {
8938 return new (Context) OMPMergeableClause(StartLoc, EndLoc);
8939}
8940
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008941OMPClause *Sema::ActOnOpenMPReadClause(SourceLocation StartLoc,
8942 SourceLocation EndLoc) {
Alexey Bataevf98b00c2014-07-23 02:27:21 +00008943 return new (Context) OMPReadClause(StartLoc, EndLoc);
8944}
8945
Alexey Bataevdea47612014-07-23 07:46:59 +00008946OMPClause *Sema::ActOnOpenMPWriteClause(SourceLocation StartLoc,
8947 SourceLocation EndLoc) {
8948 return new (Context) OMPWriteClause(StartLoc, EndLoc);
8949}
8950
Alexey Bataev67a4f222014-07-23 10:25:33 +00008951OMPClause *Sema::ActOnOpenMPUpdateClause(SourceLocation StartLoc,
8952 SourceLocation EndLoc) {
8953 return new (Context) OMPUpdateClause(StartLoc, EndLoc);
8954}
8955
Alexey Bataev459dec02014-07-24 06:46:57 +00008956OMPClause *Sema::ActOnOpenMPCaptureClause(SourceLocation StartLoc,
8957 SourceLocation EndLoc) {
8958 return new (Context) OMPCaptureClause(StartLoc, EndLoc);
8959}
8960
Alexey Bataev82bad8b2014-07-24 08:55:34 +00008961OMPClause *Sema::ActOnOpenMPSeqCstClause(SourceLocation StartLoc,
8962 SourceLocation EndLoc) {
8963 return new (Context) OMPSeqCstClause(StartLoc, EndLoc);
8964}
8965
Alexey Bataev346265e2015-09-25 10:37:12 +00008966OMPClause *Sema::ActOnOpenMPThreadsClause(SourceLocation StartLoc,
8967 SourceLocation EndLoc) {
8968 return new (Context) OMPThreadsClause(StartLoc, EndLoc);
8969}
8970
Alexey Bataevd14d1e62015-09-28 06:39:35 +00008971OMPClause *Sema::ActOnOpenMPSIMDClause(SourceLocation StartLoc,
8972 SourceLocation EndLoc) {
8973 return new (Context) OMPSIMDClause(StartLoc, EndLoc);
8974}
8975
Alexey Bataevb825de12015-12-07 10:51:44 +00008976OMPClause *Sema::ActOnOpenMPNogroupClause(SourceLocation StartLoc,
8977 SourceLocation EndLoc) {
8978 return new (Context) OMPNogroupClause(StartLoc, EndLoc);
8979}
8980
Alexey Bataevc5e02582014-06-16 07:08:35 +00008981OMPClause *Sema::ActOnOpenMPVarListClause(
8982 OpenMPClauseKind Kind, ArrayRef<Expr *> VarList, Expr *TailExpr,
8983 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation ColonLoc,
8984 SourceLocation EndLoc, CXXScopeSpec &ReductionIdScopeSpec,
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00008985 const DeclarationNameInfo &ReductionId, OpenMPDependClauseKind DepKind,
Samuel Antao23abd722016-01-19 20:40:49 +00008986 OpenMPLinearClauseKind LinKind, OpenMPMapClauseKind MapTypeModifier,
8987 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
8988 SourceLocation DepLinMapLoc) {
Alexander Musmancb7f9c42014-05-15 13:04:49 +00008989 OMPClause *Res = nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00008990 switch (Kind) {
8991 case OMPC_private:
8992 Res = ActOnOpenMPPrivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8993 break;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00008994 case OMPC_firstprivate:
8995 Res = ActOnOpenMPFirstprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8996 break;
Alexander Musman1bb328c2014-06-04 13:06:39 +00008997 case OMPC_lastprivate:
8998 Res = ActOnOpenMPLastprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
8999 break;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009000 case OMPC_shared:
9001 Res = ActOnOpenMPSharedClause(VarList, StartLoc, LParenLoc, EndLoc);
9002 break;
Alexey Bataevc5e02582014-06-16 07:08:35 +00009003 case OMPC_reduction:
Alexey Bataev23b69422014-06-18 07:08:49 +00009004 Res = ActOnOpenMPReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9005 EndLoc, ReductionIdScopeSpec, ReductionId);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009006 break;
Alexey Bataev169d96a2017-07-18 20:17:46 +00009007 case OMPC_task_reduction:
9008 Res = ActOnOpenMPTaskReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9009 EndLoc, ReductionIdScopeSpec,
9010 ReductionId);
9011 break;
Alexey Bataevfa312f32017-07-21 18:48:21 +00009012 case OMPC_in_reduction:
9013 Res =
9014 ActOnOpenMPInReductionClause(VarList, StartLoc, LParenLoc, ColonLoc,
9015 EndLoc, ReductionIdScopeSpec, ReductionId);
9016 break;
Alexander Musman8dba6642014-04-22 13:09:42 +00009017 case OMPC_linear:
9018 Res = ActOnOpenMPLinearClause(VarList, TailExpr, StartLoc, LParenLoc,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009019 LinKind, DepLinMapLoc, ColonLoc, EndLoc);
Alexander Musman8dba6642014-04-22 13:09:42 +00009020 break;
Alexander Musmanf0d76e72014-05-29 14:36:25 +00009021 case OMPC_aligned:
9022 Res = ActOnOpenMPAlignedClause(VarList, TailExpr, StartLoc, LParenLoc,
9023 ColonLoc, EndLoc);
9024 break;
Alexey Bataevd48bcd82014-03-31 03:36:38 +00009025 case OMPC_copyin:
9026 Res = ActOnOpenMPCopyinClause(VarList, StartLoc, LParenLoc, EndLoc);
9027 break;
Alexey Bataevbae9a792014-06-27 10:37:06 +00009028 case OMPC_copyprivate:
9029 Res = ActOnOpenMPCopyprivateClause(VarList, StartLoc, LParenLoc, EndLoc);
9030 break;
Alexey Bataev6125da92014-07-21 11:26:11 +00009031 case OMPC_flush:
9032 Res = ActOnOpenMPFlushClause(VarList, StartLoc, LParenLoc, EndLoc);
9033 break;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009034 case OMPC_depend:
David Majnemer9d168222016-08-05 17:44:54 +00009035 Res = ActOnOpenMPDependClause(DepKind, DepLinMapLoc, ColonLoc, VarList,
Kelvin Li0bff7af2015-11-23 05:32:03 +00009036 StartLoc, LParenLoc, EndLoc);
9037 break;
9038 case OMPC_map:
Samuel Antao23abd722016-01-19 20:40:49 +00009039 Res = ActOnOpenMPMapClause(MapTypeModifier, MapType, IsMapTypeImplicit,
9040 DepLinMapLoc, ColonLoc, VarList, StartLoc,
9041 LParenLoc, EndLoc);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +00009042 break;
Samuel Antao661c0902016-05-26 17:39:58 +00009043 case OMPC_to:
9044 Res = ActOnOpenMPToClause(VarList, StartLoc, LParenLoc, EndLoc);
9045 break;
Samuel Antaoec172c62016-05-26 17:49:04 +00009046 case OMPC_from:
9047 Res = ActOnOpenMPFromClause(VarList, StartLoc, LParenLoc, EndLoc);
9048 break;
Carlo Bertolli2404b172016-07-13 15:37:16 +00009049 case OMPC_use_device_ptr:
9050 Res = ActOnOpenMPUseDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9051 break;
Carlo Bertolli70594e92016-07-13 17:16:49 +00009052 case OMPC_is_device_ptr:
9053 Res = ActOnOpenMPIsDevicePtrClause(VarList, StartLoc, LParenLoc, EndLoc);
9054 break;
Alexey Bataevaadd52e2014-02-13 05:29:23 +00009055 case OMPC_if:
Alexey Bataev3778b602014-07-17 07:32:53 +00009056 case OMPC_final:
Alexey Bataev568a8332014-03-06 06:15:19 +00009057 case OMPC_num_threads:
Alexey Bataev62c87d22014-03-21 04:51:18 +00009058 case OMPC_safelen:
Alexey Bataev66b15b52015-08-21 11:14:16 +00009059 case OMPC_simdlen:
Alexander Musman8bd31e62014-05-27 15:12:19 +00009060 case OMPC_collapse:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009061 case OMPC_default:
Alexey Bataevbcbadb62014-05-06 06:04:14 +00009062 case OMPC_proc_bind:
Alexey Bataev56dafe82014-06-20 07:16:17 +00009063 case OMPC_schedule:
Alexey Bataev142e1fc2014-06-20 09:44:06 +00009064 case OMPC_ordered:
Alexey Bataev236070f2014-06-20 11:19:47 +00009065 case OMPC_nowait:
Alexey Bataev7aea99a2014-07-17 12:19:31 +00009066 case OMPC_untied:
Alexey Bataev74ba3a52014-07-17 12:47:03 +00009067 case OMPC_mergeable:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009068 case OMPC_threadprivate:
Alexey Bataevf98b00c2014-07-23 02:27:21 +00009069 case OMPC_read:
Alexey Bataevdea47612014-07-23 07:46:59 +00009070 case OMPC_write:
Alexey Bataev67a4f222014-07-23 10:25:33 +00009071 case OMPC_update:
Alexey Bataev459dec02014-07-24 06:46:57 +00009072 case OMPC_capture:
Alexey Bataev82bad8b2014-07-24 08:55:34 +00009073 case OMPC_seq_cst:
Michael Wonge710d542015-08-07 16:16:36 +00009074 case OMPC_device:
Alexey Bataev346265e2015-09-25 10:37:12 +00009075 case OMPC_threads:
Alexey Bataevd14d1e62015-09-28 06:39:35 +00009076 case OMPC_simd:
Kelvin Li099bb8c2015-11-24 20:50:12 +00009077 case OMPC_num_teams:
Kelvin Lia15fb1a2015-11-27 18:47:36 +00009078 case OMPC_thread_limit:
Alexey Bataeva0569352015-12-01 10:17:31 +00009079 case OMPC_priority:
Alexey Bataev1fd4aed2015-12-07 12:52:51 +00009080 case OMPC_grainsize:
Alexey Bataevb825de12015-12-07 10:51:44 +00009081 case OMPC_nogroup:
Alexey Bataev382967a2015-12-08 12:06:20 +00009082 case OMPC_num_tasks:
Alexey Bataev28c75412015-12-15 08:19:24 +00009083 case OMPC_hint:
Carlo Bertollib4adf552016-01-15 18:50:31 +00009084 case OMPC_dist_schedule:
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +00009085 case OMPC_defaultmap:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009086 case OMPC_unknown:
Alexey Bataeve48a5fc2016-04-12 05:28:34 +00009087 case OMPC_uniform:
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009088 llvm_unreachable("Clause is not allowed.");
9089 }
9090 return Res;
9091}
9092
Alexey Bataev90c228f2016-02-08 09:29:13 +00009093ExprResult Sema::getOpenMPCapturedExpr(VarDecl *Capture, ExprValueKind VK,
Alexey Bataev61205072016-03-02 04:57:40 +00009094 ExprObjectKind OK, SourceLocation Loc) {
Alexey Bataev90c228f2016-02-08 09:29:13 +00009095 ExprResult Res = BuildDeclRefExpr(
9096 Capture, Capture->getType().getNonReferenceType(), VK_LValue, Loc);
9097 if (!Res.isUsable())
9098 return ExprError();
9099 if (OK == OK_Ordinary && !getLangOpts().CPlusPlus) {
9100 Res = CreateBuiltinUnaryOp(Loc, UO_Deref, Res.get());
9101 if (!Res.isUsable())
9102 return ExprError();
9103 }
9104 if (VK != VK_LValue && Res.get()->isGLValue()) {
9105 Res = DefaultLvalueConversion(Res.get());
9106 if (!Res.isUsable())
9107 return ExprError();
9108 }
9109 return Res;
9110}
9111
Alexey Bataev60da77e2016-02-29 05:54:20 +00009112static std::pair<ValueDecl *, bool>
9113getPrivateItem(Sema &S, Expr *&RefExpr, SourceLocation &ELoc,
9114 SourceRange &ERange, bool AllowArraySection = false) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009115 if (RefExpr->isTypeDependent() || RefExpr->isValueDependent() ||
9116 RefExpr->containsUnexpandedParameterPack())
9117 return std::make_pair(nullptr, true);
9118
Alexey Bataevd985eda2016-02-10 11:29:16 +00009119 // OpenMP [3.1, C/C++]
9120 // A list item is a variable name.
9121 // OpenMP [2.9.3.3, Restrictions, p.1]
9122 // A variable that is part of another variable (as an array or
9123 // structure element) cannot appear in a private clause.
9124 RefExpr = RefExpr->IgnoreParens();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009125 enum {
9126 NoArrayExpr = -1,
9127 ArraySubscript = 0,
9128 OMPArraySection = 1
9129 } IsArrayExpr = NoArrayExpr;
9130 if (AllowArraySection) {
9131 if (auto *ASE = dyn_cast_or_null<ArraySubscriptExpr>(RefExpr)) {
9132 auto *Base = ASE->getBase()->IgnoreParenImpCasts();
9133 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9134 Base = TempASE->getBase()->IgnoreParenImpCasts();
9135 RefExpr = Base;
9136 IsArrayExpr = ArraySubscript;
9137 } else if (auto *OASE = dyn_cast_or_null<OMPArraySectionExpr>(RefExpr)) {
9138 auto *Base = OASE->getBase()->IgnoreParenImpCasts();
9139 while (auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base))
9140 Base = TempOASE->getBase()->IgnoreParenImpCasts();
9141 while (auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base))
9142 Base = TempASE->getBase()->IgnoreParenImpCasts();
9143 RefExpr = Base;
9144 IsArrayExpr = OMPArraySection;
9145 }
9146 }
9147 ELoc = RefExpr->getExprLoc();
9148 ERange = RefExpr->getSourceRange();
9149 RefExpr = RefExpr->IgnoreParenImpCasts();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009150 auto *DE = dyn_cast_or_null<DeclRefExpr>(RefExpr);
9151 auto *ME = dyn_cast_or_null<MemberExpr>(RefExpr);
9152 if ((!DE || !isa<VarDecl>(DE->getDecl())) &&
9153 (S.getCurrentThisType().isNull() || !ME ||
9154 !isa<CXXThisExpr>(ME->getBase()->IgnoreParenImpCasts()) ||
9155 !isa<FieldDecl>(ME->getMemberDecl()))) {
Alexey Bataev60da77e2016-02-29 05:54:20 +00009156 if (IsArrayExpr != NoArrayExpr)
9157 S.Diag(ELoc, diag::err_omp_expected_base_var_name) << IsArrayExpr
9158 << ERange;
9159 else {
9160 S.Diag(ELoc,
9161 AllowArraySection
9162 ? diag::err_omp_expected_var_name_member_expr_or_array_item
9163 : diag::err_omp_expected_var_name_member_expr)
9164 << (S.getCurrentThisType().isNull() ? 0 : 1) << ERange;
9165 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009166 return std::make_pair(nullptr, false);
9167 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +00009168 return std::make_pair(
9169 getCanonicalDecl(DE ? DE->getDecl() : ME->getMemberDecl()), false);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009170}
9171
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009172OMPClause *Sema::ActOnOpenMPPrivateClause(ArrayRef<Expr *> VarList,
9173 SourceLocation StartLoc,
9174 SourceLocation LParenLoc,
9175 SourceLocation EndLoc) {
9176 SmallVector<Expr *, 8> Vars;
Alexey Bataev03b340a2014-10-21 03:16:40 +00009177 SmallVector<Expr *, 8> PrivateCopies;
Alexey Bataeved09d242014-05-28 05:53:51 +00009178 for (auto &RefExpr : VarList) {
9179 assert(RefExpr && "NULL expr in OpenMP private clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009180 SourceLocation ELoc;
9181 SourceRange ERange;
9182 Expr *SimpleRefExpr = RefExpr;
9183 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009184 if (Res.second) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009185 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009186 Vars.push_back(RefExpr);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009187 PrivateCopies.push_back(nullptr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009188 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009189 ValueDecl *D = Res.first;
9190 if (!D)
9191 continue;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009192
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009193 QualType Type = D->getType();
9194 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009195
9196 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9197 // A variable that appears in a private clause must not have an incomplete
9198 // type or a reference type.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009199 if (RequireCompleteType(ELoc, Type, diag::err_omp_private_incomplete_type))
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009200 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009201 Type = Type.getNonReferenceType();
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009202
Alexey Bataev758e55e2013-09-06 18:03:48 +00009203 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9204 // in a Construct]
9205 // Variables with the predetermined data-sharing attributes may not be
9206 // listed in data-sharing attributes clauses, except for the cases
9207 // listed below. For these exceptions only, listing a predetermined
9208 // variable in a data-sharing attribute clause is allowed and overrides
9209 // the variable's predetermined data-sharing attributes.
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009210 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009211 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_private) {
Alexey Bataeved09d242014-05-28 05:53:51 +00009212 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9213 << getOpenMPClauseName(OMPC_private);
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009214 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009215 continue;
9216 }
9217
Kelvin Libf594a52016-12-17 05:48:59 +00009218 auto CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009219 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009220 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Kelvin Libf594a52016-12-17 05:48:59 +00009221 isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009222 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9223 << getOpenMPClauseName(OMPC_private) << Type
Kelvin Libf594a52016-12-17 05:48:59 +00009224 << getOpenMPDirectiveName(CurrDir);
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009225 bool IsDecl =
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009226 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009227 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009228 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009229 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009230 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009231 continue;
9232 }
9233
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009234 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9235 // A list item cannot appear in both a map clause and a data-sharing
9236 // attribute clause on the same construct
Kelvin Libf594a52016-12-17 05:48:59 +00009237 if (CurrDir == OMPD_target || CurrDir == OMPD_target_parallel ||
Alexey Bataev647dd842018-01-15 20:59:40 +00009238 CurrDir == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +00009239 CurrDir == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +00009240 CurrDir == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lic4bfc6f2017-01-10 04:26:44 +00009241 CurrDir == OMPD_target_teams_distribute_parallel_for_simd ||
Kelvin Lida681182017-01-10 18:08:18 +00009242 CurrDir == OMPD_target_teams_distribute_simd ||
Kelvin Li41010322017-01-10 05:15:35 +00009243 CurrDir == OMPD_target_parallel_for_simd ||
9244 CurrDir == OMPD_target_parallel_for) {
Samuel Antao6890b092016-07-28 14:25:09 +00009245 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009246 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009247 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009248 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9249 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9250 ConflictKind = WhereFoundClauseKind;
9251 return true;
9252 })) {
9253 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009254 << getOpenMPClauseName(OMPC_private)
Samuel Antao6890b092016-07-28 14:25:09 +00009255 << getOpenMPClauseName(ConflictKind)
Kelvin Libf594a52016-12-17 05:48:59 +00009256 << getOpenMPDirectiveName(CurrDir);
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009257 ReportOriginalDSA(*this, DSAStack, D, DVar);
9258 continue;
9259 }
9260 }
9261
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009262 // OpenMP [2.9.3.3, Restrictions, C/C++, p.1]
9263 // A variable of class type (or array thereof) that appears in a private
9264 // clause requires an accessible, unambiguous default constructor for the
9265 // class type.
Alexey Bataev03b340a2014-10-21 03:16:40 +00009266 // Generate helper private variable and initialize it with the default
9267 // value. The address of the original variable is replaced by the address of
9268 // the new private variable in CodeGen. This new variable is not added to
9269 // IdResolver, so the code in the OpenMP region uses original variable for
9270 // proper diagnostics.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009271 Type = Type.getUnqualifiedType();
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009272 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9273 D->hasAttrs() ? &D->getAttrs() : nullptr);
Richard Smith3beb7c62017-01-12 02:27:38 +00009274 ActOnUninitializedDecl(VDPrivate);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009275 if (VDPrivate->isInvalidDecl())
9276 continue;
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009277 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataev48c0bfb2016-01-20 09:07:54 +00009278 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009279
Alexey Bataev90c228f2016-02-08 09:29:13 +00009280 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009281 if (!VD && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009282 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev90c228f2016-02-08 09:29:13 +00009283 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_private, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009284 Vars.push_back((VD || CurContext->isDependentContext())
9285 ? RefExpr->IgnoreParens()
9286 : Ref);
Alexey Bataev03b340a2014-10-21 03:16:40 +00009287 PrivateCopies.push_back(VDPrivateRefExpr);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009288 }
9289
Alexey Bataeved09d242014-05-28 05:53:51 +00009290 if (Vars.empty())
9291 return nullptr;
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009292
Alexey Bataev03b340a2014-10-21 03:16:40 +00009293 return OMPPrivateClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
9294 PrivateCopies);
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00009295}
9296
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009297namespace {
9298class DiagsUninitializedSeveretyRAII {
9299private:
9300 DiagnosticsEngine &Diags;
9301 SourceLocation SavedLoc;
9302 bool IsIgnored;
9303
9304public:
9305 DiagsUninitializedSeveretyRAII(DiagnosticsEngine &Diags, SourceLocation Loc,
9306 bool IsIgnored)
9307 : Diags(Diags), SavedLoc(Loc), IsIgnored(IsIgnored) {
9308 if (!IsIgnored) {
9309 Diags.setSeverity(/*Diag*/ diag::warn_uninit_self_reference_in_init,
9310 /*Map*/ diag::Severity::Ignored, Loc);
9311 }
9312 }
9313 ~DiagsUninitializedSeveretyRAII() {
9314 if (!IsIgnored)
9315 Diags.popMappings(SavedLoc);
9316 }
9317};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009318}
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009319
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009320OMPClause *Sema::ActOnOpenMPFirstprivateClause(ArrayRef<Expr *> VarList,
9321 SourceLocation StartLoc,
9322 SourceLocation LParenLoc,
9323 SourceLocation EndLoc) {
9324 SmallVector<Expr *, 8> Vars;
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009325 SmallVector<Expr *, 8> PrivateCopies;
9326 SmallVector<Expr *, 8> Inits;
Alexey Bataev417089f2016-02-17 13:19:37 +00009327 SmallVector<Decl *, 4> ExprCaptures;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009328 bool IsImplicitClause =
9329 StartLoc.isInvalid() && LParenLoc.isInvalid() && EndLoc.isInvalid();
9330 auto ImplicitClauseLoc = DSAStack->getConstructLoc();
9331
Alexey Bataeved09d242014-05-28 05:53:51 +00009332 for (auto &RefExpr : VarList) {
9333 assert(RefExpr && "NULL expr in OpenMP firstprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009334 SourceLocation ELoc;
9335 SourceRange ERange;
9336 Expr *SimpleRefExpr = RefExpr;
9337 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009338 if (Res.second) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009339 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009340 Vars.push_back(RefExpr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009341 PrivateCopies.push_back(nullptr);
9342 Inits.push_back(nullptr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009343 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009344 ValueDecl *D = Res.first;
9345 if (!D)
9346 continue;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009347
Alexey Bataev60da77e2016-02-29 05:54:20 +00009348 ELoc = IsImplicitClause ? ImplicitClauseLoc : ELoc;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009349 QualType Type = D->getType();
9350 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009351
9352 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
9353 // A variable that appears in a private clause must not have an incomplete
9354 // type or a reference type.
9355 if (RequireCompleteType(ELoc, Type,
Alexey Bataevd985eda2016-02-10 11:29:16 +00009356 diag::err_omp_firstprivate_incomplete_type))
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009357 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009358 Type = Type.getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009359
9360 // OpenMP [2.9.3.4, Restrictions, C/C++, p.1]
9361 // A variable of class type (or array thereof) that appears in a private
Alexey Bataev23b69422014-06-18 07:08:49 +00009362 // clause requires an accessible, unambiguous copy constructor for the
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009363 // class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009364 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009365
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009366 // If an implicit firstprivate variable found it was checked already.
Alexey Bataev005248a2016-02-25 05:25:57 +00009367 DSAStackTy::DSAVarData TopDVar;
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009368 if (!IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009369 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009370 TopDVar = DVar;
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009371 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009372 bool IsConstant = ElemType.isConstant(Context);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009373 // OpenMP [2.4.13, Data-sharing Attribute Clauses]
9374 // A list item that specifies a given variable may not appear in more
9375 // than one clause on the same directive, except that a variable may be
9376 // specified in both firstprivate and lastprivate clauses.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009377 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9378 // A list item may appear in a firstprivate or lastprivate clause but not
9379 // both.
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009380 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_firstprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +00009381 (isOpenMPDistributeDirective(CurrDir) ||
9382 DVar.CKind != OMPC_lastprivate) &&
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009383 DVar.RefExpr) {
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009384 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009385 << getOpenMPClauseName(DVar.CKind)
9386 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009387 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009388 continue;
9389 }
9390
9391 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9392 // in a Construct]
9393 // Variables with the predetermined data-sharing attributes may not be
9394 // listed in data-sharing attributes clauses, except for the cases
9395 // listed below. For these exceptions only, listing a predetermined
9396 // variable in a data-sharing attribute clause is allowed and overrides
9397 // the variable's predetermined data-sharing attributes.
9398 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9399 // in a Construct, C/C++, p.2]
9400 // Variables with const-qualified type having no mutable member may be
9401 // listed in a firstprivate clause, even if they are static data members.
Alexey Bataevd985eda2016-02-10 11:29:16 +00009402 if (!(IsConstant || (VD && VD->isStaticDataMember())) && !DVar.RefExpr &&
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009403 DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared) {
9404 Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataeved09d242014-05-28 05:53:51 +00009405 << getOpenMPClauseName(DVar.CKind)
9406 << getOpenMPClauseName(OMPC_firstprivate);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009407 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009408 continue;
9409 }
9410
9411 // OpenMP [2.9.3.4, Restrictions, p.2]
9412 // A list item that is private within a parallel region must not appear
9413 // in a firstprivate clause on a worksharing construct if any of the
9414 // worksharing regions arising from the worksharing construct ever bind
9415 // to any of the parallel regions arising from the parallel construct.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009416 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9417 // A list item that is private within a teams region must not appear in a
9418 // firstprivate clause on a distribute construct if any of the distribute
9419 // regions arising from the distribute construct ever bind to any of the
9420 // teams regions arising from the teams construct.
9421 // OpenMP 4.5 [2.15.3.4, Restrictions, p.3]
9422 // A list item that appears in a reduction clause of a teams construct
9423 // must not appear in a firstprivate clause on a distribute construct if
9424 // any of the distribute regions arising from the distribute construct
9425 // ever bind to any of the teams regions arising from the teams construct.
9426 if ((isOpenMPWorksharingDirective(CurrDir) ||
9427 isOpenMPDistributeDirective(CurrDir)) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009428 !isOpenMPParallelDirective(CurrDir) &&
9429 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009430 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009431 if (DVar.CKind != OMPC_shared &&
9432 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009433 isOpenMPTeamsDirective(DVar.DKind) ||
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009434 DVar.DKind == OMPD_unknown)) {
Alexey Bataevf29276e2014-06-18 04:14:57 +00009435 Diag(ELoc, diag::err_omp_required_access)
9436 << getOpenMPClauseName(OMPC_firstprivate)
9437 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009438 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009439 continue;
9440 }
9441 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009442 // OpenMP [2.9.3.4, Restrictions, p.3]
9443 // A list item that appears in a reduction clause of a parallel construct
9444 // must not appear in a firstprivate clause on a worksharing or task
9445 // construct if any of the worksharing or task regions arising from the
9446 // worksharing or task construct ever bind to any of the parallel regions
9447 // arising from the parallel construct.
9448 // OpenMP [2.9.3.4, Restrictions, p.4]
9449 // A list item that appears in a reduction clause in worksharing
9450 // construct must not appear in a firstprivate clause in a task construct
9451 // encountered during execution of any of the worksharing regions arising
9452 // from the worksharing construct.
Alexey Bataev35aaee62016-04-13 13:36:48 +00009453 if (isOpenMPTaskingDirective(CurrDir)) {
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009454 DVar = DSAStack->hasInnermostDSA(
9455 D, [](OpenMPClauseKind C) -> bool { return C == OMPC_reduction; },
9456 [](OpenMPDirectiveKind K) -> bool {
9457 return isOpenMPParallelDirective(K) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009458 isOpenMPWorksharingDirective(K) ||
9459 isOpenMPTeamsDirective(K);
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009460 },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009461 /*FromParent=*/true);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009462 if (DVar.CKind == OMPC_reduction &&
9463 (isOpenMPParallelDirective(DVar.DKind) ||
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009464 isOpenMPWorksharingDirective(DVar.DKind) ||
9465 isOpenMPTeamsDirective(DVar.DKind))) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009466 Diag(ELoc, diag::err_omp_parallel_reduction_in_task_firstprivate)
9467 << getOpenMPDirectiveName(DVar.DKind);
Alexey Bataevd985eda2016-02-10 11:29:16 +00009468 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009469 continue;
9470 }
9471 }
Carlo Bertolli6200a3d2015-12-14 14:51:25 +00009472
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009473 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
9474 // A list item cannot appear in both a map clause and a data-sharing
9475 // attribute clause on the same construct
Alexey Bataevb358f992017-12-01 17:40:15 +00009476 if (isOpenMPTargetExecutionDirective(CurrDir)) {
Samuel Antao6890b092016-07-28 14:25:09 +00009477 OpenMPClauseKind ConflictKind;
Samuel Antao90927002016-04-26 14:54:23 +00009478 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +00009479 VD, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +00009480 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef,
9481 OpenMPClauseKind WhereFoundClauseKind) -> bool {
9482 ConflictKind = WhereFoundClauseKind;
9483 return true;
9484 })) {
9485 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009486 << getOpenMPClauseName(OMPC_firstprivate)
Samuel Antao6890b092016-07-28 14:25:09 +00009487 << getOpenMPClauseName(ConflictKind)
Carlo Bertollib74bfc82016-03-18 21:43:32 +00009488 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9489 ReportOriginalDSA(*this, DSAStack, D, DVar);
9490 continue;
9491 }
9492 }
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009493 }
9494
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009495 // Variably modified types are not supported for tasks.
Alexey Bataev5129d3a2015-05-21 09:47:46 +00009496 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType() &&
Alexey Bataev35aaee62016-04-13 13:36:48 +00009497 isOpenMPTaskingDirective(DSAStack->getCurrentDirective())) {
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009498 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
9499 << getOpenMPClauseName(OMPC_firstprivate) << Type
9500 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
9501 bool IsDecl =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009502 !VD ||
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009503 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataevd985eda2016-02-10 11:29:16 +00009504 Diag(D->getLocation(),
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009505 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataevd985eda2016-02-10 11:29:16 +00009506 << D;
Alexey Bataevccb59ec2015-05-19 08:44:56 +00009507 continue;
9508 }
9509
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009510 Type = Type.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009511 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
9512 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009513 // Generate helper private variable and initialize it with the value of the
9514 // original variable. The address of the original variable is replaced by
9515 // the address of the new private variable in the CodeGen. This new variable
9516 // is not added to IdResolver, so the code in the OpenMP region uses
9517 // original variable for proper diagnostics and variable capturing.
9518 Expr *VDInitRefExpr = nullptr;
9519 // For arrays generate initializer for single element and replace it by the
9520 // original array element in CodeGen.
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009521 if (Type->isArrayType()) {
9522 auto VDInit =
Alexey Bataevd985eda2016-02-10 11:29:16 +00009523 buildVarDecl(*this, RefExpr->getExprLoc(), ElemType, D->getName());
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009524 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, ElemType, ELoc);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009525 auto Init = DefaultLvalueConversion(VDInitRefExpr).get();
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009526 ElemType = ElemType.getUnqualifiedType();
Alexey Bataevd985eda2016-02-10 11:29:16 +00009527 auto *VDInitTemp = buildVarDecl(*this, RefExpr->getExprLoc(), ElemType,
Alexey Bataevf120c0d2015-05-19 07:46:42 +00009528 ".firstprivate.temp");
Alexey Bataev69c62a92015-04-15 04:52:20 +00009529 InitializedEntity Entity =
9530 InitializedEntity::InitializeVariable(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009531 InitializationKind Kind = InitializationKind::CreateCopy(ELoc, ELoc);
9532
9533 InitializationSequence InitSeq(*this, Entity, Kind, Init);
9534 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Init);
9535 if (Result.isInvalid())
9536 VDPrivate->setInvalidDecl();
9537 else
9538 VDPrivate->setInit(Result.getAs<Expr>());
Alexey Bataevf24e7b12015-10-08 09:10:53 +00009539 // Remove temp variable declaration.
9540 Context.Deallocate(VDInitTemp);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009541 } else {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009542 auto *VDInit = buildVarDecl(*this, RefExpr->getExprLoc(), Type,
9543 ".firstprivate.temp");
9544 VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
9545 RefExpr->getExprLoc());
Alexey Bataev69c62a92015-04-15 04:52:20 +00009546 AddInitializerToDecl(VDPrivate,
9547 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +00009548 /*DirectInit=*/false);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009549 }
9550 if (VDPrivate->isInvalidDecl()) {
9551 if (IsImplicitClause) {
Alexey Bataevd985eda2016-02-10 11:29:16 +00009552 Diag(RefExpr->getExprLoc(),
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009553 diag::note_omp_task_predetermined_firstprivate_here);
9554 }
9555 continue;
9556 }
9557 CurContext->addDecl(VDPrivate);
Alexey Bataev39f915b82015-05-08 10:41:21 +00009558 auto VDPrivateRefExpr = buildDeclRefExpr(
Alexey Bataevd985eda2016-02-10 11:29:16 +00009559 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(),
9560 RefExpr->getExprLoc());
9561 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009562 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009563 if (TopDVar.CKind == OMPC_lastprivate)
9564 Ref = TopDVar.PrivateCopy;
9565 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009566 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataev005248a2016-02-25 05:25:57 +00009567 if (!IsOpenMPCapturedDecl(D))
9568 ExprCaptures.push_back(Ref->getDecl());
9569 }
Alexey Bataev417089f2016-02-17 13:19:37 +00009570 }
Alexey Bataevd985eda2016-02-10 11:29:16 +00009571 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009572 Vars.push_back((VD || CurContext->isDependentContext())
9573 ? RefExpr->IgnoreParens()
9574 : Ref);
Alexey Bataev4a5bb772014-10-08 14:01:46 +00009575 PrivateCopies.push_back(VDPrivateRefExpr);
9576 Inits.push_back(VDInitRefExpr);
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009577 }
9578
Alexey Bataeved09d242014-05-28 05:53:51 +00009579 if (Vars.empty())
9580 return nullptr;
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009581
9582 return OMPFirstprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009583 Vars, PrivateCopies, Inits,
9584 buildPreInits(Context, ExprCaptures));
Alexey Bataevd5af8e42013-10-01 05:32:34 +00009585}
9586
Alexander Musman1bb328c2014-06-04 13:06:39 +00009587OMPClause *Sema::ActOnOpenMPLastprivateClause(ArrayRef<Expr *> VarList,
9588 SourceLocation StartLoc,
9589 SourceLocation LParenLoc,
9590 SourceLocation EndLoc) {
9591 SmallVector<Expr *, 8> Vars;
Alexey Bataev38e89532015-04-16 04:54:05 +00009592 SmallVector<Expr *, 8> SrcExprs;
9593 SmallVector<Expr *, 8> DstExprs;
9594 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataev005248a2016-02-25 05:25:57 +00009595 SmallVector<Decl *, 4> ExprCaptures;
9596 SmallVector<Expr *, 4> ExprPostUpdates;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009597 for (auto &RefExpr : VarList) {
9598 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009599 SourceLocation ELoc;
9600 SourceRange ERange;
9601 Expr *SimpleRefExpr = RefExpr;
9602 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009603 if (Res.second) {
Alexander Musman1bb328c2014-06-04 13:06:39 +00009604 // It will be analyzed later.
9605 Vars.push_back(RefExpr);
Alexey Bataev38e89532015-04-16 04:54:05 +00009606 SrcExprs.push_back(nullptr);
9607 DstExprs.push_back(nullptr);
9608 AssignmentOps.push_back(nullptr);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009609 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009610 ValueDecl *D = Res.first;
9611 if (!D)
9612 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009613
Alexey Bataev74caaf22016-02-20 04:09:36 +00009614 QualType Type = D->getType();
9615 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009616
9617 // OpenMP [2.14.3.5, Restrictions, C/C++, p.2]
9618 // A variable that appears in a lastprivate clause must not have an
9619 // incomplete type or a reference type.
9620 if (RequireCompleteType(ELoc, Type,
Alexey Bataev74caaf22016-02-20 04:09:36 +00009621 diag::err_omp_lastprivate_incomplete_type))
Alexander Musman1bb328c2014-06-04 13:06:39 +00009622 continue;
Alexey Bataevbd9fec12015-08-18 06:47:21 +00009623 Type = Type.getNonReferenceType();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009624
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009625 OpenMPDirectiveKind CurrDir = DSAStack->getCurrentDirective();
Alexander Musman1bb328c2014-06-04 13:06:39 +00009626 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
9627 // in a Construct]
9628 // Variables with the predetermined data-sharing attributes may not be
9629 // listed in data-sharing attributes clauses, except for the cases
9630 // listed below.
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009631 // OpenMP 4.5 [2.10.8, Distribute Construct, p.3]
9632 // A list item may appear in a firstprivate or lastprivate clause but not
9633 // both.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009634 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009635 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_lastprivate &&
Alexey Bataevb358f992017-12-01 17:40:15 +00009636 (isOpenMPDistributeDirective(CurrDir) ||
9637 DVar.CKind != OMPC_firstprivate) &&
Alexander Musman1bb328c2014-06-04 13:06:39 +00009638 (DVar.CKind != OMPC_private || DVar.RefExpr != nullptr)) {
9639 Diag(ELoc, diag::err_omp_wrong_dsa)
9640 << getOpenMPClauseName(DVar.CKind)
9641 << getOpenMPClauseName(OMPC_lastprivate);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009642 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman1bb328c2014-06-04 13:06:39 +00009643 continue;
9644 }
9645
Alexey Bataevf29276e2014-06-18 04:14:57 +00009646 // OpenMP [2.14.3.5, Restrictions, p.2]
9647 // A list item that is private within a parallel region, or that appears in
9648 // the reduction clause of a parallel construct, must not appear in a
9649 // lastprivate clause on a worksharing construct if any of the corresponding
9650 // worksharing regions ever binds to any of the corresponding parallel
9651 // regions.
Alexey Bataev39f915b82015-05-08 10:41:21 +00009652 DSAStackTy::DSAVarData TopDVar = DVar;
Alexey Bataev549210e2014-06-24 04:39:47 +00009653 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +00009654 !isOpenMPParallelDirective(CurrDir) &&
9655 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataev74caaf22016-02-20 04:09:36 +00009656 DVar = DSAStack->getImplicitDSA(D, true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009657 if (DVar.CKind != OMPC_shared) {
9658 Diag(ELoc, diag::err_omp_required_access)
9659 << getOpenMPClauseName(OMPC_lastprivate)
9660 << getOpenMPClauseName(OMPC_shared);
Alexey Bataev74caaf22016-02-20 04:09:36 +00009661 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009662 continue;
9663 }
9664 }
Alexey Bataev74caaf22016-02-20 04:09:36 +00009665
Alexander Musman1bb328c2014-06-04 13:06:39 +00009666 // OpenMP [2.14.3.5, Restrictions, C++, p.1,2]
Alexey Bataevf29276e2014-06-18 04:14:57 +00009667 // A variable of class type (or array thereof) that appears in a
9668 // lastprivate clause requires an accessible, unambiguous default
9669 // constructor for the class type, unless the list item is also specified
9670 // in a firstprivate clause.
Alexander Musman1bb328c2014-06-04 13:06:39 +00009671 // A variable of class type (or array thereof) that appears in a
9672 // lastprivate clause requires an accessible, unambiguous copy assignment
9673 // operator for the class type.
Alexey Bataev38e89532015-04-16 04:54:05 +00009674 Type = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +00009675 auto *SrcVD = buildVarDecl(*this, ERange.getBegin(),
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +00009676 Type.getUnqualifiedType(), ".lastprivate.src",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009677 D->hasAttrs() ? &D->getAttrs() : nullptr);
9678 auto *PseudoSrcExpr =
9679 buildDeclRefExpr(*this, SrcVD, Type.getUnqualifiedType(), ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009680 auto *DstVD =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009681 buildVarDecl(*this, ERange.getBegin(), Type, ".lastprivate.dst",
Alexey Bataev74caaf22016-02-20 04:09:36 +00009682 D->hasAttrs() ? &D->getAttrs() : nullptr);
9683 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataev38e89532015-04-16 04:54:05 +00009684 // For arrays generate assignment operation for single element and replace
9685 // it by the original array element in CodeGen.
Alexey Bataev74caaf22016-02-20 04:09:36 +00009686 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, ELoc, BO_Assign,
Alexey Bataev38e89532015-04-16 04:54:05 +00009687 PseudoDstExpr, PseudoSrcExpr);
9688 if (AssignmentOp.isInvalid())
9689 continue;
Alexey Bataev74caaf22016-02-20 04:09:36 +00009690 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataev38e89532015-04-16 04:54:05 +00009691 /*DiscardedValue=*/true);
9692 if (AssignmentOp.isInvalid())
9693 continue;
Alexander Musman1bb328c2014-06-04 13:06:39 +00009694
Alexey Bataev74caaf22016-02-20 04:09:36 +00009695 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009696 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009697 if (TopDVar.CKind == OMPC_firstprivate)
9698 Ref = TopDVar.PrivateCopy;
9699 else {
Alexey Bataev61205072016-03-02 04:57:40 +00009700 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev005248a2016-02-25 05:25:57 +00009701 if (!IsOpenMPCapturedDecl(D))
9702 ExprCaptures.push_back(Ref->getDecl());
9703 }
9704 if (TopDVar.CKind == OMPC_firstprivate ||
9705 (!IsOpenMPCapturedDecl(D) &&
Alexey Bataev2bbf7212016-03-03 03:52:24 +00009706 Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>())) {
Alexey Bataev005248a2016-02-25 05:25:57 +00009707 ExprResult RefRes = DefaultLvalueConversion(Ref);
9708 if (!RefRes.isUsable())
9709 continue;
9710 ExprResult PostUpdateRes =
Alexey Bataev60da77e2016-02-29 05:54:20 +00009711 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
9712 RefRes.get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009713 if (!PostUpdateRes.isUsable())
9714 continue;
Alexey Bataev78849fb2016-03-09 09:49:00 +00009715 ExprPostUpdates.push_back(
9716 IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev005248a2016-02-25 05:25:57 +00009717 }
9718 }
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009719 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_lastprivate, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009720 Vars.push_back((VD || CurContext->isDependentContext())
9721 ? RefExpr->IgnoreParens()
9722 : Ref);
Alexey Bataev38e89532015-04-16 04:54:05 +00009723 SrcExprs.push_back(PseudoSrcExpr);
9724 DstExprs.push_back(PseudoDstExpr);
9725 AssignmentOps.push_back(AssignmentOp.get());
Alexander Musman1bb328c2014-06-04 13:06:39 +00009726 }
9727
9728 if (Vars.empty())
9729 return nullptr;
9730
9731 return OMPLastprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
Alexey Bataev005248a2016-02-25 05:25:57 +00009732 Vars, SrcExprs, DstExprs, AssignmentOps,
Alexey Bataev5a3af132016-03-29 08:58:54 +00009733 buildPreInits(Context, ExprCaptures),
9734 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman1bb328c2014-06-04 13:06:39 +00009735}
9736
Alexey Bataev758e55e2013-09-06 18:03:48 +00009737OMPClause *Sema::ActOnOpenMPSharedClause(ArrayRef<Expr *> VarList,
9738 SourceLocation StartLoc,
9739 SourceLocation LParenLoc,
9740 SourceLocation EndLoc) {
9741 SmallVector<Expr *, 8> Vars;
Alexey Bataeved09d242014-05-28 05:53:51 +00009742 for (auto &RefExpr : VarList) {
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009743 assert(RefExpr && "NULL expr in OpenMP lastprivate clause.");
Alexey Bataev60da77e2016-02-29 05:54:20 +00009744 SourceLocation ELoc;
9745 SourceRange ERange;
9746 Expr *SimpleRefExpr = RefExpr;
9747 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009748 if (Res.second) {
Alexey Bataev758e55e2013-09-06 18:03:48 +00009749 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +00009750 Vars.push_back(RefExpr);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009751 }
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009752 ValueDecl *D = Res.first;
9753 if (!D)
9754 continue;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009755
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009756 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009757 // OpenMP [2.9.1.1, Data-sharing Attribute Rules for Variables Referenced
9758 // in a Construct]
9759 // Variables with the predetermined data-sharing attributes may not be
9760 // listed in data-sharing attributes clauses, except for the cases
9761 // listed below. For these exceptions only, listing a predetermined
9762 // variable in a data-sharing attribute clause is allowed and overrides
9763 // the variable's predetermined data-sharing attributes.
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009764 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeved09d242014-05-28 05:53:51 +00009765 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_shared &&
9766 DVar.RefExpr) {
9767 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
9768 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009769 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009770 continue;
9771 }
9772
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009773 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009774 if (!VD && IsOpenMPCapturedDecl(D) && !CurContext->isDependentContext())
Alexey Bataev61205072016-03-02 04:57:40 +00009775 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
Alexey Bataevb7a34b62016-02-25 03:59:29 +00009776 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_shared, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +00009777 Vars.push_back((VD || !Ref || CurContext->isDependentContext())
9778 ? RefExpr->IgnoreParens()
9779 : Ref);
Alexey Bataev758e55e2013-09-06 18:03:48 +00009780 }
9781
Alexey Bataeved09d242014-05-28 05:53:51 +00009782 if (Vars.empty())
9783 return nullptr;
Alexey Bataev758e55e2013-09-06 18:03:48 +00009784
9785 return OMPSharedClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars);
9786}
9787
Alexey Bataevc5e02582014-06-16 07:08:35 +00009788namespace {
9789class DSARefChecker : public StmtVisitor<DSARefChecker, bool> {
9790 DSAStackTy *Stack;
9791
9792public:
9793 bool VisitDeclRefExpr(DeclRefExpr *E) {
9794 if (VarDecl *VD = dyn_cast<VarDecl>(E->getDecl())) {
Alexey Bataev9c2e8ee2014-07-11 11:25:16 +00009795 DSAStackTy::DSAVarData DVar = Stack->getTopDSA(VD, false);
Alexey Bataevc5e02582014-06-16 07:08:35 +00009796 if (DVar.CKind == OMPC_shared && !DVar.RefExpr)
9797 return false;
9798 if (DVar.CKind != OMPC_unknown)
9799 return true;
Alexey Bataev7ace49d2016-05-17 08:55:33 +00009800 DSAStackTy::DSAVarData DVarPrivate = Stack->hasDSA(
9801 VD, isOpenMPPrivate, [](OpenMPDirectiveKind) -> bool { return true; },
Alexey Bataeveffbdf12017-07-21 17:24:30 +00009802 /*FromParent=*/true);
Alexey Bataevf29276e2014-06-18 04:14:57 +00009803 if (DVarPrivate.CKind != OMPC_unknown)
Alexey Bataevc5e02582014-06-16 07:08:35 +00009804 return true;
9805 return false;
9806 }
9807 return false;
9808 }
9809 bool VisitStmt(Stmt *S) {
9810 for (auto Child : S->children()) {
9811 if (Child && Visit(Child))
9812 return true;
9813 }
9814 return false;
9815 }
Alexey Bataev23b69422014-06-18 07:08:49 +00009816 explicit DSARefChecker(DSAStackTy *S) : Stack(S) {}
Alexey Bataevc5e02582014-06-16 07:08:35 +00009817};
Alexey Bataev23b69422014-06-18 07:08:49 +00009818} // namespace
Alexey Bataevc5e02582014-06-16 07:08:35 +00009819
Alexey Bataev60da77e2016-02-29 05:54:20 +00009820namespace {
9821// Transform MemberExpression for specified FieldDecl of current class to
9822// DeclRefExpr to specified OMPCapturedExprDecl.
9823class TransformExprToCaptures : public TreeTransform<TransformExprToCaptures> {
9824 typedef TreeTransform<TransformExprToCaptures> BaseTransform;
9825 ValueDecl *Field;
9826 DeclRefExpr *CapturedExpr;
9827
9828public:
9829 TransformExprToCaptures(Sema &SemaRef, ValueDecl *FieldDecl)
9830 : BaseTransform(SemaRef), Field(FieldDecl), CapturedExpr(nullptr) {}
9831
9832 ExprResult TransformMemberExpr(MemberExpr *E) {
9833 if (isa<CXXThisExpr>(E->getBase()->IgnoreParenImpCasts()) &&
9834 E->getMemberDecl() == Field) {
Alexey Bataev61205072016-03-02 04:57:40 +00009835 CapturedExpr = buildCapture(SemaRef, Field, E, /*WithInit=*/false);
Alexey Bataev60da77e2016-02-29 05:54:20 +00009836 return CapturedExpr;
9837 }
9838 return BaseTransform::TransformMemberExpr(E);
9839 }
9840 DeclRefExpr *getCapturedExpr() { return CapturedExpr; }
9841};
9842} // namespace
9843
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009844template <typename T>
9845static T filterLookupForUDR(SmallVectorImpl<UnresolvedSet<8>> &Lookups,
9846 const llvm::function_ref<T(ValueDecl *)> &Gen) {
9847 for (auto &Set : Lookups) {
9848 for (auto *D : Set) {
9849 if (auto Res = Gen(cast<ValueDecl>(D)))
9850 return Res;
9851 }
9852 }
9853 return T();
9854}
9855
9856static ExprResult
9857buildDeclareReductionRef(Sema &SemaRef, SourceLocation Loc, SourceRange Range,
9858 Scope *S, CXXScopeSpec &ReductionIdScopeSpec,
9859 const DeclarationNameInfo &ReductionId, QualType Ty,
9860 CXXCastPath &BasePath, Expr *UnresolvedReduction) {
9861 if (ReductionIdScopeSpec.isInvalid())
9862 return ExprError();
9863 SmallVector<UnresolvedSet<8>, 4> Lookups;
9864 if (S) {
9865 LookupResult Lookup(SemaRef, ReductionId, Sema::LookupOMPReductionName);
9866 Lookup.suppressDiagnostics();
9867 while (S && SemaRef.LookupParsedName(Lookup, S, &ReductionIdScopeSpec)) {
9868 auto *D = Lookup.getRepresentativeDecl();
9869 do {
9870 S = S->getParent();
9871 } while (S && !S->isDeclScope(D));
9872 if (S)
9873 S = S->getParent();
9874 Lookups.push_back(UnresolvedSet<8>());
9875 Lookups.back().append(Lookup.begin(), Lookup.end());
9876 Lookup.clear();
9877 }
9878 } else if (auto *ULE =
9879 cast_or_null<UnresolvedLookupExpr>(UnresolvedReduction)) {
9880 Lookups.push_back(UnresolvedSet<8>());
9881 Decl *PrevD = nullptr;
David Majnemer9d168222016-08-05 17:44:54 +00009882 for (auto *D : ULE->decls()) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009883 if (D == PrevD)
9884 Lookups.push_back(UnresolvedSet<8>());
9885 else if (auto *DRD = cast<OMPDeclareReductionDecl>(D))
9886 Lookups.back().addDecl(DRD);
9887 PrevD = D;
9888 }
9889 }
Alexey Bataevfdc20352017-08-25 15:43:55 +00009890 if (SemaRef.CurContext->isDependentContext() || Ty->isDependentType() ||
9891 Ty->isInstantiationDependentType() ||
Alexey Bataeva839ddd2016-03-17 10:19:46 +00009892 Ty->containsUnexpandedParameterPack() ||
9893 filterLookupForUDR<bool>(Lookups, [](ValueDecl *D) -> bool {
9894 return !D->isInvalidDecl() &&
9895 (D->getType()->isDependentType() ||
9896 D->getType()->isInstantiationDependentType() ||
9897 D->getType()->containsUnexpandedParameterPack());
9898 })) {
9899 UnresolvedSet<8> ResSet;
9900 for (auto &Set : Lookups) {
9901 ResSet.append(Set.begin(), Set.end());
9902 // The last item marks the end of all declarations at the specified scope.
9903 ResSet.addDecl(Set[Set.size() - 1]);
9904 }
9905 return UnresolvedLookupExpr::Create(
9906 SemaRef.Context, /*NamingClass=*/nullptr,
9907 ReductionIdScopeSpec.getWithLocInContext(SemaRef.Context), ReductionId,
9908 /*ADL=*/true, /*Overloaded=*/true, ResSet.begin(), ResSet.end());
9909 }
9910 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9911 Lookups, [&SemaRef, Ty](ValueDecl *D) -> ValueDecl * {
9912 if (!D->isInvalidDecl() &&
9913 SemaRef.Context.hasSameType(D->getType(), Ty))
9914 return D;
9915 return nullptr;
9916 }))
9917 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9918 if (auto *VD = filterLookupForUDR<ValueDecl *>(
9919 Lookups, [&SemaRef, Ty, Loc](ValueDecl *D) -> ValueDecl * {
9920 if (!D->isInvalidDecl() &&
9921 SemaRef.IsDerivedFrom(Loc, Ty, D->getType()) &&
9922 !Ty.isMoreQualifiedThan(D->getType()))
9923 return D;
9924 return nullptr;
9925 })) {
9926 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
9927 /*DetectVirtual=*/false);
9928 if (SemaRef.IsDerivedFrom(Loc, Ty, VD->getType(), Paths)) {
9929 if (!Paths.isAmbiguous(SemaRef.Context.getCanonicalType(
9930 VD->getType().getUnqualifiedType()))) {
9931 if (SemaRef.CheckBaseClassAccess(Loc, VD->getType(), Ty, Paths.front(),
9932 /*DiagID=*/0) !=
9933 Sema::AR_inaccessible) {
9934 SemaRef.BuildBasePathArray(Paths, BasePath);
9935 return SemaRef.BuildDeclRefExpr(VD, Ty, VK_LValue, Loc);
9936 }
9937 }
9938 }
9939 }
9940 if (ReductionIdScopeSpec.isSet()) {
9941 SemaRef.Diag(Loc, diag::err_omp_not_resolved_reduction_identifier) << Range;
9942 return ExprError();
9943 }
9944 return ExprEmpty();
9945}
9946
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009947namespace {
9948/// Data for the reduction-based clauses.
9949struct ReductionData {
9950 /// List of original reduction items.
9951 SmallVector<Expr *, 8> Vars;
9952 /// List of private copies of the reduction items.
9953 SmallVector<Expr *, 8> Privates;
9954 /// LHS expressions for the reduction_op expressions.
9955 SmallVector<Expr *, 8> LHSs;
9956 /// RHS expressions for the reduction_op expressions.
9957 SmallVector<Expr *, 8> RHSs;
9958 /// Reduction operation expression.
9959 SmallVector<Expr *, 8> ReductionOps;
Alexey Bataev88202be2017-07-27 13:20:36 +00009960 /// Taskgroup descriptors for the corresponding reduction items in
9961 /// in_reduction clauses.
9962 SmallVector<Expr *, 8> TaskgroupDescriptors;
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009963 /// List of captures for clause.
9964 SmallVector<Decl *, 4> ExprCaptures;
9965 /// List of postupdate expressions.
9966 SmallVector<Expr *, 4> ExprPostUpdates;
9967 ReductionData() = delete;
9968 /// Reserves required memory for the reduction data.
9969 ReductionData(unsigned Size) {
9970 Vars.reserve(Size);
9971 Privates.reserve(Size);
9972 LHSs.reserve(Size);
9973 RHSs.reserve(Size);
9974 ReductionOps.reserve(Size);
Alexey Bataev88202be2017-07-27 13:20:36 +00009975 TaskgroupDescriptors.reserve(Size);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009976 ExprCaptures.reserve(Size);
9977 ExprPostUpdates.reserve(Size);
9978 }
9979 /// Stores reduction item and reduction operation only (required for dependent
9980 /// reduction item).
9981 void push(Expr *Item, Expr *ReductionOp) {
9982 Vars.emplace_back(Item);
9983 Privates.emplace_back(nullptr);
9984 LHSs.emplace_back(nullptr);
9985 RHSs.emplace_back(nullptr);
9986 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009987 TaskgroupDescriptors.emplace_back(nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009988 }
9989 /// Stores reduction data.
Alexey Bataev88202be2017-07-27 13:20:36 +00009990 void push(Expr *Item, Expr *Private, Expr *LHS, Expr *RHS, Expr *ReductionOp,
9991 Expr *TaskgroupDescriptor) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009992 Vars.emplace_back(Item);
9993 Privates.emplace_back(Private);
9994 LHSs.emplace_back(LHS);
9995 RHSs.emplace_back(RHS);
9996 ReductionOps.emplace_back(ReductionOp);
Alexey Bataev88202be2017-07-27 13:20:36 +00009997 TaskgroupDescriptors.emplace_back(TaskgroupDescriptor);
Alexey Bataevfad872fc2017-07-18 15:32:58 +00009998 }
9999};
10000} // namespace
10001
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010002static bool CheckOMPArraySectionConstantForReduction(
10003 ASTContext &Context, const OMPArraySectionExpr *OASE, bool &SingleElement,
10004 SmallVectorImpl<llvm::APSInt> &ArraySizes) {
10005 const Expr *Length = OASE->getLength();
10006 if (Length == nullptr) {
10007 // For array sections of the form [1:] or [:], we would need to analyze
10008 // the lower bound...
10009 if (OASE->getColonLoc().isValid())
10010 return false;
10011
10012 // This is an array subscript which has implicit length 1!
10013 SingleElement = true;
10014 ArraySizes.push_back(llvm::APSInt::get(1));
10015 } else {
10016 llvm::APSInt ConstantLengthValue;
10017 if (!Length->EvaluateAsInt(ConstantLengthValue, Context))
10018 return false;
10019
10020 SingleElement = (ConstantLengthValue.getSExtValue() == 1);
10021 ArraySizes.push_back(ConstantLengthValue);
10022 }
10023
10024 // Get the base of this array section and walk up from there.
10025 const Expr *Base = OASE->getBase()->IgnoreParenImpCasts();
10026
10027 // We require length = 1 for all array sections except the right-most to
10028 // guarantee that the memory region is contiguous and has no holes in it.
10029 while (const auto *TempOASE = dyn_cast<OMPArraySectionExpr>(Base)) {
10030 Length = TempOASE->getLength();
10031 if (Length == nullptr) {
10032 // For array sections of the form [1:] or [:], we would need to analyze
10033 // the lower bound...
10034 if (OASE->getColonLoc().isValid())
10035 return false;
10036
10037 // This is an array subscript which has implicit length 1!
10038 ArraySizes.push_back(llvm::APSInt::get(1));
10039 } else {
10040 llvm::APSInt ConstantLengthValue;
10041 if (!Length->EvaluateAsInt(ConstantLengthValue, Context) ||
10042 ConstantLengthValue.getSExtValue() != 1)
10043 return false;
10044
10045 ArraySizes.push_back(ConstantLengthValue);
10046 }
10047 Base = TempOASE->getBase()->IgnoreParenImpCasts();
10048 }
10049
10050 // If we have a single element, we don't need to add the implicit lengths.
10051 if (!SingleElement) {
10052 while (const auto *TempASE = dyn_cast<ArraySubscriptExpr>(Base)) {
10053 // Has implicit length 1!
10054 ArraySizes.push_back(llvm::APSInt::get(1));
10055 Base = TempASE->getBase()->IgnoreParenImpCasts();
10056 }
10057 }
10058
10059 // This array section can be privatized as a single value or as a constant
10060 // sized array.
10061 return true;
10062}
10063
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010064static bool ActOnOMPReductionKindClause(
Alexey Bataev169d96a2017-07-18 20:17:46 +000010065 Sema &S, DSAStackTy *Stack, OpenMPClauseKind ClauseKind,
10066 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10067 SourceLocation ColonLoc, SourceLocation EndLoc,
10068 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010069 ArrayRef<Expr *> UnresolvedReductions, ReductionData &RD) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010070 auto DN = ReductionId.getName();
10071 auto OOK = DN.getCXXOverloadedOperator();
10072 BinaryOperatorKind BOK = BO_Comma;
10073
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010074 ASTContext &Context = S.Context;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010075 // OpenMP [2.14.3.6, reduction clause]
10076 // C
10077 // reduction-identifier is either an identifier or one of the following
10078 // operators: +, -, *, &, |, ^, && and ||
10079 // C++
10080 // reduction-identifier is either an id-expression or one of the following
10081 // operators: +, -, *, &, |, ^, && and ||
Alexey Bataevc5e02582014-06-16 07:08:35 +000010082 switch (OOK) {
10083 case OO_Plus:
10084 case OO_Minus:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010085 BOK = BO_Add;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010086 break;
10087 case OO_Star:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010088 BOK = BO_Mul;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010089 break;
10090 case OO_Amp:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010091 BOK = BO_And;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010092 break;
10093 case OO_Pipe:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010094 BOK = BO_Or;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010095 break;
10096 case OO_Caret:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010097 BOK = BO_Xor;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010098 break;
10099 case OO_AmpAmp:
10100 BOK = BO_LAnd;
10101 break;
10102 case OO_PipePipe:
10103 BOK = BO_LOr;
10104 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010105 case OO_New:
10106 case OO_Delete:
10107 case OO_Array_New:
10108 case OO_Array_Delete:
10109 case OO_Slash:
10110 case OO_Percent:
10111 case OO_Tilde:
10112 case OO_Exclaim:
10113 case OO_Equal:
10114 case OO_Less:
10115 case OO_Greater:
10116 case OO_LessEqual:
10117 case OO_GreaterEqual:
10118 case OO_PlusEqual:
10119 case OO_MinusEqual:
10120 case OO_StarEqual:
10121 case OO_SlashEqual:
10122 case OO_PercentEqual:
10123 case OO_CaretEqual:
10124 case OO_AmpEqual:
10125 case OO_PipeEqual:
10126 case OO_LessLess:
10127 case OO_GreaterGreater:
10128 case OO_LessLessEqual:
10129 case OO_GreaterGreaterEqual:
10130 case OO_EqualEqual:
10131 case OO_ExclaimEqual:
Richard Smithd30b23d2017-12-01 02:13:10 +000010132 case OO_Spaceship:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010133 case OO_PlusPlus:
10134 case OO_MinusMinus:
10135 case OO_Comma:
10136 case OO_ArrowStar:
10137 case OO_Arrow:
10138 case OO_Call:
10139 case OO_Subscript:
10140 case OO_Conditional:
Richard Smith9be594e2015-10-22 05:12:22 +000010141 case OO_Coawait:
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010142 case NUM_OVERLOADED_OPERATORS:
10143 llvm_unreachable("Unexpected reduction identifier");
10144 case OO_None:
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010145 if (auto *II = DN.getAsIdentifierInfo()) {
Alexey Bataevc5e02582014-06-16 07:08:35 +000010146 if (II->isStr("max"))
10147 BOK = BO_GT;
10148 else if (II->isStr("min"))
10149 BOK = BO_LT;
10150 }
10151 break;
10152 }
10153 SourceRange ReductionIdRange;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010154 if (ReductionIdScopeSpec.isValid())
Alexey Bataevc5e02582014-06-16 07:08:35 +000010155 ReductionIdRange.setBegin(ReductionIdScopeSpec.getBeginLoc());
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010156 else
10157 ReductionIdRange.setBegin(ReductionId.getBeginLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000010158 ReductionIdRange.setEnd(ReductionId.getEndLoc());
Alexey Bataevc5e02582014-06-16 07:08:35 +000010159
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010160 auto IR = UnresolvedReductions.begin(), ER = UnresolvedReductions.end();
10161 bool FirstIter = true;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010162 for (auto RefExpr : VarList) {
10163 assert(RefExpr && "nullptr expr in OpenMP reduction clause.");
Alexey Bataevc5e02582014-06-16 07:08:35 +000010164 // OpenMP [2.1, C/C++]
10165 // A list item is a variable or array section, subject to the restrictions
10166 // specified in Section 2.4 on page 42 and in each of the sections
10167 // describing clauses and directives for which a list appears.
10168 // OpenMP [2.14.3.3, Restrictions, p.1]
10169 // A variable that is part of another variable (as an array or
10170 // structure element) cannot appear in a private clause.
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010171 if (!FirstIter && IR != ER)
10172 ++IR;
10173 FirstIter = false;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010174 SourceLocation ELoc;
10175 SourceRange ERange;
10176 Expr *SimpleRefExpr = RefExpr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010177 auto Res = getPrivateItem(S, SimpleRefExpr, ELoc, ERange,
Alexey Bataev60da77e2016-02-29 05:54:20 +000010178 /*AllowArraySection=*/true);
10179 if (Res.second) {
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010180 // Try to find 'declare reduction' corresponding construct before using
10181 // builtin/overloaded operators.
10182 QualType Type = Context.DependentTy;
10183 CXXCastPath BasePath;
10184 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010185 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010186 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010187 Expr *ReductionOp = nullptr;
10188 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010189 (DeclareReductionRef.isUnset() ||
10190 isa<UnresolvedLookupExpr>(DeclareReductionRef.get())))
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010191 ReductionOp = DeclareReductionRef.get();
10192 // It will be analyzed later.
10193 RD.push(RefExpr, ReductionOp);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010194 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010195 ValueDecl *D = Res.first;
10196 if (!D)
10197 continue;
10198
Alexey Bataev88202be2017-07-27 13:20:36 +000010199 Expr *TaskgroupDescriptor = nullptr;
Alexey Bataeva1764212015-09-30 09:22:36 +000010200 QualType Type;
Alexey Bataev60da77e2016-02-29 05:54:20 +000010201 auto *ASE = dyn_cast<ArraySubscriptExpr>(RefExpr->IgnoreParens());
10202 auto *OASE = dyn_cast<OMPArraySectionExpr>(RefExpr->IgnoreParens());
10203 if (ASE)
Alexey Bataev31300ed2016-02-04 11:27:03 +000010204 Type = ASE->getType().getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010205 else if (OASE) {
Alexey Bataeva1764212015-09-30 09:22:36 +000010206 auto BaseType = OMPArraySectionExpr::getBaseOriginalType(OASE->getBase());
10207 if (auto *ATy = BaseType->getAsArrayTypeUnsafe())
10208 Type = ATy->getElementType();
10209 else
10210 Type = BaseType->getPointeeType();
Alexey Bataev31300ed2016-02-04 11:27:03 +000010211 Type = Type.getNonReferenceType();
Alexey Bataev60da77e2016-02-29 05:54:20 +000010212 } else
10213 Type = Context.getBaseElementType(D->getType().getNonReferenceType());
10214 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataeva1764212015-09-30 09:22:36 +000010215
Alexey Bataevc5e02582014-06-16 07:08:35 +000010216 // OpenMP [2.9.3.3, Restrictions, C/C++, p.3]
10217 // A variable that appears in a private clause must not have an incomplete
10218 // type or a reference type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010219 if (S.RequireCompleteType(ELoc, Type,
10220 diag::err_omp_reduction_incomplete_type))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010221 continue;
10222 // OpenMP [2.14.3.6, reduction clause, Restrictions]
Alexey Bataevc5e02582014-06-16 07:08:35 +000010223 // A list item that appears in a reduction clause must not be
10224 // const-qualified.
10225 if (Type.getNonReferenceType().isConstant(Context)) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010226 S.Diag(ELoc, diag::err_omp_const_reduction_list_item) << ERange;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010227 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010228 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10229 VarDecl::DeclarationOnly;
10230 S.Diag(D->getLocation(),
10231 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010232 << D;
Alexey Bataeva1764212015-09-30 09:22:36 +000010233 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010234 continue;
10235 }
10236 // OpenMP [2.9.3.6, Restrictions, C/C++, p.4]
10237 // If a list-item is a reference type then it must bind to the same object
10238 // for all threads of the team.
Alexey Bataev60da77e2016-02-29 05:54:20 +000010239 if (!ASE && !OASE && VD) {
Alexey Bataeva1764212015-09-30 09:22:36 +000010240 VarDecl *VDDef = VD->getDefinition();
David Sheinkman92589992016-10-04 14:41:36 +000010241 if (VD->getType()->isReferenceType() && VDDef && VDDef->hasInit()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010242 DSARefChecker Check(Stack);
Alexey Bataeva1764212015-09-30 09:22:36 +000010243 if (Check.Visit(VDDef->getInit())) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010244 S.Diag(ELoc, diag::err_omp_reduction_ref_type_arg)
10245 << getOpenMPClauseName(ClauseKind) << ERange;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010246 S.Diag(VDDef->getLocation(), diag::note_defined_here) << VDDef;
Alexey Bataeva1764212015-09-30 09:22:36 +000010247 continue;
10248 }
Alexey Bataevc5e02582014-06-16 07:08:35 +000010249 }
10250 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010251
Alexey Bataevc5e02582014-06-16 07:08:35 +000010252 // OpenMP [2.14.1.1, Data-sharing Attribute Rules for Variables Referenced
10253 // in a Construct]
10254 // Variables with the predetermined data-sharing attributes may not be
10255 // listed in data-sharing attributes clauses, except for the cases
10256 // listed below. For these exceptions only, listing a predetermined
10257 // variable in a data-sharing attribute clause is allowed and overrides
10258 // the variable's predetermined data-sharing attributes.
10259 // OpenMP [2.14.3.6, Restrictions, p.3]
10260 // Any number of reduction clauses can be specified on the directive,
10261 // but a list item can appear only once in the reduction clauses for that
10262 // directive.
Alexey Bataeva1764212015-09-30 09:22:36 +000010263 DSAStackTy::DSAVarData DVar;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010264 DVar = Stack->getTopDSA(D, false);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010265 if (DVar.CKind == OMPC_reduction) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010266 S.Diag(ELoc, diag::err_omp_once_referenced)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010267 << getOpenMPClauseName(ClauseKind);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010268 if (DVar.RefExpr)
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010269 S.Diag(DVar.RefExpr->getExprLoc(), diag::note_omp_referenced);
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010270 continue;
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010271 } else if (DVar.CKind != OMPC_unknown) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010272 S.Diag(ELoc, diag::err_omp_wrong_dsa)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010273 << getOpenMPClauseName(DVar.CKind)
10274 << getOpenMPClauseName(OMPC_reduction);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010275 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010276 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010277 }
10278
10279 // OpenMP [2.14.3.6, Restrictions, p.1]
10280 // A list item that appears in a reduction clause of a worksharing
10281 // construct must be shared in the parallel regions to which any of the
10282 // worksharing regions arising from the worksharing construct bind.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010283 OpenMPDirectiveKind CurrDir = Stack->getCurrentDirective();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010284 if (isOpenMPWorksharingDirective(CurrDir) &&
Kelvin Li579e41c2016-11-30 23:51:03 +000010285 !isOpenMPParallelDirective(CurrDir) &&
10286 !isOpenMPTeamsDirective(CurrDir)) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010287 DVar = Stack->getImplicitDSA(D, true);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010288 if (DVar.CKind != OMPC_shared) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010289 S.Diag(ELoc, diag::err_omp_required_access)
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010290 << getOpenMPClauseName(OMPC_reduction)
10291 << getOpenMPClauseName(OMPC_shared);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010292 ReportOriginalDSA(S, Stack, D, DVar);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010293 continue;
Alexey Bataevf29276e2014-06-18 04:14:57 +000010294 }
10295 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010296
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010297 // Try to find 'declare reduction' corresponding construct before using
10298 // builtin/overloaded operators.
10299 CXXCastPath BasePath;
10300 ExprResult DeclareReductionRef = buildDeclareReductionRef(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010301 S, ELoc, ERange, Stack->getCurScope(), ReductionIdScopeSpec,
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010302 ReductionId, Type, BasePath, IR == ER ? nullptr : *IR);
10303 if (DeclareReductionRef.isInvalid())
10304 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010305 if (S.CurContext->isDependentContext() &&
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010306 (DeclareReductionRef.isUnset() ||
10307 isa<UnresolvedLookupExpr>(DeclareReductionRef.get()))) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010308 RD.push(RefExpr, DeclareReductionRef.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010309 continue;
10310 }
10311 if (BOK == BO_Comma && DeclareReductionRef.isUnset()) {
10312 // Not allowed reduction identifier is found.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010313 S.Diag(ReductionId.getLocStart(),
10314 diag::err_omp_unknown_reduction_identifier)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010315 << Type << ReductionIdRange;
10316 continue;
10317 }
10318
10319 // OpenMP [2.14.3.6, reduction clause, Restrictions]
10320 // The type of a list item that appears in a reduction clause must be valid
10321 // for the reduction-identifier. For a max or min reduction in C, the type
10322 // of the list item must be an allowed arithmetic data type: char, int,
10323 // float, double, or _Bool, possibly modified with long, short, signed, or
10324 // unsigned. For a max or min reduction in C++, the type of the list item
10325 // must be an allowed arithmetic data type: char, wchar_t, int, float,
10326 // double, or bool, possibly modified with long, short, signed, or unsigned.
10327 if (DeclareReductionRef.isUnset()) {
10328 if ((BOK == BO_GT || BOK == BO_LT) &&
10329 !(Type->isScalarType() ||
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010330 (S.getLangOpts().CPlusPlus && Type->isArithmeticType()))) {
10331 S.Diag(ELoc, diag::err_omp_clause_not_arithmetic_type_arg)
Alexey Bataev169d96a2017-07-18 20:17:46 +000010332 << getOpenMPClauseName(ClauseKind) << S.getLangOpts().CPlusPlus;
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010333 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010334 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10335 VarDecl::DeclarationOnly;
10336 S.Diag(D->getLocation(),
10337 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010338 << D;
10339 }
10340 continue;
10341 }
10342 if ((BOK == BO_OrAssign || BOK == BO_AndAssign || BOK == BO_XorAssign) &&
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010343 !S.getLangOpts().CPlusPlus && Type->isFloatingType()) {
Alexey Bataev169d96a2017-07-18 20:17:46 +000010344 S.Diag(ELoc, diag::err_omp_clause_floating_type_arg)
10345 << getOpenMPClauseName(ClauseKind);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010346 if (!ASE && !OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010347 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10348 VarDecl::DeclarationOnly;
10349 S.Diag(D->getLocation(),
10350 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010351 << D;
10352 }
10353 continue;
10354 }
10355 }
10356
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010357 Type = Type.getNonLValueExprType(Context).getUnqualifiedType();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010358 auto *LHSVD = buildVarDecl(S, ELoc, Type, ".reduction.lhs",
Alexey Bataev60da77e2016-02-29 05:54:20 +000010359 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010360 auto *RHSVD = buildVarDecl(S, ELoc, Type, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010361 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010362 auto PrivateTy = Type;
Jonas Hahnfeld4525c822017-10-23 19:01:35 +000010363
10364 // Try if we can determine constant lengths for all array sections and avoid
10365 // the VLA.
10366 bool ConstantLengthOASE = false;
10367 if (OASE) {
10368 bool SingleElement;
10369 llvm::SmallVector<llvm::APSInt, 4> ArraySizes;
10370 ConstantLengthOASE = CheckOMPArraySectionConstantForReduction(
10371 Context, OASE, SingleElement, ArraySizes);
10372
10373 // If we don't have a single element, we must emit a constant array type.
10374 if (ConstantLengthOASE && !SingleElement) {
10375 for (auto &Size : ArraySizes) {
10376 PrivateTy = Context.getConstantArrayType(
10377 PrivateTy, Size, ArrayType::Normal, /*IndexTypeQuals=*/0);
10378 }
10379 }
10380 }
10381
10382 if ((OASE && !ConstantLengthOASE) ||
Jonas Hahnfeld96087f32017-11-02 13:30:42 +000010383 (!OASE && !ASE &&
Alexey Bataev60da77e2016-02-29 05:54:20 +000010384 D->getType().getNonReferenceType()->isVariablyModifiedType())) {
Jonas Hahnfeld87d44262017-11-18 21:00:46 +000010385 if (!Context.getTargetInfo().isVLASupported() &&
10386 S.shouldDiagnoseTargetSupportFromOpenMP()) {
10387 S.Diag(ELoc, diag::err_omp_reduction_vla_unsupported) << !!OASE;
10388 S.Diag(ELoc, diag::note_vla_unsupported);
10389 continue;
10390 }
David Majnemer9d168222016-08-05 17:44:54 +000010391 // For arrays/array sections only:
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010392 // Create pseudo array type for private copy. The size for this array will
10393 // be generated during codegen.
10394 // For array subscripts or single variables Private Ty is the same as Type
10395 // (type of the variable or single array element).
10396 PrivateTy = Context.getVariableArrayType(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010397 Type,
Alexey Bataevd070a582017-10-25 15:54:04 +000010398 new (Context) OpaqueValueExpr(ELoc, Context.getSizeType(), VK_RValue),
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010399 ArrayType::Normal, /*IndexTypeQuals=*/0, SourceRange());
Alexey Bataev60da77e2016-02-29 05:54:20 +000010400 } else if (!ASE && !OASE &&
10401 Context.getAsArrayType(D->getType().getNonReferenceType()))
10402 PrivateTy = D->getType().getNonReferenceType();
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010403 // Private copy.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010404 auto *PrivateVD = buildVarDecl(S, ELoc, PrivateTy, D->getName(),
Alexey Bataev60da77e2016-02-29 05:54:20 +000010405 D->hasAttrs() ? &D->getAttrs() : nullptr);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010406 // Add initializer for private variable.
10407 Expr *Init = nullptr;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010408 auto *LHSDRE = buildDeclRefExpr(S, LHSVD, Type, ELoc);
10409 auto *RHSDRE = buildDeclRefExpr(S, RHSVD, Type, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010410 if (DeclareReductionRef.isUsable()) {
10411 auto *DRDRef = DeclareReductionRef.getAs<DeclRefExpr>();
10412 auto *DRD = cast<OMPDeclareReductionDecl>(DRDRef->getDecl());
10413 if (DRD->getInitializer()) {
10414 Init = DRDRef;
10415 RHSVD->setInit(DRDRef);
10416 RHSVD->setInitStyle(VarDecl::CallInit);
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010417 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010418 } else {
10419 switch (BOK) {
10420 case BO_Add:
10421 case BO_Xor:
10422 case BO_Or:
10423 case BO_LOr:
10424 // '+', '-', '^', '|', '||' reduction ops - initializer is '0'.
10425 if (Type->isScalarType() || Type->isAnyComplexType())
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010426 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/0).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010427 break;
10428 case BO_Mul:
10429 case BO_LAnd:
10430 if (Type->isScalarType() || Type->isAnyComplexType()) {
10431 // '*' and '&&' reduction ops - initializer is '1'.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010432 Init = S.ActOnIntegerConstant(ELoc, /*Val=*/1).get();
Alexey Bataevc5e02582014-06-16 07:08:35 +000010433 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010434 break;
10435 case BO_And: {
10436 // '&' reduction op - initializer is '~0'.
10437 QualType OrigType = Type;
10438 if (auto *ComplexTy = OrigType->getAs<ComplexType>())
10439 Type = ComplexTy->getElementType();
10440 if (Type->isRealFloatingType()) {
10441 llvm::APFloat InitValue =
10442 llvm::APFloat::getAllOnesValue(Context.getTypeSize(Type),
10443 /*isIEEE=*/true);
10444 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10445 Type, ELoc);
10446 } else if (Type->isScalarType()) {
10447 auto Size = Context.getTypeSize(Type);
10448 QualType IntTy = Context.getIntTypeForBitwidth(Size, /*Signed=*/0);
10449 llvm::APInt InitValue = llvm::APInt::getAllOnesValue(Size);
10450 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10451 }
10452 if (Init && OrigType->isAnyComplexType()) {
10453 // Init = 0xFFFF + 0xFFFFi;
10454 auto *Im = new (Context) ImaginaryLiteral(Init, OrigType);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010455 Init = S.CreateBuiltinBinOp(ELoc, BO_Add, Init, Im).get();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010456 }
10457 Type = OrigType;
10458 break;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010459 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010460 case BO_LT:
10461 case BO_GT: {
10462 // 'min' reduction op - initializer is 'Largest representable number in
10463 // the reduction list item type'.
10464 // 'max' reduction op - initializer is 'Least representable number in
10465 // the reduction list item type'.
10466 if (Type->isIntegerType() || Type->isPointerType()) {
10467 bool IsSigned = Type->hasSignedIntegerRepresentation();
10468 auto Size = Context.getTypeSize(Type);
10469 QualType IntTy =
10470 Context.getIntTypeForBitwidth(Size, /*Signed=*/IsSigned);
10471 llvm::APInt InitValue =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010472 (BOK != BO_LT) ? IsSigned ? llvm::APInt::getSignedMinValue(Size)
10473 : llvm::APInt::getMinValue(Size)
10474 : IsSigned ? llvm::APInt::getSignedMaxValue(Size)
10475 : llvm::APInt::getMaxValue(Size);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010476 Init = IntegerLiteral::Create(Context, InitValue, IntTy, ELoc);
10477 if (Type->isPointerType()) {
10478 // Cast to pointer type.
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010479 auto CastExpr = S.BuildCStyleCastExpr(
Alexey Bataevd070a582017-10-25 15:54:04 +000010480 ELoc, Context.getTrivialTypeSourceInfo(Type, ELoc), ELoc, Init);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010481 if (CastExpr.isInvalid())
10482 continue;
10483 Init = CastExpr.get();
10484 }
10485 } else if (Type->isRealFloatingType()) {
10486 llvm::APFloat InitValue = llvm::APFloat::getLargest(
10487 Context.getFloatTypeSemantics(Type), BOK != BO_LT);
10488 Init = FloatingLiteral::Create(Context, InitValue, /*isexact=*/true,
10489 Type, ELoc);
10490 }
10491 break;
10492 }
10493 case BO_PtrMemD:
10494 case BO_PtrMemI:
10495 case BO_MulAssign:
10496 case BO_Div:
10497 case BO_Rem:
10498 case BO_Sub:
10499 case BO_Shl:
10500 case BO_Shr:
10501 case BO_LE:
10502 case BO_GE:
10503 case BO_EQ:
10504 case BO_NE:
Richard Smithc70f1d62017-12-14 15:16:18 +000010505 case BO_Cmp:
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010506 case BO_AndAssign:
10507 case BO_XorAssign:
10508 case BO_OrAssign:
10509 case BO_Assign:
10510 case BO_AddAssign:
10511 case BO_SubAssign:
10512 case BO_DivAssign:
10513 case BO_RemAssign:
10514 case BO_ShlAssign:
10515 case BO_ShrAssign:
10516 case BO_Comma:
10517 llvm_unreachable("Unexpected reduction operation");
10518 }
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010519 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010520 if (Init && DeclareReductionRef.isUnset())
10521 S.AddInitializerToDecl(RHSVD, Init, /*DirectInit=*/false);
10522 else if (!Init)
10523 S.ActOnUninitializedDecl(RHSVD);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010524 if (RHSVD->isInvalidDecl())
10525 continue;
10526 if (!RHSVD->hasInit() && DeclareReductionRef.isUnset()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010527 S.Diag(ELoc, diag::err_omp_reduction_id_not_compatible)
10528 << Type << ReductionIdRange;
10529 bool IsDecl = !VD || VD->isThisDeclarationADefinition(Context) ==
10530 VarDecl::DeclarationOnly;
10531 S.Diag(D->getLocation(),
10532 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev60da77e2016-02-29 05:54:20 +000010533 << D;
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010534 continue;
10535 }
Alexey Bataevf24e7b12015-10-08 09:10:53 +000010536 // Store initializer for single element in private copy. Will be used during
10537 // codegen.
10538 PrivateVD->setInit(RHSVD->getInit());
10539 PrivateVD->setInitStyle(RHSVD->getInitStyle());
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010540 auto *PrivateDRE = buildDeclRefExpr(S, PrivateVD, PrivateTy, ELoc);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010541 ExprResult ReductionOp;
10542 if (DeclareReductionRef.isUsable()) {
10543 QualType RedTy = DeclareReductionRef.get()->getType();
10544 QualType PtrRedTy = Context.getPointerType(RedTy);
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010545 ExprResult LHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, LHSDRE);
10546 ExprResult RHS = S.CreateBuiltinUnaryOp(ELoc, UO_AddrOf, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010547 if (!BasePath.empty()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010548 LHS = S.DefaultLvalueConversion(LHS.get());
10549 RHS = S.DefaultLvalueConversion(RHS.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010550 LHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10551 CK_UncheckedDerivedToBase, LHS.get(),
10552 &BasePath, LHS.get()->getValueKind());
10553 RHS = ImplicitCastExpr::Create(Context, PtrRedTy,
10554 CK_UncheckedDerivedToBase, RHS.get(),
10555 &BasePath, RHS.get()->getValueKind());
Alexey Bataev794ba0d2015-04-10 10:43:45 +000010556 }
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010557 FunctionProtoType::ExtProtoInfo EPI;
10558 QualType Params[] = {PtrRedTy, PtrRedTy};
10559 QualType FnTy = Context.getFunctionType(Context.VoidTy, Params, EPI);
10560 auto *OVE = new (Context) OpaqueValueExpr(
10561 ELoc, Context.getPointerType(FnTy), VK_RValue, OK_Ordinary,
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010562 S.DefaultLvalueConversion(DeclareReductionRef.get()).get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010563 Expr *Args[] = {LHS.get(), RHS.get()};
10564 ReductionOp = new (Context)
10565 CallExpr(Context, OVE, Args, Context.VoidTy, VK_RValue, ELoc);
10566 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010567 ReductionOp = S.BuildBinOp(
10568 Stack->getCurScope(), ReductionId.getLocStart(), BOK, LHSDRE, RHSDRE);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010569 if (ReductionOp.isUsable()) {
10570 if (BOK != BO_LT && BOK != BO_GT) {
10571 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010572 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10573 BO_Assign, LHSDRE, ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010574 } else {
Alexey Bataevd070a582017-10-25 15:54:04 +000010575 auto *ConditionalOp = new (Context)
10576 ConditionalOperator(ReductionOp.get(), ELoc, LHSDRE, ELoc, RHSDRE,
10577 Type, VK_LValue, OK_Ordinary);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010578 ReductionOp =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010579 S.BuildBinOp(Stack->getCurScope(), ReductionId.getLocStart(),
10580 BO_Assign, LHSDRE, ConditionalOp);
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010581 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010582 if (ReductionOp.isUsable())
10583 ReductionOp = S.ActOnFinishFullExpr(ReductionOp.get());
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010584 }
Alexey Bataev4d4624c2017-07-20 16:47:47 +000010585 if (!ReductionOp.isUsable())
Alexey Bataeva839ddd2016-03-17 10:19:46 +000010586 continue;
Alexey Bataevc5e02582014-06-16 07:08:35 +000010587 }
10588
Alexey Bataevfa312f32017-07-21 18:48:21 +000010589 // OpenMP [2.15.4.6, Restrictions, p.2]
10590 // A list item that appears in an in_reduction clause of a task construct
10591 // must appear in a task_reduction clause of a construct associated with a
10592 // taskgroup region that includes the participating task in its taskgroup
10593 // set. The construct associated with the innermost region that meets this
10594 // condition must specify the same reduction-identifier as the in_reduction
10595 // clause.
10596 if (ClauseKind == OMPC_in_reduction) {
Alexey Bataevfa312f32017-07-21 18:48:21 +000010597 SourceRange ParentSR;
10598 BinaryOperatorKind ParentBOK;
10599 const Expr *ParentReductionOp;
Alexey Bataev88202be2017-07-27 13:20:36 +000010600 Expr *ParentBOKTD, *ParentReductionOpTD;
Alexey Bataevf189cb72017-07-24 14:52:13 +000010601 DSAStackTy::DSAVarData ParentBOKDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010602 Stack->getTopMostTaskgroupReductionData(D, ParentSR, ParentBOK,
10603 ParentBOKTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010604 DSAStackTy::DSAVarData ParentReductionOpDSA =
Alexey Bataev88202be2017-07-27 13:20:36 +000010605 Stack->getTopMostTaskgroupReductionData(
10606 D, ParentSR, ParentReductionOp, ParentReductionOpTD);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010607 bool IsParentBOK = ParentBOKDSA.DKind != OMPD_unknown;
10608 bool IsParentReductionOp = ParentReductionOpDSA.DKind != OMPD_unknown;
10609 if (!IsParentBOK && !IsParentReductionOp) {
10610 S.Diag(ELoc, diag::err_omp_in_reduction_not_task_reduction);
10611 continue;
10612 }
Alexey Bataevfa312f32017-07-21 18:48:21 +000010613 if ((DeclareReductionRef.isUnset() && IsParentReductionOp) ||
10614 (DeclareReductionRef.isUsable() && IsParentBOK) || BOK != ParentBOK ||
10615 IsParentReductionOp) {
10616 bool EmitError = true;
10617 if (IsParentReductionOp && DeclareReductionRef.isUsable()) {
10618 llvm::FoldingSetNodeID RedId, ParentRedId;
10619 ParentReductionOp->Profile(ParentRedId, Context, /*Canonical=*/true);
10620 DeclareReductionRef.get()->Profile(RedId, Context,
10621 /*Canonical=*/true);
10622 EmitError = RedId != ParentRedId;
10623 }
10624 if (EmitError) {
10625 S.Diag(ReductionId.getLocStart(),
10626 diag::err_omp_reduction_identifier_mismatch)
10627 << ReductionIdRange << RefExpr->getSourceRange();
10628 S.Diag(ParentSR.getBegin(),
10629 diag::note_omp_previous_reduction_identifier)
Alexey Bataevf189cb72017-07-24 14:52:13 +000010630 << ParentSR
10631 << (IsParentBOK ? ParentBOKDSA.RefExpr
10632 : ParentReductionOpDSA.RefExpr)
10633 ->getSourceRange();
Alexey Bataevfa312f32017-07-21 18:48:21 +000010634 continue;
10635 }
10636 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010637 TaskgroupDescriptor = IsParentBOK ? ParentBOKTD : ParentReductionOpTD;
10638 assert(TaskgroupDescriptor && "Taskgroup descriptor must be defined.");
Alexey Bataevfa312f32017-07-21 18:48:21 +000010639 }
10640
Alexey Bataev60da77e2016-02-29 05:54:20 +000010641 DeclRefExpr *Ref = nullptr;
10642 Expr *VarsExpr = RefExpr->IgnoreParens();
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010643 if (!VD && !S.CurContext->isDependentContext()) {
Alexey Bataev60da77e2016-02-29 05:54:20 +000010644 if (ASE || OASE) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010645 TransformExprToCaptures RebuildToCapture(S, D);
Alexey Bataev60da77e2016-02-29 05:54:20 +000010646 VarsExpr =
10647 RebuildToCapture.TransformExpr(RefExpr->IgnoreParens()).get();
10648 Ref = RebuildToCapture.getCapturedExpr();
Alexey Bataev61205072016-03-02 04:57:40 +000010649 } else {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010650 VarsExpr = Ref = buildCapture(S, D, SimpleRefExpr, /*WithInit=*/false);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010651 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010652 if (!S.IsOpenMPCapturedDecl(D)) {
10653 RD.ExprCaptures.emplace_back(Ref->getDecl());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010654 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010655 ExprResult RefRes = S.DefaultLvalueConversion(Ref);
Alexey Bataev5a3af132016-03-29 08:58:54 +000010656 if (!RefRes.isUsable())
10657 continue;
10658 ExprResult PostUpdateRes =
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010659 S.BuildBinOp(Stack->getCurScope(), ELoc, BO_Assign, SimpleRefExpr,
10660 RefRes.get());
Alexey Bataev5a3af132016-03-29 08:58:54 +000010661 if (!PostUpdateRes.isUsable())
10662 continue;
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010663 if (isOpenMPTaskingDirective(Stack->getCurrentDirective()) ||
10664 Stack->getCurrentDirective() == OMPD_taskgroup) {
10665 S.Diag(RefExpr->getExprLoc(),
10666 diag::err_omp_reduction_non_addressable_expression)
Alexey Bataevbcd0ae02017-07-11 19:16:44 +000010667 << RefExpr->getSourceRange();
10668 continue;
10669 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010670 RD.ExprPostUpdates.emplace_back(
10671 S.IgnoredValueConversions(PostUpdateRes.get()).get());
Alexey Bataev61205072016-03-02 04:57:40 +000010672 }
10673 }
Alexey Bataev60da77e2016-02-29 05:54:20 +000010674 }
Alexey Bataev169d96a2017-07-18 20:17:46 +000010675 // All reduction items are still marked as reduction (to do not increase
10676 // code base size).
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010677 Stack->addDSA(D, RefExpr->IgnoreParens(), OMPC_reduction, Ref);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010678 if (CurrDir == OMPD_taskgroup) {
10679 if (DeclareReductionRef.isUsable())
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010680 Stack->addTaskgroupReductionData(D, ReductionIdRange,
10681 DeclareReductionRef.get());
Alexey Bataevf189cb72017-07-24 14:52:13 +000010682 else
Alexey Bataev3b1b8952017-07-25 15:53:26 +000010683 Stack->addTaskgroupReductionData(D, ReductionIdRange, BOK);
Alexey Bataevf189cb72017-07-24 14:52:13 +000010684 }
Alexey Bataev88202be2017-07-27 13:20:36 +000010685 RD.push(VarsExpr, PrivateDRE, LHSDRE, RHSDRE, ReductionOp.get(),
10686 TaskgroupDescriptor);
Alexey Bataevc5e02582014-06-16 07:08:35 +000010687 }
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010688 return RD.Vars.empty();
10689}
Alexey Bataevc5e02582014-06-16 07:08:35 +000010690
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010691OMPClause *Sema::ActOnOpenMPReductionClause(
10692 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10693 SourceLocation ColonLoc, SourceLocation EndLoc,
10694 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10695 ArrayRef<Expr *> UnresolvedReductions) {
10696 ReductionData RD(VarList.size());
10697
Alexey Bataev169d96a2017-07-18 20:17:46 +000010698 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_reduction, VarList,
10699 StartLoc, LParenLoc, ColonLoc, EndLoc,
10700 ReductionIdScopeSpec, ReductionId,
10701 UnresolvedReductions, RD))
Alexey Bataevc5e02582014-06-16 07:08:35 +000010702 return nullptr;
Alexey Bataev61205072016-03-02 04:57:40 +000010703
Alexey Bataevc5e02582014-06-16 07:08:35 +000010704 return OMPReductionClause::Create(
Alexey Bataevfad872fc2017-07-18 15:32:58 +000010705 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10706 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10707 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10708 buildPreInits(Context, RD.ExprCaptures),
10709 buildPostUpdate(*this, RD.ExprPostUpdates));
Alexey Bataevc5e02582014-06-16 07:08:35 +000010710}
10711
Alexey Bataev169d96a2017-07-18 20:17:46 +000010712OMPClause *Sema::ActOnOpenMPTaskReductionClause(
10713 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10714 SourceLocation ColonLoc, SourceLocation EndLoc,
10715 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10716 ArrayRef<Expr *> UnresolvedReductions) {
10717 ReductionData RD(VarList.size());
10718
10719 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_task_reduction,
10720 VarList, StartLoc, LParenLoc, ColonLoc,
10721 EndLoc, ReductionIdScopeSpec, ReductionId,
10722 UnresolvedReductions, RD))
10723 return nullptr;
10724
10725 return OMPTaskReductionClause::Create(
10726 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10727 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
10728 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps,
10729 buildPreInits(Context, RD.ExprCaptures),
10730 buildPostUpdate(*this, RD.ExprPostUpdates));
10731}
10732
Alexey Bataevfa312f32017-07-21 18:48:21 +000010733OMPClause *Sema::ActOnOpenMPInReductionClause(
10734 ArrayRef<Expr *> VarList, SourceLocation StartLoc, SourceLocation LParenLoc,
10735 SourceLocation ColonLoc, SourceLocation EndLoc,
10736 CXXScopeSpec &ReductionIdScopeSpec, const DeclarationNameInfo &ReductionId,
10737 ArrayRef<Expr *> UnresolvedReductions) {
10738 ReductionData RD(VarList.size());
10739
10740 if (ActOnOMPReductionKindClause(*this, DSAStack, OMPC_in_reduction, VarList,
10741 StartLoc, LParenLoc, ColonLoc, EndLoc,
10742 ReductionIdScopeSpec, ReductionId,
10743 UnresolvedReductions, RD))
10744 return nullptr;
10745
10746 return OMPInReductionClause::Create(
10747 Context, StartLoc, LParenLoc, ColonLoc, EndLoc, RD.Vars,
10748 ReductionIdScopeSpec.getWithLocInContext(Context), ReductionId,
Alexey Bataev88202be2017-07-27 13:20:36 +000010749 RD.Privates, RD.LHSs, RD.RHSs, RD.ReductionOps, RD.TaskgroupDescriptors,
Alexey Bataevfa312f32017-07-21 18:48:21 +000010750 buildPreInits(Context, RD.ExprCaptures),
10751 buildPostUpdate(*this, RD.ExprPostUpdates));
10752}
10753
Alexey Bataevecba70f2016-04-12 11:02:11 +000010754bool Sema::CheckOpenMPLinearModifier(OpenMPLinearClauseKind LinKind,
10755 SourceLocation LinLoc) {
10756 if ((!LangOpts.CPlusPlus && LinKind != OMPC_LINEAR_val) ||
10757 LinKind == OMPC_LINEAR_unknown) {
10758 Diag(LinLoc, diag::err_omp_wrong_linear_modifier) << LangOpts.CPlusPlus;
10759 return true;
10760 }
10761 return false;
10762}
10763
10764bool Sema::CheckOpenMPLinearDecl(ValueDecl *D, SourceLocation ELoc,
10765 OpenMPLinearClauseKind LinKind,
10766 QualType Type) {
10767 auto *VD = dyn_cast_or_null<VarDecl>(D);
10768 // A variable must not have an incomplete type or a reference type.
10769 if (RequireCompleteType(ELoc, Type, diag::err_omp_linear_incomplete_type))
10770 return true;
10771 if ((LinKind == OMPC_LINEAR_uval || LinKind == OMPC_LINEAR_ref) &&
10772 !Type->isReferenceType()) {
10773 Diag(ELoc, diag::err_omp_wrong_linear_modifier_non_reference)
10774 << Type << getOpenMPSimpleClauseTypeName(OMPC_linear, LinKind);
10775 return true;
10776 }
10777 Type = Type.getNonReferenceType();
10778
10779 // A list item must not be const-qualified.
10780 if (Type.isConstant(Context)) {
10781 Diag(ELoc, diag::err_omp_const_variable)
10782 << getOpenMPClauseName(OMPC_linear);
10783 if (D) {
10784 bool IsDecl =
10785 !VD ||
10786 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10787 Diag(D->getLocation(),
10788 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10789 << D;
10790 }
10791 return true;
10792 }
10793
10794 // A list item must be of integral or pointer type.
10795 Type = Type.getUnqualifiedType().getCanonicalType();
10796 const auto *Ty = Type.getTypePtrOrNull();
10797 if (!Ty || (!Ty->isDependentType() && !Ty->isIntegralType(Context) &&
10798 !Ty->isPointerType())) {
10799 Diag(ELoc, diag::err_omp_linear_expected_int_or_ptr) << Type;
10800 if (D) {
10801 bool IsDecl =
10802 !VD ||
10803 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
10804 Diag(D->getLocation(),
10805 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
10806 << D;
10807 }
10808 return true;
10809 }
10810 return false;
10811}
10812
Alexey Bataev182227b2015-08-20 10:54:39 +000010813OMPClause *Sema::ActOnOpenMPLinearClause(
10814 ArrayRef<Expr *> VarList, Expr *Step, SourceLocation StartLoc,
10815 SourceLocation LParenLoc, OpenMPLinearClauseKind LinKind,
10816 SourceLocation LinLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010817 SmallVector<Expr *, 8> Vars;
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010818 SmallVector<Expr *, 8> Privates;
Alexander Musman3276a272015-03-21 10:12:56 +000010819 SmallVector<Expr *, 8> Inits;
Alexey Bataev78849fb2016-03-09 09:49:00 +000010820 SmallVector<Decl *, 4> ExprCaptures;
10821 SmallVector<Expr *, 4> ExprPostUpdates;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010822 if (CheckOpenMPLinearModifier(LinKind, LinLoc))
Alexey Bataev182227b2015-08-20 10:54:39 +000010823 LinKind = OMPC_LINEAR_val;
Alexey Bataeved09d242014-05-28 05:53:51 +000010824 for (auto &RefExpr : VarList) {
10825 assert(RefExpr && "NULL expr in OpenMP linear clause.");
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010826 SourceLocation ELoc;
10827 SourceRange ERange;
10828 Expr *SimpleRefExpr = RefExpr;
10829 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
10830 /*AllowArraySection=*/false);
10831 if (Res.second) {
Alexander Musman8dba6642014-04-22 13:09:42 +000010832 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000010833 Vars.push_back(RefExpr);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010834 Privates.push_back(nullptr);
Alexander Musman3276a272015-03-21 10:12:56 +000010835 Inits.push_back(nullptr);
Alexander Musman8dba6642014-04-22 13:09:42 +000010836 }
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010837 ValueDecl *D = Res.first;
10838 if (!D)
Alexander Musman8dba6642014-04-22 13:09:42 +000010839 continue;
Alexander Musman8dba6642014-04-22 13:09:42 +000010840
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010841 QualType Type = D->getType();
10842 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musman8dba6642014-04-22 13:09:42 +000010843
10844 // OpenMP [2.14.3.7, linear clause]
10845 // A list-item cannot appear in more than one linear clause.
10846 // A list-item that appears in a linear clause cannot appear in any
10847 // other data-sharing attribute clause.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010848 DSAStackTy::DSAVarData DVar = DSAStack->getTopDSA(D, false);
Alexander Musman8dba6642014-04-22 13:09:42 +000010849 if (DVar.RefExpr) {
10850 Diag(ELoc, diag::err_omp_wrong_dsa) << getOpenMPClauseName(DVar.CKind)
10851 << getOpenMPClauseName(OMPC_linear);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010852 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexander Musman8dba6642014-04-22 13:09:42 +000010853 continue;
10854 }
10855
Alexey Bataevecba70f2016-04-12 11:02:11 +000010856 if (CheckOpenMPLinearDecl(D, ELoc, LinKind, Type))
Alexander Musman8dba6642014-04-22 13:09:42 +000010857 continue;
Alexey Bataevecba70f2016-04-12 11:02:11 +000010858 Type = Type.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musman8dba6642014-04-22 13:09:42 +000010859
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010860 // Build private copy of original var.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010861 auto *Private = buildVarDecl(*this, ELoc, Type, D->getName(),
10862 D->hasAttrs() ? &D->getAttrs() : nullptr);
10863 auto *PrivateRef = buildDeclRefExpr(*this, Private, Type, ELoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010864 // Build var to save initial value.
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010865 VarDecl *Init = buildVarDecl(*this, ELoc, Type, ".linear.start");
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010866 Expr *InitExpr;
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010867 DeclRefExpr *Ref = nullptr;
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010868 if (!VD && !CurContext->isDependentContext()) {
Alexey Bataev78849fb2016-03-09 09:49:00 +000010869 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false);
10870 if (!IsOpenMPCapturedDecl(D)) {
10871 ExprCaptures.push_back(Ref->getDecl());
10872 if (Ref->getDecl()->hasAttr<OMPCaptureNoInitAttr>()) {
10873 ExprResult RefRes = DefaultLvalueConversion(Ref);
10874 if (!RefRes.isUsable())
10875 continue;
10876 ExprResult PostUpdateRes =
10877 BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
10878 SimpleRefExpr, RefRes.get());
10879 if (!PostUpdateRes.isUsable())
10880 continue;
10881 ExprPostUpdates.push_back(
10882 IgnoredValueConversions(PostUpdateRes.get()).get());
10883 }
10884 }
10885 }
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010886 if (LinKind == OMPC_LINEAR_uval)
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010887 InitExpr = VD ? VD->getInit() : SimpleRefExpr;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010888 else
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010889 InitExpr = VD ? SimpleRefExpr : Ref;
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010890 AddInitializerToDecl(Init, DefaultLvalueConversion(InitExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000010891 /*DirectInit=*/false);
Alexey Bataev2bbf7212016-03-03 03:52:24 +000010892 auto InitRef = buildDeclRefExpr(*this, Init, Type, ELoc);
10893
10894 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_linear, Ref);
Alexey Bataevbe8b8b52016-07-07 11:04:06 +000010895 Vars.push_back((VD || CurContext->isDependentContext())
10896 ? RefExpr->IgnoreParens()
10897 : Ref);
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010898 Privates.push_back(PrivateRef);
Alexander Musman3276a272015-03-21 10:12:56 +000010899 Inits.push_back(InitRef);
Alexander Musman8dba6642014-04-22 13:09:42 +000010900 }
10901
10902 if (Vars.empty())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010903 return nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010904
10905 Expr *StepExpr = Step;
Alexander Musman3276a272015-03-21 10:12:56 +000010906 Expr *CalcStepExpr = nullptr;
Alexander Musman8dba6642014-04-22 13:09:42 +000010907 if (Step && !Step->isValueDependent() && !Step->isTypeDependent() &&
10908 !Step->isInstantiationDependent() &&
10909 !Step->containsUnexpandedParameterPack()) {
10910 SourceLocation StepLoc = Step->getLocStart();
Alexander Musmana8e9d2e2014-06-03 10:16:47 +000010911 ExprResult Val = PerformOpenMPImplicitIntegerConversion(StepLoc, Step);
Alexander Musman8dba6642014-04-22 13:09:42 +000010912 if (Val.isInvalid())
Alexander Musmancb7f9c42014-05-15 13:04:49 +000010913 return nullptr;
Nikola Smiljanic01a75982014-05-29 10:55:11 +000010914 StepExpr = Val.get();
Alexander Musman8dba6642014-04-22 13:09:42 +000010915
Alexander Musman3276a272015-03-21 10:12:56 +000010916 // Build var to save the step value.
10917 VarDecl *SaveVar =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010918 buildVarDecl(*this, StepLoc, StepExpr->getType(), ".linear.step");
Alexander Musman3276a272015-03-21 10:12:56 +000010919 ExprResult SaveRef =
Alexey Bataev39f915b82015-05-08 10:41:21 +000010920 buildDeclRefExpr(*this, SaveVar, StepExpr->getType(), StepLoc);
Alexander Musman3276a272015-03-21 10:12:56 +000010921 ExprResult CalcStep =
10922 BuildBinOp(CurScope, StepLoc, BO_Assign, SaveRef.get(), StepExpr);
Alexey Bataev6b8046a2015-09-03 07:23:48 +000010923 CalcStep = ActOnFinishFullExpr(CalcStep.get());
Alexander Musman3276a272015-03-21 10:12:56 +000010924
Alexander Musman8dba6642014-04-22 13:09:42 +000010925 // Warn about zero linear step (it would be probably better specified as
10926 // making corresponding variables 'const').
10927 llvm::APSInt Result;
Alexander Musman3276a272015-03-21 10:12:56 +000010928 bool IsConstant = StepExpr->isIntegerConstantExpr(Result, Context);
10929 if (IsConstant && !Result.isNegative() && !Result.isStrictlyPositive())
Alexander Musman8dba6642014-04-22 13:09:42 +000010930 Diag(StepLoc, diag::warn_omp_linear_step_zero) << Vars[0]
10931 << (Vars.size() > 1);
Alexander Musman3276a272015-03-21 10:12:56 +000010932 if (!IsConstant && CalcStep.isUsable()) {
10933 // Calculate the step beforehand instead of doing this on each iteration.
10934 // (This is not used if the number of iterations may be kfold-ed).
10935 CalcStepExpr = CalcStep.get();
10936 }
Alexander Musman8dba6642014-04-22 13:09:42 +000010937 }
10938
Alexey Bataev182227b2015-08-20 10:54:39 +000010939 return OMPLinearClause::Create(Context, StartLoc, LParenLoc, LinKind, LinLoc,
10940 ColonLoc, EndLoc, Vars, Privates, Inits,
Alexey Bataev5a3af132016-03-29 08:58:54 +000010941 StepExpr, CalcStepExpr,
10942 buildPreInits(Context, ExprCaptures),
10943 buildPostUpdate(*this, ExprPostUpdates));
Alexander Musman3276a272015-03-21 10:12:56 +000010944}
10945
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010946static bool FinishOpenMPLinearClause(OMPLinearClause &Clause, DeclRefExpr *IV,
10947 Expr *NumIterations, Sema &SemaRef,
10948 Scope *S, DSAStackTy *Stack) {
Alexander Musman3276a272015-03-21 10:12:56 +000010949 // Walk the vars and build update/final expressions for the CodeGen.
10950 SmallVector<Expr *, 8> Updates;
10951 SmallVector<Expr *, 8> Finals;
10952 Expr *Step = Clause.getStep();
10953 Expr *CalcStep = Clause.getCalcStep();
10954 // OpenMP [2.14.3.7, linear clause]
10955 // If linear-step is not specified it is assumed to be 1.
10956 if (Step == nullptr)
10957 Step = SemaRef.ActOnIntegerConstant(SourceLocation(), 1).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010958 else if (CalcStep) {
Alexander Musman3276a272015-03-21 10:12:56 +000010959 Step = cast<BinaryOperator>(CalcStep)->getLHS();
Alexey Bataev5a3af132016-03-29 08:58:54 +000010960 }
Alexander Musman3276a272015-03-21 10:12:56 +000010961 bool HasErrors = false;
10962 auto CurInit = Clause.inits().begin();
Alexey Bataevbd9fec12015-08-18 06:47:21 +000010963 auto CurPrivate = Clause.privates().begin();
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010964 auto LinKind = Clause.getModifier();
Alexander Musman3276a272015-03-21 10:12:56 +000010965 for (auto &RefExpr : Clause.varlists()) {
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010966 SourceLocation ELoc;
10967 SourceRange ERange;
10968 Expr *SimpleRefExpr = RefExpr;
10969 auto Res = getPrivateItem(SemaRef, SimpleRefExpr, ELoc, ERange,
10970 /*AllowArraySection=*/false);
10971 ValueDecl *D = Res.first;
10972 if (Res.second || !D) {
10973 Updates.push_back(nullptr);
10974 Finals.push_back(nullptr);
10975 HasErrors = true;
10976 continue;
10977 }
Alexey Bataev5dff95c2016-04-22 03:56:56 +000010978 auto &&Info = Stack->isLoopControlVariable(D);
Alexey Bataev2b86f212017-11-29 21:31:48 +000010979 // OpenMP [2.15.11, distribute simd Construct]
10980 // A list item may not appear in a linear clause, unless it is the loop
10981 // iteration variable.
10982 if (isOpenMPDistributeDirective(Stack->getCurrentDirective()) &&
10983 isOpenMPSimdDirective(Stack->getCurrentDirective()) && !Info.first) {
10984 SemaRef.Diag(ELoc,
10985 diag::err_omp_linear_distribute_var_non_loop_iteration);
10986 Updates.push_back(nullptr);
10987 Finals.push_back(nullptr);
10988 HasErrors = true;
10989 continue;
10990 }
Alexander Musman3276a272015-03-21 10:12:56 +000010991 Expr *InitExpr = *CurInit;
10992
10993 // Build privatized reference to the current linear var.
David Majnemer9d168222016-08-05 17:44:54 +000010994 auto *DE = cast<DeclRefExpr>(SimpleRefExpr);
Alexey Bataev84cfb1d2015-08-21 06:41:23 +000010995 Expr *CapturedRef;
10996 if (LinKind == OMPC_LINEAR_uval)
10997 CapturedRef = cast<VarDecl>(DE->getDecl())->getInit();
10998 else
10999 CapturedRef =
11000 buildDeclRefExpr(SemaRef, cast<VarDecl>(DE->getDecl()),
11001 DE->getType().getUnqualifiedType(), DE->getExprLoc(),
11002 /*RefersToCapture=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011003
11004 // Build update: Var = InitExpr + IV * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011005 ExprResult Update;
11006 if (!Info.first) {
11007 Update =
11008 BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), *CurPrivate,
11009 InitExpr, IV, Step, /* Subtract */ false);
11010 } else
11011 Update = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011012 Update = SemaRef.ActOnFinishFullExpr(Update.get(), DE->getLocStart(),
11013 /*DiscardedValue=*/true);
Alexander Musman3276a272015-03-21 10:12:56 +000011014
11015 // Build final: Var = InitExpr + NumIterations * Step
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011016 ExprResult Final;
11017 if (!Info.first) {
11018 Final = BuildCounterUpdate(SemaRef, S, RefExpr->getExprLoc(), CapturedRef,
11019 InitExpr, NumIterations, Step,
11020 /* Subtract */ false);
11021 } else
11022 Final = *CurPrivate;
Alexey Bataev6b8046a2015-09-03 07:23:48 +000011023 Final = SemaRef.ActOnFinishFullExpr(Final.get(), DE->getLocStart(),
11024 /*DiscardedValue=*/true);
Alexey Bataev5dff95c2016-04-22 03:56:56 +000011025
Alexander Musman3276a272015-03-21 10:12:56 +000011026 if (!Update.isUsable() || !Final.isUsable()) {
11027 Updates.push_back(nullptr);
11028 Finals.push_back(nullptr);
11029 HasErrors = true;
11030 } else {
11031 Updates.push_back(Update.get());
11032 Finals.push_back(Final.get());
11033 }
Richard Trieucc3949d2016-02-18 22:34:54 +000011034 ++CurInit;
11035 ++CurPrivate;
Alexander Musman3276a272015-03-21 10:12:56 +000011036 }
11037 Clause.setUpdates(Updates);
11038 Clause.setFinals(Finals);
11039 return HasErrors;
Alexander Musman8dba6642014-04-22 13:09:42 +000011040}
11041
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011042OMPClause *Sema::ActOnOpenMPAlignedClause(
11043 ArrayRef<Expr *> VarList, Expr *Alignment, SourceLocation StartLoc,
11044 SourceLocation LParenLoc, SourceLocation ColonLoc, SourceLocation EndLoc) {
11045
11046 SmallVector<Expr *, 8> Vars;
11047 for (auto &RefExpr : VarList) {
Alexey Bataev1efd1662016-03-29 10:59:56 +000011048 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11049 SourceLocation ELoc;
11050 SourceRange ERange;
11051 Expr *SimpleRefExpr = RefExpr;
11052 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11053 /*AllowArraySection=*/false);
11054 if (Res.second) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011055 // It will be analyzed later.
11056 Vars.push_back(RefExpr);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011057 }
Alexey Bataev1efd1662016-03-29 10:59:56 +000011058 ValueDecl *D = Res.first;
11059 if (!D)
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011060 continue;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011061
Alexey Bataev1efd1662016-03-29 10:59:56 +000011062 QualType QType = D->getType();
11063 auto *VD = dyn_cast<VarDecl>(D);
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011064
11065 // OpenMP [2.8.1, simd construct, Restrictions]
11066 // The type of list items appearing in the aligned clause must be
11067 // array, pointer, reference to array, or reference to pointer.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011068 QType = QType.getNonReferenceType().getUnqualifiedType().getCanonicalType();
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011069 const Type *Ty = QType.getTypePtrOrNull();
Alexey Bataev1efd1662016-03-29 10:59:56 +000011070 if (!Ty || (!Ty->isArrayType() && !Ty->isPointerType())) {
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011071 Diag(ELoc, diag::err_omp_aligned_expected_array_or_ptr)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011072 << QType << getLangOpts().CPlusPlus << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011073 bool IsDecl =
Alexey Bataev1efd1662016-03-29 10:59:56 +000011074 !VD ||
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011075 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataev1efd1662016-03-29 10:59:56 +000011076 Diag(D->getLocation(),
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011077 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataev1efd1662016-03-29 10:59:56 +000011078 << D;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011079 continue;
11080 }
11081
11082 // OpenMP [2.8.1, simd construct, Restrictions]
11083 // A list-item cannot appear in more than one aligned clause.
Alexey Bataev1efd1662016-03-29 10:59:56 +000011084 if (Expr *PrevRef = DSAStack->addUniqueAligned(D, SimpleRefExpr)) {
Alexey Bataevd93d3762016-04-12 09:35:56 +000011085 Diag(ELoc, diag::err_omp_aligned_twice) << 0 << ERange;
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011086 Diag(PrevRef->getExprLoc(), diag::note_omp_explicit_dsa)
11087 << getOpenMPClauseName(OMPC_aligned);
11088 continue;
11089 }
11090
Alexey Bataev1efd1662016-03-29 10:59:56 +000011091 DeclRefExpr *Ref = nullptr;
11092 if (!VD && IsOpenMPCapturedDecl(D))
11093 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
11094 Vars.push_back(DefaultFunctionArrayConversion(
11095 (VD || !Ref) ? RefExpr->IgnoreParens() : Ref)
11096 .get());
Alexander Musmanf0d76e72014-05-29 14:36:25 +000011097 }
11098
11099 // OpenMP [2.8.1, simd construct, Description]
11100 // The parameter of the aligned clause, alignment, must be a constant
11101 // positive integer expression.
11102 // If no optional parameter is specified, implementation-defined default
11103 // alignments for SIMD instructions on the target platforms are assumed.
11104 if (Alignment != nullptr) {
11105 ExprResult AlignResult =
11106 VerifyPositiveIntegerConstantInClause(Alignment, OMPC_aligned);
11107 if (AlignResult.isInvalid())
11108 return nullptr;
11109 Alignment = AlignResult.get();
11110 }
11111 if (Vars.empty())
11112 return nullptr;
11113
11114 return OMPAlignedClause::Create(Context, StartLoc, LParenLoc, ColonLoc,
11115 EndLoc, Vars, Alignment);
11116}
11117
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011118OMPClause *Sema::ActOnOpenMPCopyinClause(ArrayRef<Expr *> VarList,
11119 SourceLocation StartLoc,
11120 SourceLocation LParenLoc,
11121 SourceLocation EndLoc) {
11122 SmallVector<Expr *, 8> Vars;
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011123 SmallVector<Expr *, 8> SrcExprs;
11124 SmallVector<Expr *, 8> DstExprs;
11125 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataeved09d242014-05-28 05:53:51 +000011126 for (auto &RefExpr : VarList) {
11127 assert(RefExpr && "NULL expr in OpenMP copyin clause.");
11128 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011129 // It will be analyzed later.
Alexey Bataeved09d242014-05-28 05:53:51 +000011130 Vars.push_back(RefExpr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011131 SrcExprs.push_back(nullptr);
11132 DstExprs.push_back(nullptr);
11133 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011134 continue;
11135 }
11136
Alexey Bataeved09d242014-05-28 05:53:51 +000011137 SourceLocation ELoc = RefExpr->getExprLoc();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011138 // OpenMP [2.1, C/C++]
11139 // A list item is a variable name.
11140 // OpenMP [2.14.4.1, Restrictions, p.1]
11141 // A list item that appears in a copyin clause must be threadprivate.
Alexey Bataeved09d242014-05-28 05:53:51 +000011142 DeclRefExpr *DE = dyn_cast<DeclRefExpr>(RefExpr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011143 if (!DE || !isa<VarDecl>(DE->getDecl())) {
Alexey Bataev48c0bfb2016-01-20 09:07:54 +000011144 Diag(ELoc, diag::err_omp_expected_var_name_member_expr)
11145 << 0 << RefExpr->getSourceRange();
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011146 continue;
11147 }
11148
11149 Decl *D = DE->getDecl();
11150 VarDecl *VD = cast<VarDecl>(D);
11151
11152 QualType Type = VD->getType();
11153 if (Type->isDependentType() || Type->isInstantiationDependentType()) {
11154 // It will be analyzed later.
11155 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011156 SrcExprs.push_back(nullptr);
11157 DstExprs.push_back(nullptr);
11158 AssignmentOps.push_back(nullptr);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011159 continue;
11160 }
11161
11162 // OpenMP [2.14.4.1, Restrictions, C/C++, p.1]
11163 // A list item that appears in a copyin clause must be threadprivate.
11164 if (!DSAStack->isThreadPrivate(VD)) {
11165 Diag(ELoc, diag::err_omp_required_access)
Alexey Bataeved09d242014-05-28 05:53:51 +000011166 << getOpenMPClauseName(OMPC_copyin)
11167 << getOpenMPDirectiveName(OMPD_threadprivate);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011168 continue;
11169 }
11170
11171 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11172 // A variable of class type (or array thereof) that appears in a
Alexey Bataev23b69422014-06-18 07:08:49 +000011173 // copyin clause requires an accessible, unambiguous copy assignment
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011174 // operator for the class type.
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011175 auto ElemType = Context.getBaseElementType(Type).getNonReferenceType();
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000011176 auto *SrcVD =
11177 buildVarDecl(*this, DE->getLocStart(), ElemType.getUnqualifiedType(),
11178 ".copyin.src", VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataev39f915b82015-05-08 10:41:21 +000011179 auto *PseudoSrcExpr = buildDeclRefExpr(
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011180 *this, SrcVD, ElemType.getUnqualifiedType(), DE->getExprLoc());
11181 auto *DstVD =
Alexey Bataev1d7f0fa2015-09-10 09:48:30 +000011182 buildVarDecl(*this, DE->getLocStart(), ElemType, ".copyin.dst",
11183 VD->hasAttrs() ? &VD->getAttrs() : nullptr);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011184 auto *PseudoDstExpr =
Alexey Bataevf120c0d2015-05-19 07:46:42 +000011185 buildDeclRefExpr(*this, DstVD, ElemType, DE->getExprLoc());
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011186 // For arrays generate assignment operation for single element and replace
11187 // it by the original array element in CodeGen.
11188 auto AssignmentOp = BuildBinOp(/*S=*/nullptr, DE->getExprLoc(), BO_Assign,
11189 PseudoDstExpr, PseudoSrcExpr);
11190 if (AssignmentOp.isInvalid())
11191 continue;
11192 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), DE->getExprLoc(),
11193 /*DiscardedValue=*/true);
11194 if (AssignmentOp.isInvalid())
11195 continue;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011196
11197 DSAStack->addDSA(VD, DE, OMPC_copyin);
11198 Vars.push_back(DE);
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011199 SrcExprs.push_back(PseudoSrcExpr);
11200 DstExprs.push_back(PseudoDstExpr);
11201 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011202 }
11203
Alexey Bataeved09d242014-05-28 05:53:51 +000011204 if (Vars.empty())
11205 return nullptr;
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011206
Alexey Bataevf56f98c2015-04-16 05:39:01 +000011207 return OMPCopyinClause::Create(Context, StartLoc, LParenLoc, EndLoc, Vars,
11208 SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevd48bcd82014-03-31 03:36:38 +000011209}
11210
Alexey Bataevbae9a792014-06-27 10:37:06 +000011211OMPClause *Sema::ActOnOpenMPCopyprivateClause(ArrayRef<Expr *> VarList,
11212 SourceLocation StartLoc,
11213 SourceLocation LParenLoc,
11214 SourceLocation EndLoc) {
11215 SmallVector<Expr *, 8> Vars;
Alexey Bataeva63048e2015-03-23 06:18:07 +000011216 SmallVector<Expr *, 8> SrcExprs;
11217 SmallVector<Expr *, 8> DstExprs;
11218 SmallVector<Expr *, 8> AssignmentOps;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011219 for (auto &RefExpr : VarList) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011220 assert(RefExpr && "NULL expr in OpenMP linear clause.");
11221 SourceLocation ELoc;
11222 SourceRange ERange;
11223 Expr *SimpleRefExpr = RefExpr;
11224 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange,
11225 /*AllowArraySection=*/false);
11226 if (Res.second) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011227 // It will be analyzed later.
11228 Vars.push_back(RefExpr);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011229 SrcExprs.push_back(nullptr);
11230 DstExprs.push_back(nullptr);
11231 AssignmentOps.push_back(nullptr);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011232 }
Alexey Bataeve122da12016-03-17 10:50:17 +000011233 ValueDecl *D = Res.first;
11234 if (!D)
Alexey Bataevbae9a792014-06-27 10:37:06 +000011235 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011236
Alexey Bataeve122da12016-03-17 10:50:17 +000011237 QualType Type = D->getType();
11238 auto *VD = dyn_cast<VarDecl>(D);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011239
11240 // OpenMP [2.14.4.2, Restrictions, p.2]
11241 // A list item that appears in a copyprivate clause may not appear in a
11242 // private or firstprivate clause on the single construct.
Alexey Bataeve122da12016-03-17 10:50:17 +000011243 if (!VD || !DSAStack->isThreadPrivate(VD)) {
11244 auto DVar = DSAStack->getTopDSA(D, false);
Alexey Bataeva63048e2015-03-23 06:18:07 +000011245 if (DVar.CKind != OMPC_unknown && DVar.CKind != OMPC_copyprivate &&
11246 DVar.RefExpr) {
Alexey Bataevbae9a792014-06-27 10:37:06 +000011247 Diag(ELoc, diag::err_omp_wrong_dsa)
11248 << getOpenMPClauseName(DVar.CKind)
11249 << getOpenMPClauseName(OMPC_copyprivate);
Alexey Bataeve122da12016-03-17 10:50:17 +000011250 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011251 continue;
11252 }
11253
11254 // OpenMP [2.11.4.2, Restrictions, p.1]
11255 // All list items that appear in a copyprivate clause must be either
11256 // threadprivate or private in the enclosing context.
11257 if (DVar.CKind == OMPC_unknown) {
Alexey Bataeve122da12016-03-17 10:50:17 +000011258 DVar = DSAStack->getImplicitDSA(D, false);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011259 if (DVar.CKind == OMPC_shared) {
11260 Diag(ELoc, diag::err_omp_required_access)
11261 << getOpenMPClauseName(OMPC_copyprivate)
11262 << "threadprivate or private in the enclosing context";
Alexey Bataeve122da12016-03-17 10:50:17 +000011263 ReportOriginalDSA(*this, DSAStack, D, DVar);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011264 continue;
11265 }
11266 }
11267 }
11268
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011269 // Variably modified types are not supported.
Alexey Bataev5129d3a2015-05-21 09:47:46 +000011270 if (!Type->isAnyPointerType() && Type->isVariablyModifiedType()) {
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011271 Diag(ELoc, diag::err_omp_variably_modified_type_not_supported)
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011272 << getOpenMPClauseName(OMPC_copyprivate) << Type
11273 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011274 bool IsDecl =
Alexey Bataeve122da12016-03-17 10:50:17 +000011275 !VD ||
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011276 VD->isThisDeclarationADefinition(Context) == VarDecl::DeclarationOnly;
Alexey Bataeve122da12016-03-17 10:50:17 +000011277 Diag(D->getLocation(),
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011278 IsDecl ? diag::note_previous_decl : diag::note_defined_here)
Alexey Bataeve122da12016-03-17 10:50:17 +000011279 << D;
Alexey Bataev7a3e5852015-05-19 08:19:24 +000011280 continue;
11281 }
Alexey Bataevccb59ec2015-05-19 08:44:56 +000011282
Alexey Bataevbae9a792014-06-27 10:37:06 +000011283 // OpenMP [2.14.4.1, Restrictions, C/C++, p.2]
11284 // A variable of class type (or array thereof) that appears in a
11285 // copyin clause requires an accessible, unambiguous copy assignment
11286 // operator for the class type.
Alexey Bataevbd9fec12015-08-18 06:47:21 +000011287 Type = Context.getBaseElementType(Type.getNonReferenceType())
11288 .getUnqualifiedType();
Alexey Bataev420d45b2015-04-14 05:11:24 +000011289 auto *SrcVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011290 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.src",
11291 D->hasAttrs() ? &D->getAttrs() : nullptr);
11292 auto *PseudoSrcExpr = buildDeclRefExpr(*this, SrcVD, Type, ELoc);
Alexey Bataev420d45b2015-04-14 05:11:24 +000011293 auto *DstVD =
Alexey Bataeve122da12016-03-17 10:50:17 +000011294 buildVarDecl(*this, RefExpr->getLocStart(), Type, ".copyprivate.dst",
11295 D->hasAttrs() ? &D->getAttrs() : nullptr);
David Majnemer9d168222016-08-05 17:44:54 +000011296 auto *PseudoDstExpr = buildDeclRefExpr(*this, DstVD, Type, ELoc);
Alexey Bataeve122da12016-03-17 10:50:17 +000011297 auto AssignmentOp = BuildBinOp(DSAStack->getCurScope(), ELoc, BO_Assign,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011298 PseudoDstExpr, PseudoSrcExpr);
11299 if (AssignmentOp.isInvalid())
11300 continue;
Alexey Bataeve122da12016-03-17 10:50:17 +000011301 AssignmentOp = ActOnFinishFullExpr(AssignmentOp.get(), ELoc,
Alexey Bataeva63048e2015-03-23 06:18:07 +000011302 /*DiscardedValue=*/true);
11303 if (AssignmentOp.isInvalid())
11304 continue;
Alexey Bataevbae9a792014-06-27 10:37:06 +000011305
11306 // No need to mark vars as copyprivate, they are already threadprivate or
11307 // implicitly private.
Alexey Bataeve122da12016-03-17 10:50:17 +000011308 assert(VD || IsOpenMPCapturedDecl(D));
11309 Vars.push_back(
11310 VD ? RefExpr->IgnoreParens()
11311 : buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/false));
Alexey Bataeva63048e2015-03-23 06:18:07 +000011312 SrcExprs.push_back(PseudoSrcExpr);
11313 DstExprs.push_back(PseudoDstExpr);
11314 AssignmentOps.push_back(AssignmentOp.get());
Alexey Bataevbae9a792014-06-27 10:37:06 +000011315 }
11316
11317 if (Vars.empty())
11318 return nullptr;
11319
Alexey Bataeva63048e2015-03-23 06:18:07 +000011320 return OMPCopyprivateClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11321 Vars, SrcExprs, DstExprs, AssignmentOps);
Alexey Bataevbae9a792014-06-27 10:37:06 +000011322}
11323
Alexey Bataev6125da92014-07-21 11:26:11 +000011324OMPClause *Sema::ActOnOpenMPFlushClause(ArrayRef<Expr *> VarList,
11325 SourceLocation StartLoc,
11326 SourceLocation LParenLoc,
11327 SourceLocation EndLoc) {
11328 if (VarList.empty())
11329 return nullptr;
11330
11331 return OMPFlushClause::Create(Context, StartLoc, LParenLoc, EndLoc, VarList);
11332}
Alexey Bataevdea47612014-07-23 07:46:59 +000011333
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011334OMPClause *
11335Sema::ActOnOpenMPDependClause(OpenMPDependClauseKind DepKind,
11336 SourceLocation DepLoc, SourceLocation ColonLoc,
11337 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
11338 SourceLocation LParenLoc, SourceLocation EndLoc) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011339 if (DSAStack->getCurrentDirective() == OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011340 DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink) {
Alexey Bataeveb482352015-12-18 05:05:56 +000011341 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011342 << "'source' or 'sink'" << getOpenMPClauseName(OMPC_depend);
Alexey Bataeveb482352015-12-18 05:05:56 +000011343 return nullptr;
11344 }
11345 if (DSAStack->getCurrentDirective() != OMPD_ordered &&
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011346 (DepKind == OMPC_DEPEND_unknown || DepKind == OMPC_DEPEND_source ||
11347 DepKind == OMPC_DEPEND_sink)) {
Alexey Bataev6402bca2015-12-28 07:25:51 +000011348 unsigned Except[] = {OMPC_DEPEND_source, OMPC_DEPEND_sink};
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011349 Diag(DepLoc, diag::err_omp_unexpected_clause_value)
Alexey Bataev6402bca2015-12-28 07:25:51 +000011350 << getListOfPossibleValues(OMPC_depend, /*First=*/0,
11351 /*Last=*/OMPC_DEPEND_unknown, Except)
11352 << getOpenMPClauseName(OMPC_depend);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011353 return nullptr;
11354 }
11355 SmallVector<Expr *, 8> Vars;
Alexey Bataev8b427062016-05-25 12:36:08 +000011356 DSAStackTy::OperatorOffsetTy OpsOffs;
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011357 llvm::APSInt DepCounter(/*BitWidth=*/32);
11358 llvm::APSInt TotalDepCount(/*BitWidth=*/32);
11359 if (DepKind == OMPC_DEPEND_sink) {
11360 if (auto *OrderedCountExpr = DSAStack->getParentOrderedRegionParam()) {
11361 TotalDepCount = OrderedCountExpr->EvaluateKnownConstInt(Context);
11362 TotalDepCount.setIsUnsigned(/*Val=*/true);
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011363 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011364 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011365 if ((DepKind != OMPC_DEPEND_sink && DepKind != OMPC_DEPEND_source) ||
11366 DSAStack->getParentOrderedRegionParam()) {
11367 for (auto &RefExpr : VarList) {
11368 assert(RefExpr && "NULL expr in OpenMP shared clause.");
Alexey Bataev8b427062016-05-25 12:36:08 +000011369 if (isa<DependentScopeDeclRefExpr>(RefExpr)) {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011370 // It will be analyzed later.
11371 Vars.push_back(RefExpr);
11372 continue;
11373 }
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011374
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011375 SourceLocation ELoc = RefExpr->getExprLoc();
11376 auto *SimpleExpr = RefExpr->IgnoreParenCasts();
11377 if (DepKind == OMPC_DEPEND_sink) {
11378 if (DepCounter >= TotalDepCount) {
11379 Diag(ELoc, diag::err_omp_depend_sink_unexpected_expr);
11380 continue;
11381 }
11382 ++DepCounter;
11383 // OpenMP [2.13.9, Summary]
11384 // depend(dependence-type : vec), where dependence-type is:
11385 // 'sink' and where vec is the iteration vector, which has the form:
11386 // x1 [+- d1], x2 [+- d2 ], . . . , xn [+- dn]
11387 // where n is the value specified by the ordered clause in the loop
11388 // directive, xi denotes the loop iteration variable of the i-th nested
11389 // loop associated with the loop directive, and di is a constant
11390 // non-negative integer.
Alexey Bataev8b427062016-05-25 12:36:08 +000011391 if (CurContext->isDependentContext()) {
11392 // It will be analyzed later.
11393 Vars.push_back(RefExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011394 continue;
11395 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011396 SimpleExpr = SimpleExpr->IgnoreImplicit();
11397 OverloadedOperatorKind OOK = OO_None;
11398 SourceLocation OOLoc;
11399 Expr *LHS = SimpleExpr;
11400 Expr *RHS = nullptr;
11401 if (auto *BO = dyn_cast<BinaryOperator>(SimpleExpr)) {
11402 OOK = BinaryOperator::getOverloadedOperator(BO->getOpcode());
11403 OOLoc = BO->getOperatorLoc();
11404 LHS = BO->getLHS()->IgnoreParenImpCasts();
11405 RHS = BO->getRHS()->IgnoreParenImpCasts();
11406 } else if (auto *OCE = dyn_cast<CXXOperatorCallExpr>(SimpleExpr)) {
11407 OOK = OCE->getOperator();
11408 OOLoc = OCE->getOperatorLoc();
11409 LHS = OCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11410 RHS = OCE->getArg(/*Arg=*/1)->IgnoreParenImpCasts();
11411 } else if (auto *MCE = dyn_cast<CXXMemberCallExpr>(SimpleExpr)) {
11412 OOK = MCE->getMethodDecl()
11413 ->getNameInfo()
11414 .getName()
11415 .getCXXOverloadedOperator();
11416 OOLoc = MCE->getCallee()->getExprLoc();
11417 LHS = MCE->getImplicitObjectArgument()->IgnoreParenImpCasts();
11418 RHS = MCE->getArg(/*Arg=*/0)->IgnoreParenImpCasts();
11419 }
11420 SourceLocation ELoc;
11421 SourceRange ERange;
11422 auto Res = getPrivateItem(*this, LHS, ELoc, ERange,
11423 /*AllowArraySection=*/false);
11424 if (Res.second) {
11425 // It will be analyzed later.
11426 Vars.push_back(RefExpr);
11427 }
11428 ValueDecl *D = Res.first;
11429 if (!D)
11430 continue;
11431
11432 if (OOK != OO_Plus && OOK != OO_Minus && (RHS || OOK != OO_None)) {
11433 Diag(OOLoc, diag::err_omp_depend_sink_expected_plus_minus);
11434 continue;
11435 }
11436 if (RHS) {
11437 ExprResult RHSRes = VerifyPositiveIntegerConstantInClause(
11438 RHS, OMPC_depend, /*StrictlyPositive=*/false);
11439 if (RHSRes.isInvalid())
11440 continue;
11441 }
11442 if (!CurContext->isDependentContext() &&
11443 DSAStack->getParentOrderedRegionParam() &&
11444 DepCounter != DSAStack->isParentLoopControlVariable(D).first) {
Rachel Craik1cf49e42017-09-19 21:04:23 +000011445 ValueDecl* VD = DSAStack->getParentLoopControlVariable(
11446 DepCounter.getZExtValue());
11447 if (VD) {
11448 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration)
11449 << 1 << VD;
11450 } else {
11451 Diag(ELoc, diag::err_omp_depend_sink_expected_loop_iteration) << 0;
11452 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011453 continue;
11454 }
11455 OpsOffs.push_back({RHS, OOK});
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011456 } else {
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011457 auto *ASE = dyn_cast<ArraySubscriptExpr>(SimpleExpr);
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011458 if (!RefExpr->IgnoreParenImpCasts()->isLValue() ||
Alexey Bataev31300ed2016-02-04 11:27:03 +000011459 (ASE &&
11460 !ASE->getBase()
11461 ->getType()
11462 .getNonReferenceType()
11463 ->isPointerType() &&
11464 !ASE->getBase()->getType().getNonReferenceType()->isArrayType())) {
Alexey Bataev463a9fe2017-07-27 19:15:30 +000011465 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11466 << RefExpr->getSourceRange();
11467 continue;
11468 }
11469 bool Suppress = getDiagnostics().getSuppressAllDiagnostics();
11470 getDiagnostics().setSuppressAllDiagnostics(/*Val=*/true);
Alexey Bataevd070a582017-10-25 15:54:04 +000011471 ExprResult Res = CreateBuiltinUnaryOp(ELoc, UO_AddrOf,
Alexey Bataev463a9fe2017-07-27 19:15:30 +000011472 RefExpr->IgnoreParenImpCasts());
11473 getDiagnostics().setSuppressAllDiagnostics(Suppress);
11474 if (!Res.isUsable() && !isa<OMPArraySectionExpr>(SimpleExpr)) {
11475 Diag(ELoc, diag::err_omp_expected_addressable_lvalue_or_array_item)
11476 << RefExpr->getSourceRange();
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011477 continue;
11478 }
11479 }
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011480 Vars.push_back(RefExpr->IgnoreParenImpCasts());
11481 }
11482
11483 if (!CurContext->isDependentContext() && DepKind == OMPC_DEPEND_sink &&
11484 TotalDepCount > VarList.size() &&
Rachel Craik1cf49e42017-09-19 21:04:23 +000011485 DSAStack->getParentOrderedRegionParam() &&
11486 DSAStack->getParentLoopControlVariable(VarList.size() + 1)) {
11487 Diag(EndLoc, diag::err_omp_depend_sink_expected_loop_iteration) << 1
Alexey Bataeva636c7f2015-12-23 10:27:45 +000011488 << DSAStack->getParentLoopControlVariable(VarList.size() + 1);
11489 }
11490 if (DepKind != OMPC_DEPEND_source && DepKind != OMPC_DEPEND_sink &&
11491 Vars.empty())
11492 return nullptr;
11493 }
Alexey Bataev8b427062016-05-25 12:36:08 +000011494 auto *C = OMPDependClause::Create(Context, StartLoc, LParenLoc, EndLoc,
11495 DepKind, DepLoc, ColonLoc, Vars);
11496 if (DepKind == OMPC_DEPEND_sink || DepKind == OMPC_DEPEND_source)
11497 DSAStack->addDoacrossDependClause(C, OpsOffs);
11498 return C;
Alexey Bataev1c2cfbc2015-06-23 14:25:19 +000011499}
Michael Wonge710d542015-08-07 16:16:36 +000011500
11501OMPClause *Sema::ActOnOpenMPDeviceClause(Expr *Device, SourceLocation StartLoc,
11502 SourceLocation LParenLoc,
11503 SourceLocation EndLoc) {
11504 Expr *ValExpr = Device;
Alexey Bataev931e19b2017-10-02 16:32:39 +000011505 Stmt *HelperValStmt = nullptr;
Michael Wonge710d542015-08-07 16:16:36 +000011506
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011507 // OpenMP [2.9.1, Restrictions]
11508 // The device expression must evaluate to a non-negative integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000011509 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_device,
11510 /*StrictlyPositive=*/false))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000011511 return nullptr;
11512
Alexey Bataev931e19b2017-10-02 16:32:39 +000011513 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000011514 OpenMPDirectiveKind CaptureRegion =
11515 getOpenMPCaptureRegionForClause(DKind, OMPC_device);
11516 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000011517 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev931e19b2017-10-02 16:32:39 +000011518 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
11519 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
11520 HelperValStmt = buildPreInits(Context, Captures);
11521 }
11522
Alexey Bataev8451efa2018-01-15 19:06:12 +000011523 return new (Context) OMPDeviceClause(ValExpr, HelperValStmt, CaptureRegion,
11524 StartLoc, LParenLoc, EndLoc);
Michael Wonge710d542015-08-07 16:16:36 +000011525}
Kelvin Li0bff7af2015-11-23 05:32:03 +000011526
Kelvin Li0bff7af2015-11-23 05:32:03 +000011527static bool CheckTypeMappable(SourceLocation SL, SourceRange SR, Sema &SemaRef,
11528 DSAStackTy *Stack, QualType QTy) {
11529 NamedDecl *ND;
11530 if (QTy->isIncompleteType(&ND)) {
11531 SemaRef.Diag(SL, diag::err_incomplete_type) << QTy << SR;
11532 return false;
Kelvin Li0bff7af2015-11-23 05:32:03 +000011533 }
11534 return true;
11535}
11536
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011537/// \brief Return true if it can be proven that the provided array expression
11538/// (array section or array subscript) does NOT specify the whole size of the
11539/// array whose base type is \a BaseQTy.
11540static bool CheckArrayExpressionDoesNotReferToWholeSize(Sema &SemaRef,
11541 const Expr *E,
11542 QualType BaseQTy) {
11543 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11544
11545 // If this is an array subscript, it refers to the whole size if the size of
11546 // the dimension is constant and equals 1. Also, an array section assumes the
11547 // format of an array subscript if no colon is used.
11548 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid())) {
11549 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11550 return ATy->getSize().getSExtValue() != 1;
11551 // Size can't be evaluated statically.
11552 return false;
11553 }
11554
11555 assert(OASE && "Expecting array section if not an array subscript.");
11556 auto *LowerBound = OASE->getLowerBound();
11557 auto *Length = OASE->getLength();
11558
11559 // If there is a lower bound that does not evaluates to zero, we are not
David Majnemer9d168222016-08-05 17:44:54 +000011560 // covering the whole dimension.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011561 if (LowerBound) {
11562 llvm::APSInt ConstLowerBound;
11563 if (!LowerBound->EvaluateAsInt(ConstLowerBound, SemaRef.getASTContext()))
11564 return false; // Can't get the integer value as a constant.
11565 if (ConstLowerBound.getSExtValue())
11566 return true;
11567 }
11568
11569 // If we don't have a length we covering the whole dimension.
11570 if (!Length)
11571 return false;
11572
11573 // If the base is a pointer, we don't have a way to get the size of the
11574 // pointee.
11575 if (BaseQTy->isPointerType())
11576 return false;
11577
11578 // We can only check if the length is the same as the size of the dimension
11579 // if we have a constant array.
11580 auto *CATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr());
11581 if (!CATy)
11582 return false;
11583
11584 llvm::APSInt ConstLength;
11585 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11586 return false; // Can't get the integer value as a constant.
11587
11588 return CATy->getSize().getSExtValue() != ConstLength.getSExtValue();
11589}
11590
11591// Return true if it can be proven that the provided array expression (array
11592// section or array subscript) does NOT specify a single element of the array
11593// whose base type is \a BaseQTy.
11594static bool CheckArrayExpressionDoesNotReferToUnitySize(Sema &SemaRef,
David Majnemer9d168222016-08-05 17:44:54 +000011595 const Expr *E,
11596 QualType BaseQTy) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011597 auto *OASE = dyn_cast<OMPArraySectionExpr>(E);
11598
11599 // An array subscript always refer to a single element. Also, an array section
11600 // assumes the format of an array subscript if no colon is used.
11601 if (isa<ArraySubscriptExpr>(E) || (OASE && OASE->getColonLoc().isInvalid()))
11602 return false;
11603
11604 assert(OASE && "Expecting array section if not an array subscript.");
11605 auto *Length = OASE->getLength();
11606
11607 // If we don't have a length we have to check if the array has unitary size
11608 // for this dimension. Also, we should always expect a length if the base type
11609 // is pointer.
11610 if (!Length) {
11611 if (auto *ATy = dyn_cast<ConstantArrayType>(BaseQTy.getTypePtr()))
11612 return ATy->getSize().getSExtValue() != 1;
11613 // We cannot assume anything.
11614 return false;
11615 }
11616
11617 // Check if the length evaluates to 1.
11618 llvm::APSInt ConstLength;
11619 if (!Length->EvaluateAsInt(ConstLength, SemaRef.getASTContext()))
11620 return false; // Can't get the integer value as a constant.
11621
11622 return ConstLength.getSExtValue() != 1;
11623}
11624
Samuel Antao661c0902016-05-26 17:39:58 +000011625// Return the expression of the base of the mappable expression or null if it
11626// cannot be determined and do all the necessary checks to see if the expression
11627// is valid as a standalone mappable expression. In the process, record all the
Samuel Antao90927002016-04-26 14:54:23 +000011628// components of the expression.
11629static Expr *CheckMapClauseExpressionBase(
11630 Sema &SemaRef, Expr *E,
Samuel Antao661c0902016-05-26 17:39:58 +000011631 OMPClauseMappableExprCommon::MappableExprComponentList &CurComponents,
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011632 OpenMPClauseKind CKind, bool NoDiagnose) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011633 SourceLocation ELoc = E->getExprLoc();
11634 SourceRange ERange = E->getSourceRange();
11635
11636 // The base of elements of list in a map clause have to be either:
11637 // - a reference to variable or field.
11638 // - a member expression.
11639 // - an array expression.
11640 //
11641 // E.g. if we have the expression 'r.S.Arr[:12]', we want to retrieve the
11642 // reference to 'r'.
11643 //
11644 // If we have:
11645 //
11646 // struct SS {
11647 // Bla S;
11648 // foo() {
11649 // #pragma omp target map (S.Arr[:12]);
11650 // }
11651 // }
11652 //
11653 // We want to retrieve the member expression 'this->S';
11654
11655 Expr *RelevantExpr = nullptr;
11656
Samuel Antao5de996e2016-01-22 20:21:36 +000011657 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.2]
11658 // If a list item is an array section, it must specify contiguous storage.
11659 //
11660 // For this restriction it is sufficient that we make sure only references
11661 // to variables or fields and array expressions, and that no array sections
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011662 // exist except in the rightmost expression (unless they cover the whole
11663 // dimension of the array). E.g. these would be invalid:
Samuel Antao5de996e2016-01-22 20:21:36 +000011664 //
11665 // r.ArrS[3:5].Arr[6:7]
11666 //
11667 // r.ArrS[3:5].x
11668 //
11669 // but these would be valid:
11670 // r.ArrS[3].Arr[6:7]
11671 //
11672 // r.ArrS[3].x
11673
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011674 bool AllowUnitySizeArraySection = true;
11675 bool AllowWholeSizeArraySection = true;
Samuel Antao5de996e2016-01-22 20:21:36 +000011676
Dmitry Polukhin644a9252016-03-11 07:58:34 +000011677 while (!RelevantExpr) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011678 E = E->IgnoreParenImpCasts();
11679
11680 if (auto *CurE = dyn_cast<DeclRefExpr>(E)) {
11681 if (!isa<VarDecl>(CurE->getDecl()))
Alexey Bataev27041fa2017-12-05 15:22:49 +000011682 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011683
11684 RelevantExpr = CurE;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011685
11686 // If we got a reference to a declaration, we should not expect any array
11687 // section before that.
11688 AllowUnitySizeArraySection = false;
11689 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011690
11691 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011692 CurComponents.emplace_back(CurE, CurE->getDecl());
11693 } else if (auto *CurE = dyn_cast<MemberExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011694 auto *BaseE = CurE->getBase()->IgnoreParenImpCasts();
11695
11696 if (isa<CXXThisExpr>(BaseE))
11697 // We found a base expression: this->Val.
11698 RelevantExpr = CurE;
11699 else
11700 E = BaseE;
11701
11702 if (!isa<FieldDecl>(CurE->getMemberDecl())) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011703 if (!NoDiagnose) {
11704 SemaRef.Diag(ELoc, diag::err_omp_expected_access_to_data_field)
11705 << CurE->getSourceRange();
11706 return nullptr;
11707 }
11708 if (RelevantExpr)
11709 return nullptr;
11710 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011711 }
11712
11713 auto *FD = cast<FieldDecl>(CurE->getMemberDecl());
11714
11715 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.3]
11716 // A bit-field cannot appear in a map clause.
11717 //
11718 if (FD->isBitField()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011719 if (!NoDiagnose) {
11720 SemaRef.Diag(ELoc, diag::err_omp_bit_fields_forbidden_in_clause)
11721 << CurE->getSourceRange() << getOpenMPClauseName(CKind);
11722 return nullptr;
11723 }
11724 if (RelevantExpr)
11725 return nullptr;
11726 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011727 }
11728
11729 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11730 // If the type of a list item is a reference to a type T then the type
11731 // will be considered to be T for all purposes of this clause.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011732 QualType CurType = BaseE->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011733
11734 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.2]
11735 // A list item cannot be a variable that is a member of a structure with
11736 // a union type.
11737 //
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011738 if (auto *RT = CurType->getAs<RecordType>()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011739 if (RT->isUnionType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011740 if (!NoDiagnose) {
11741 SemaRef.Diag(ELoc, diag::err_omp_union_type_not_allowed)
11742 << CurE->getSourceRange();
11743 return nullptr;
11744 }
11745 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011746 }
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011747 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011748
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011749 // If we got a member expression, we should not expect any array section
11750 // before that:
11751 //
11752 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.7]
11753 // If a list item is an element of a structure, only the rightmost symbol
11754 // of the variable reference can be an array section.
11755 //
11756 AllowUnitySizeArraySection = false;
11757 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011758
11759 // Record the component.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011760 CurComponents.emplace_back(CurE, FD);
11761 } else if (auto *CurE = dyn_cast<ArraySubscriptExpr>(E)) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011762 E = CurE->getBase()->IgnoreParenImpCasts();
11763
11764 if (!E->getType()->isAnyPointerType() && !E->getType()->isArrayType()) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011765 if (!NoDiagnose) {
11766 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11767 << 0 << CurE->getSourceRange();
11768 return nullptr;
11769 }
11770 continue;
Samuel Antao5de996e2016-01-22 20:21:36 +000011771 }
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011772
11773 // If we got an array subscript that express the whole dimension we
11774 // can have any array expressions before. If it only expressing part of
11775 // the dimension, we can only have unitary-size array expressions.
11776 if (CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE,
11777 E->getType()))
11778 AllowWholeSizeArraySection = false;
Samuel Antao90927002016-04-26 14:54:23 +000011779
11780 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011781 CurComponents.emplace_back(CurE, nullptr);
11782 } else if (auto *CurE = dyn_cast<OMPArraySectionExpr>(E)) {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011783 assert(!NoDiagnose && "Array sections cannot be implicitly mapped.");
Samuel Antao5de996e2016-01-22 20:21:36 +000011784 E = CurE->getBase()->IgnoreParenImpCasts();
11785
Alexey Bataev27041fa2017-12-05 15:22:49 +000011786 QualType CurType =
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011787 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11788
Samuel Antao5de996e2016-01-22 20:21:36 +000011789 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11790 // If the type of a list item is a reference to a type T then the type
11791 // will be considered to be T for all purposes of this clause.
Samuel Antao5de996e2016-01-22 20:21:36 +000011792 if (CurType->isReferenceType())
11793 CurType = CurType->getPointeeType();
11794
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011795 bool IsPointer = CurType->isAnyPointerType();
11796
11797 if (!IsPointer && !CurType->isArrayType()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011798 SemaRef.Diag(ELoc, diag::err_omp_expected_base_var_name)
11799 << 0 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000011800 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011801 }
11802
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011803 bool NotWhole =
11804 CheckArrayExpressionDoesNotReferToWholeSize(SemaRef, CurE, CurType);
11805 bool NotUnity =
11806 CheckArrayExpressionDoesNotReferToUnitySize(SemaRef, CurE, CurType);
11807
Samuel Antaodab51bb2016-07-18 23:22:11 +000011808 if (AllowWholeSizeArraySection) {
11809 // Any array section is currently allowed. Allowing a whole size array
11810 // section implies allowing a unity array section as well.
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011811 //
11812 // If this array section refers to the whole dimension we can still
11813 // accept other array sections before this one, except if the base is a
11814 // pointer. Otherwise, only unitary sections are accepted.
11815 if (NotWhole || IsPointer)
11816 AllowWholeSizeArraySection = false;
Samuel Antaodab51bb2016-07-18 23:22:11 +000011817 } else if (AllowUnitySizeArraySection && NotUnity) {
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011818 // A unity or whole array section is not allowed and that is not
11819 // compatible with the properties of the current array section.
11820 SemaRef.Diag(
11821 ELoc, diag::err_array_section_does_not_specify_contiguous_storage)
11822 << CurE->getSourceRange();
Alexey Bataev27041fa2017-12-05 15:22:49 +000011823 return nullptr;
Samuel Antaoa9f35cb2016-03-09 15:46:05 +000011824 }
Samuel Antao90927002016-04-26 14:54:23 +000011825
11826 // Record the component - we don't have any declaration associated.
Alexey Bataev27041fa2017-12-05 15:22:49 +000011827 CurComponents.emplace_back(CurE, nullptr);
11828 } else {
Alexey Bataevb7a9b742017-12-05 19:20:09 +000011829 if (!NoDiagnose) {
11830 // If nothing else worked, this is not a valid map clause expression.
11831 SemaRef.Diag(
11832 ELoc, diag::err_omp_expected_named_var_member_or_array_expression)
11833 << ERange;
11834 }
Alexey Bataev27041fa2017-12-05 15:22:49 +000011835 return nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011836 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011837 }
11838
11839 return RelevantExpr;
11840}
11841
11842// Return true if expression E associated with value VD has conflicts with other
11843// map information.
Samuel Antao90927002016-04-26 14:54:23 +000011844static bool CheckMapConflicts(
11845 Sema &SemaRef, DSAStackTy *DSAS, ValueDecl *VD, Expr *E,
11846 bool CurrentRegionOnly,
Samuel Antao661c0902016-05-26 17:39:58 +000011847 OMPClauseMappableExprCommon::MappableExprComponentListRef CurComponents,
11848 OpenMPClauseKind CKind) {
Samuel Antao5de996e2016-01-22 20:21:36 +000011849 assert(VD && E);
Samuel Antao5de996e2016-01-22 20:21:36 +000011850 SourceLocation ELoc = E->getExprLoc();
11851 SourceRange ERange = E->getSourceRange();
11852
11853 // In order to easily check the conflicts we need to match each component of
11854 // the expression under test with the components of the expressions that are
11855 // already in the stack.
11856
Samuel Antao5de996e2016-01-22 20:21:36 +000011857 assert(!CurComponents.empty() && "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011858 assert(CurComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011859 "Map clause expression with unexpected base!");
11860
11861 // Variables to help detecting enclosing problems in data environment nests.
11862 bool IsEnclosedByDataEnvironmentExpr = false;
Samuel Antao90927002016-04-26 14:54:23 +000011863 const Expr *EnclosingExpr = nullptr;
Samuel Antao5de996e2016-01-22 20:21:36 +000011864
Samuel Antao90927002016-04-26 14:54:23 +000011865 bool FoundError = DSAS->checkMappableExprComponentListsForDecl(
11866 VD, CurrentRegionOnly,
11867 [&](OMPClauseMappableExprCommon::MappableExprComponentListRef
Samuel Antao6890b092016-07-28 14:25:09 +000011868 StackComponents,
11869 OpenMPClauseKind) -> bool {
Samuel Antao90927002016-04-26 14:54:23 +000011870
Samuel Antao5de996e2016-01-22 20:21:36 +000011871 assert(!StackComponents.empty() &&
11872 "Map clause expression with no components!");
Samuel Antao90927002016-04-26 14:54:23 +000011873 assert(StackComponents.back().getAssociatedDeclaration() == VD &&
Samuel Antao5de996e2016-01-22 20:21:36 +000011874 "Map clause expression with unexpected base!");
11875
Samuel Antao90927002016-04-26 14:54:23 +000011876 // The whole expression in the stack.
11877 auto *RE = StackComponents.front().getAssociatedExpression();
11878
Samuel Antao5de996e2016-01-22 20:21:36 +000011879 // Expressions must start from the same base. Here we detect at which
11880 // point both expressions diverge from each other and see if we can
11881 // detect if the memory referred to both expressions is contiguous and
11882 // do not overlap.
11883 auto CI = CurComponents.rbegin();
11884 auto CE = CurComponents.rend();
11885 auto SI = StackComponents.rbegin();
11886 auto SE = StackComponents.rend();
11887 for (; CI != CE && SI != SE; ++CI, ++SI) {
11888
11889 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.3]
11890 // At most one list item can be an array item derived from a given
11891 // variable in map clauses of the same construct.
Samuel Antao90927002016-04-26 14:54:23 +000011892 if (CurrentRegionOnly &&
11893 (isa<ArraySubscriptExpr>(CI->getAssociatedExpression()) ||
11894 isa<OMPArraySectionExpr>(CI->getAssociatedExpression())) &&
11895 (isa<ArraySubscriptExpr>(SI->getAssociatedExpression()) ||
11896 isa<OMPArraySectionExpr>(SI->getAssociatedExpression()))) {
11897 SemaRef.Diag(CI->getAssociatedExpression()->getExprLoc(),
Samuel Antao5de996e2016-01-22 20:21:36 +000011898 diag::err_omp_multiple_array_items_in_map_clause)
Samuel Antao90927002016-04-26 14:54:23 +000011899 << CI->getAssociatedExpression()->getSourceRange();
11900 SemaRef.Diag(SI->getAssociatedExpression()->getExprLoc(),
11901 diag::note_used_here)
11902 << SI->getAssociatedExpression()->getSourceRange();
Samuel Antao5de996e2016-01-22 20:21:36 +000011903 return true;
11904 }
11905
11906 // Do both expressions have the same kind?
Samuel Antao90927002016-04-26 14:54:23 +000011907 if (CI->getAssociatedExpression()->getStmtClass() !=
11908 SI->getAssociatedExpression()->getStmtClass())
Samuel Antao5de996e2016-01-22 20:21:36 +000011909 break;
11910
11911 // Are we dealing with different variables/fields?
Samuel Antao90927002016-04-26 14:54:23 +000011912 if (CI->getAssociatedDeclaration() != SI->getAssociatedDeclaration())
Samuel Antao5de996e2016-01-22 20:21:36 +000011913 break;
11914 }
Kelvin Li9f645ae2016-07-18 22:49:16 +000011915 // Check if the extra components of the expressions in the enclosing
11916 // data environment are redundant for the current base declaration.
11917 // If they are, the maps completely overlap, which is legal.
11918 for (; SI != SE; ++SI) {
11919 QualType Type;
11920 if (auto *ASE =
David Majnemer9d168222016-08-05 17:44:54 +000011921 dyn_cast<ArraySubscriptExpr>(SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011922 Type = ASE->getBase()->IgnoreParenImpCasts()->getType();
David Majnemer9d168222016-08-05 17:44:54 +000011923 } else if (auto *OASE = dyn_cast<OMPArraySectionExpr>(
11924 SI->getAssociatedExpression())) {
Kelvin Li9f645ae2016-07-18 22:49:16 +000011925 auto *E = OASE->getBase()->IgnoreParenImpCasts();
11926 Type =
11927 OMPArraySectionExpr::getBaseOriginalType(E).getCanonicalType();
11928 }
11929 if (Type.isNull() || Type->isAnyPointerType() ||
11930 CheckArrayExpressionDoesNotReferToWholeSize(
11931 SemaRef, SI->getAssociatedExpression(), Type))
11932 break;
11933 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011934
11935 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11936 // List items of map clauses in the same construct must not share
11937 // original storage.
11938 //
11939 // If the expressions are exactly the same or one is a subset of the
11940 // other, it means they are sharing storage.
11941 if (CI == CE && SI == SE) {
11942 if (CurrentRegionOnly) {
Samuel Antao661c0902016-05-26 17:39:58 +000011943 if (CKind == OMPC_map)
11944 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
11945 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000011946 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000011947 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
11948 << ERange;
11949 }
Samuel Antao5de996e2016-01-22 20:21:36 +000011950 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11951 << RE->getSourceRange();
11952 return true;
11953 } else {
11954 // If we find the same expression in the enclosing data environment,
11955 // that is legal.
11956 IsEnclosedByDataEnvironmentExpr = true;
11957 return false;
11958 }
11959 }
11960
Samuel Antao90927002016-04-26 14:54:23 +000011961 QualType DerivedType =
11962 std::prev(CI)->getAssociatedDeclaration()->getType();
11963 SourceLocation DerivedLoc =
11964 std::prev(CI)->getAssociatedExpression()->getExprLoc();
Samuel Antao5de996e2016-01-22 20:21:36 +000011965
11966 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
11967 // If the type of a list item is a reference to a type T then the type
11968 // will be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000011969 DerivedType = DerivedType.getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000011970
11971 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C/C++, p.1]
11972 // A variable for which the type is pointer and an array section
11973 // derived from that variable must not appear as list items of map
11974 // clauses of the same construct.
11975 //
11976 // Also, cover one of the cases in:
11977 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
11978 // If any part of the original storage of a list item has corresponding
11979 // storage in the device data environment, all of the original storage
11980 // must have corresponding storage in the device data environment.
11981 //
11982 if (DerivedType->isAnyPointerType()) {
11983 if (CI == CE || SI == SE) {
11984 SemaRef.Diag(
11985 DerivedLoc,
11986 diag::err_omp_pointer_mapped_along_with_derived_section)
11987 << DerivedLoc;
11988 } else {
11989 assert(CI != CE && SI != SE);
11990 SemaRef.Diag(DerivedLoc, diag::err_omp_same_pointer_derreferenced)
11991 << DerivedLoc;
11992 }
11993 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
11994 << RE->getSourceRange();
11995 return true;
11996 }
11997
11998 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.4]
11999 // List items of map clauses in the same construct must not share
12000 // original storage.
12001 //
12002 // An expression is a subset of the other.
12003 if (CurrentRegionOnly && (CI == CE || SI == SE)) {
Samuel Antao661c0902016-05-26 17:39:58 +000012004 if (CKind == OMPC_map)
12005 SemaRef.Diag(ELoc, diag::err_omp_map_shared_storage) << ERange;
12006 else {
Samuel Antaoec172c62016-05-26 17:49:04 +000012007 assert(CKind == OMPC_to || CKind == OMPC_from);
Samuel Antao661c0902016-05-26 17:39:58 +000012008 SemaRef.Diag(ELoc, diag::err_omp_once_referenced_in_target_update)
12009 << ERange;
12010 }
Samuel Antao5de996e2016-01-22 20:21:36 +000012011 SemaRef.Diag(RE->getExprLoc(), diag::note_used_here)
12012 << RE->getSourceRange();
12013 return true;
12014 }
12015
12016 // The current expression uses the same base as other expression in the
Samuel Antao90927002016-04-26 14:54:23 +000012017 // data environment but does not contain it completely.
Samuel Antao5de996e2016-01-22 20:21:36 +000012018 if (!CurrentRegionOnly && SI != SE)
12019 EnclosingExpr = RE;
12020
12021 // The current expression is a subset of the expression in the data
12022 // environment.
12023 IsEnclosedByDataEnvironmentExpr |=
12024 (!CurrentRegionOnly && CI != CE && SI == SE);
12025
12026 return false;
12027 });
12028
12029 if (CurrentRegionOnly)
12030 return FoundError;
12031
12032 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.5]
12033 // If any part of the original storage of a list item has corresponding
12034 // storage in the device data environment, all of the original storage must
12035 // have corresponding storage in the device data environment.
12036 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.6]
12037 // If a list item is an element of a structure, and a different element of
12038 // the structure has a corresponding list item in the device data environment
12039 // prior to a task encountering the construct associated with the map clause,
Samuel Antao90927002016-04-26 14:54:23 +000012040 // then the list item must also have a corresponding list item in the device
Samuel Antao5de996e2016-01-22 20:21:36 +000012041 // data environment prior to the task encountering the construct.
12042 //
12043 if (EnclosingExpr && !IsEnclosedByDataEnvironmentExpr) {
12044 SemaRef.Diag(ELoc,
12045 diag::err_omp_original_storage_is_shared_and_does_not_contain)
12046 << ERange;
12047 SemaRef.Diag(EnclosingExpr->getExprLoc(), diag::note_used_here)
12048 << EnclosingExpr->getSourceRange();
12049 return true;
12050 }
12051
12052 return FoundError;
12053}
12054
Samuel Antao661c0902016-05-26 17:39:58 +000012055namespace {
12056// Utility struct that gathers all the related lists associated with a mappable
12057// expression.
12058struct MappableVarListInfo final {
12059 // The list of expressions.
12060 ArrayRef<Expr *> VarList;
12061 // The list of processed expressions.
12062 SmallVector<Expr *, 16> ProcessedVarList;
12063 // The mappble components for each expression.
12064 OMPClauseMappableExprCommon::MappableExprComponentLists VarComponents;
12065 // The base declaration of the variable.
12066 SmallVector<ValueDecl *, 16> VarBaseDeclarations;
12067
12068 MappableVarListInfo(ArrayRef<Expr *> VarList) : VarList(VarList) {
12069 // We have a list of components and base declarations for each entry in the
12070 // variable list.
12071 VarComponents.reserve(VarList.size());
12072 VarBaseDeclarations.reserve(VarList.size());
12073 }
12074};
12075}
12076
12077// Check the validity of the provided variable list for the provided clause kind
12078// \a CKind. In the check process the valid expressions, and mappable expression
12079// components and variables are extracted and used to fill \a Vars,
12080// \a ClauseComponents, and \a ClauseBaseDeclarations. \a MapType and
12081// \a IsMapTypeImplicit are expected to be valid if the clause kind is 'map'.
12082static void
12083checkMappableExpressionList(Sema &SemaRef, DSAStackTy *DSAS,
12084 OpenMPClauseKind CKind, MappableVarListInfo &MVLI,
12085 SourceLocation StartLoc,
12086 OpenMPMapClauseKind MapType = OMPC_MAP_unknown,
12087 bool IsMapTypeImplicit = false) {
Samuel Antaoec172c62016-05-26 17:49:04 +000012088 // We only expect mappable expressions in 'to', 'from', and 'map' clauses.
12089 assert((CKind == OMPC_map || CKind == OMPC_to || CKind == OMPC_from) &&
Samuel Antao661c0902016-05-26 17:39:58 +000012090 "Unexpected clause kind with mappable expressions!");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012091
Samuel Antao90927002016-04-26 14:54:23 +000012092 // Keep track of the mappable components and base declarations in this clause.
12093 // Each entry in the list is going to have a list of components associated. We
12094 // record each set of the components so that we can build the clause later on.
12095 // In the end we should have the same amount of declarations and component
12096 // lists.
Samuel Antao90927002016-04-26 14:54:23 +000012097
Samuel Antao661c0902016-05-26 17:39:58 +000012098 for (auto &RE : MVLI.VarList) {
Samuel Antaoec172c62016-05-26 17:49:04 +000012099 assert(RE && "Null expr in omp to/from/map clause");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012100 SourceLocation ELoc = RE->getExprLoc();
12101
Kelvin Li0bff7af2015-11-23 05:32:03 +000012102 auto *VE = RE->IgnoreParenLValueCasts();
12103
12104 if (VE->isValueDependent() || VE->isTypeDependent() ||
12105 VE->isInstantiationDependent() ||
12106 VE->containsUnexpandedParameterPack()) {
Samuel Antao5de996e2016-01-22 20:21:36 +000012107 // We can only analyze this information once the missing information is
12108 // resolved.
Samuel Antao661c0902016-05-26 17:39:58 +000012109 MVLI.ProcessedVarList.push_back(RE);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012110 continue;
12111 }
12112
12113 auto *SimpleExpr = RE->IgnoreParenCasts();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012114
Samuel Antao5de996e2016-01-22 20:21:36 +000012115 if (!RE->IgnoreParenImpCasts()->isLValue()) {
Samuel Antao661c0902016-05-26 17:39:58 +000012116 SemaRef.Diag(ELoc,
12117 diag::err_omp_expected_named_var_member_or_array_expression)
Samuel Antao5de996e2016-01-22 20:21:36 +000012118 << RE->getSourceRange();
Kelvin Li0bff7af2015-11-23 05:32:03 +000012119 continue;
12120 }
12121
Samuel Antao90927002016-04-26 14:54:23 +000012122 OMPClauseMappableExprCommon::MappableExprComponentList CurComponents;
12123 ValueDecl *CurDeclaration = nullptr;
12124
12125 // Obtain the array or member expression bases if required. Also, fill the
12126 // components array with all the components identified in the process.
Alexey Bataevb7a9b742017-12-05 19:20:09 +000012127 auto *BE = CheckMapClauseExpressionBase(SemaRef, SimpleExpr, CurComponents,
12128 CKind, /*NoDiagnose=*/false);
Samuel Antao5de996e2016-01-22 20:21:36 +000012129 if (!BE)
12130 continue;
12131
Samuel Antao90927002016-04-26 14:54:23 +000012132 assert(!CurComponents.empty() &&
12133 "Invalid mappable expression information.");
Kelvin Li0bff7af2015-11-23 05:32:03 +000012134
Samuel Antao90927002016-04-26 14:54:23 +000012135 // For the following checks, we rely on the base declaration which is
12136 // expected to be associated with the last component. The declaration is
12137 // expected to be a variable or a field (if 'this' is being mapped).
12138 CurDeclaration = CurComponents.back().getAssociatedDeclaration();
12139 assert(CurDeclaration && "Null decl on map clause.");
12140 assert(
12141 CurDeclaration->isCanonicalDecl() &&
12142 "Expecting components to have associated only canonical declarations.");
12143
12144 auto *VD = dyn_cast<VarDecl>(CurDeclaration);
12145 auto *FD = dyn_cast<FieldDecl>(CurDeclaration);
Samuel Antao5de996e2016-01-22 20:21:36 +000012146
12147 assert((VD || FD) && "Only variables or fields are expected here!");
NAKAMURA Takumi6dcb8142016-01-23 01:38:20 +000012148 (void)FD;
Samuel Antao5de996e2016-01-22 20:21:36 +000012149
12150 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.10]
Samuel Antao661c0902016-05-26 17:39:58 +000012151 // threadprivate variables cannot appear in a map clause.
12152 // OpenMP 4.5 [2.10.5, target update Construct]
12153 // threadprivate variables cannot appear in a from clause.
12154 if (VD && DSAS->isThreadPrivate(VD)) {
12155 auto DVar = DSAS->getTopDSA(VD, false);
12156 SemaRef.Diag(ELoc, diag::err_omp_threadprivate_in_clause)
12157 << getOpenMPClauseName(CKind);
12158 ReportOriginalDSA(SemaRef, DSAS, VD, DVar);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012159 continue;
12160 }
12161
Samuel Antao5de996e2016-01-22 20:21:36 +000012162 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
12163 // A list item cannot appear in both a map clause and a data-sharing
12164 // attribute clause on the same construct.
Kelvin Li0bff7af2015-11-23 05:32:03 +000012165
Samuel Antao5de996e2016-01-22 20:21:36 +000012166 // Check conflicts with other map clause expressions. We check the conflicts
12167 // with the current construct separately from the enclosing data
Samuel Antao661c0902016-05-26 17:39:58 +000012168 // environment, because the restrictions are different. We only have to
12169 // check conflicts across regions for the map clauses.
12170 if (CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12171 /*CurrentRegionOnly=*/true, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000012172 break;
Samuel Antao661c0902016-05-26 17:39:58 +000012173 if (CKind == OMPC_map &&
12174 CheckMapConflicts(SemaRef, DSAS, CurDeclaration, SimpleExpr,
12175 /*CurrentRegionOnly=*/false, CurComponents, CKind))
Samuel Antao5de996e2016-01-22 20:21:36 +000012176 break;
Kelvin Li0bff7af2015-11-23 05:32:03 +000012177
Samuel Antao661c0902016-05-26 17:39:58 +000012178 // OpenMP 4.5 [2.10.5, target update Construct]
Samuel Antao5de996e2016-01-22 20:21:36 +000012179 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, C++, p.1]
12180 // If the type of a list item is a reference to a type T then the type will
12181 // be considered to be T for all purposes of this clause.
Samuel Antao90927002016-04-26 14:54:23 +000012182 QualType Type = CurDeclaration->getType().getNonReferenceType();
Samuel Antao5de996e2016-01-22 20:21:36 +000012183
Samuel Antao661c0902016-05-26 17:39:58 +000012184 // OpenMP 4.5 [2.10.5, target update Construct, Restrictions, p.4]
12185 // A list item in a to or from clause must have a mappable type.
Samuel Antao5de996e2016-01-22 20:21:36 +000012186 // OpenMP 4.5 [2.15.5.1, map Clause, Restrictions, p.9]
Kelvin Li0bff7af2015-11-23 05:32:03 +000012187 // A list item must have a mappable type.
Samuel Antao661c0902016-05-26 17:39:58 +000012188 if (!CheckTypeMappable(VE->getExprLoc(), VE->getSourceRange(), SemaRef,
12189 DSAS, Type))
Kelvin Li0bff7af2015-11-23 05:32:03 +000012190 continue;
12191
Samuel Antao661c0902016-05-26 17:39:58 +000012192 if (CKind == OMPC_map) {
12193 // target enter data
12194 // OpenMP [2.10.2, Restrictions, p. 99]
12195 // A map-type must be specified in all map clauses and must be either
12196 // to or alloc.
12197 OpenMPDirectiveKind DKind = DSAS->getCurrentDirective();
12198 if (DKind == OMPD_target_enter_data &&
12199 !(MapType == OMPC_MAP_to || MapType == OMPC_MAP_alloc)) {
12200 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12201 << (IsMapTypeImplicit ? 1 : 0)
12202 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12203 << getOpenMPDirectiveName(DKind);
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012204 continue;
12205 }
Samuel Antao661c0902016-05-26 17:39:58 +000012206
12207 // target exit_data
12208 // OpenMP [2.10.3, Restrictions, p. 102]
12209 // A map-type must be specified in all map clauses and must be either
12210 // from, release, or delete.
12211 if (DKind == OMPD_target_exit_data &&
12212 !(MapType == OMPC_MAP_from || MapType == OMPC_MAP_release ||
12213 MapType == OMPC_MAP_delete)) {
12214 SemaRef.Diag(StartLoc, diag::err_omp_invalid_map_type_for_directive)
12215 << (IsMapTypeImplicit ? 1 : 0)
12216 << getOpenMPSimpleClauseTypeName(OMPC_map, MapType)
12217 << getOpenMPDirectiveName(DKind);
12218 continue;
12219 }
12220
12221 // OpenMP 4.5 [2.15.5.1, Restrictions, p.3]
12222 // A list item cannot appear in both a map clause and a data-sharing
12223 // attribute clause on the same construct
Kelvin Li83c451e2016-12-25 04:52:54 +000012224 if ((DKind == OMPD_target || DKind == OMPD_target_teams ||
Kelvin Li80e8f562016-12-29 22:16:30 +000012225 DKind == OMPD_target_teams_distribute ||
Kelvin Li1851df52017-01-03 05:23:48 +000012226 DKind == OMPD_target_teams_distribute_parallel_for ||
Kelvin Lida681182017-01-10 18:08:18 +000012227 DKind == OMPD_target_teams_distribute_parallel_for_simd ||
12228 DKind == OMPD_target_teams_distribute_simd) && VD) {
Samuel Antao661c0902016-05-26 17:39:58 +000012229 auto DVar = DSAS->getTopDSA(VD, false);
12230 if (isOpenMPPrivate(DVar.CKind)) {
Samuel Antao6890b092016-07-28 14:25:09 +000012231 SemaRef.Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
Samuel Antao661c0902016-05-26 17:39:58 +000012232 << getOpenMPClauseName(DVar.CKind)
Samuel Antao6890b092016-07-28 14:25:09 +000012233 << getOpenMPClauseName(OMPC_map)
Samuel Antao661c0902016-05-26 17:39:58 +000012234 << getOpenMPDirectiveName(DSAS->getCurrentDirective());
12235 ReportOriginalDSA(SemaRef, DSAS, CurDeclaration, DVar);
12236 continue;
12237 }
12238 }
Carlo Bertollib74bfc82016-03-18 21:43:32 +000012239 }
12240
Samuel Antao90927002016-04-26 14:54:23 +000012241 // Save the current expression.
Samuel Antao661c0902016-05-26 17:39:58 +000012242 MVLI.ProcessedVarList.push_back(RE);
Samuel Antao90927002016-04-26 14:54:23 +000012243
12244 // Store the components in the stack so that they can be used to check
12245 // against other clauses later on.
Samuel Antao6890b092016-07-28 14:25:09 +000012246 DSAS->addMappableExpressionComponents(CurDeclaration, CurComponents,
12247 /*WhereFoundClauseKind=*/OMPC_map);
Samuel Antao90927002016-04-26 14:54:23 +000012248
12249 // Save the components and declaration to create the clause. For purposes of
12250 // the clause creation, any component list that has has base 'this' uses
Samuel Antao686c70c2016-05-26 17:30:50 +000012251 // null as base declaration.
Samuel Antao661c0902016-05-26 17:39:58 +000012252 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
12253 MVLI.VarComponents.back().append(CurComponents.begin(),
12254 CurComponents.end());
12255 MVLI.VarBaseDeclarations.push_back(isa<MemberExpr>(BE) ? nullptr
12256 : CurDeclaration);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012257 }
Samuel Antao661c0902016-05-26 17:39:58 +000012258}
12259
12260OMPClause *
12261Sema::ActOnOpenMPMapClause(OpenMPMapClauseKind MapTypeModifier,
12262 OpenMPMapClauseKind MapType, bool IsMapTypeImplicit,
12263 SourceLocation MapLoc, SourceLocation ColonLoc,
12264 ArrayRef<Expr *> VarList, SourceLocation StartLoc,
12265 SourceLocation LParenLoc, SourceLocation EndLoc) {
12266 MappableVarListInfo MVLI(VarList);
12267 checkMappableExpressionList(*this, DSAStack, OMPC_map, MVLI, StartLoc,
12268 MapType, IsMapTypeImplicit);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012269
Samuel Antao5de996e2016-01-22 20:21:36 +000012270 // We need to produce a map clause even if we don't have variables so that
12271 // other diagnostics related with non-existing map clauses are accurate.
Samuel Antao661c0902016-05-26 17:39:58 +000012272 return OMPMapClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12273 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12274 MVLI.VarComponents, MapTypeModifier, MapType,
12275 IsMapTypeImplicit, MapLoc);
Kelvin Li0bff7af2015-11-23 05:32:03 +000012276}
Kelvin Li099bb8c2015-11-24 20:50:12 +000012277
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012278QualType Sema::ActOnOpenMPDeclareReductionType(SourceLocation TyLoc,
12279 TypeResult ParsedType) {
12280 assert(ParsedType.isUsable());
12281
12282 QualType ReductionType = GetTypeFromParser(ParsedType.get());
12283 if (ReductionType.isNull())
12284 return QualType();
12285
12286 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions, C\C++
12287 // A type name in a declare reduction directive cannot be a function type, an
12288 // array type, a reference type, or a type qualified with const, volatile or
12289 // restrict.
12290 if (ReductionType.hasQualifiers()) {
12291 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 0;
12292 return QualType();
12293 }
12294
12295 if (ReductionType->isFunctionType()) {
12296 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 1;
12297 return QualType();
12298 }
12299 if (ReductionType->isReferenceType()) {
12300 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 2;
12301 return QualType();
12302 }
12303 if (ReductionType->isArrayType()) {
12304 Diag(TyLoc, diag::err_omp_reduction_wrong_type) << 3;
12305 return QualType();
12306 }
12307 return ReductionType;
12308}
12309
12310Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveStart(
12311 Scope *S, DeclContext *DC, DeclarationName Name,
12312 ArrayRef<std::pair<QualType, SourceLocation>> ReductionTypes,
12313 AccessSpecifier AS, Decl *PrevDeclInScope) {
12314 SmallVector<Decl *, 8> Decls;
12315 Decls.reserve(ReductionTypes.size());
12316
12317 LookupResult Lookup(*this, Name, SourceLocation(), LookupOMPReductionName,
Richard Smithbecb92d2017-10-10 22:33:17 +000012318 forRedeclarationInCurContext());
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012319 // [OpenMP 4.0], 2.15 declare reduction Directive, Restrictions
12320 // A reduction-identifier may not be re-declared in the current scope for the
12321 // same type or for a type that is compatible according to the base language
12322 // rules.
12323 llvm::DenseMap<QualType, SourceLocation> PreviousRedeclTypes;
12324 OMPDeclareReductionDecl *PrevDRD = nullptr;
12325 bool InCompoundScope = true;
12326 if (S != nullptr) {
12327 // Find previous declaration with the same name not referenced in other
12328 // declarations.
12329 FunctionScopeInfo *ParentFn = getEnclosingFunction();
12330 InCompoundScope =
12331 (ParentFn != nullptr) && !ParentFn->CompoundScopes.empty();
12332 LookupName(Lookup, S);
12333 FilterLookupForScope(Lookup, DC, S, /*ConsiderLinkage=*/false,
12334 /*AllowInlineNamespace=*/false);
12335 llvm::DenseMap<OMPDeclareReductionDecl *, bool> UsedAsPrevious;
12336 auto Filter = Lookup.makeFilter();
12337 while (Filter.hasNext()) {
12338 auto *PrevDecl = cast<OMPDeclareReductionDecl>(Filter.next());
12339 if (InCompoundScope) {
12340 auto I = UsedAsPrevious.find(PrevDecl);
12341 if (I == UsedAsPrevious.end())
12342 UsedAsPrevious[PrevDecl] = false;
12343 if (auto *D = PrevDecl->getPrevDeclInScope())
12344 UsedAsPrevious[D] = true;
12345 }
12346 PreviousRedeclTypes[PrevDecl->getType().getCanonicalType()] =
12347 PrevDecl->getLocation();
12348 }
12349 Filter.done();
12350 if (InCompoundScope) {
12351 for (auto &PrevData : UsedAsPrevious) {
12352 if (!PrevData.second) {
12353 PrevDRD = PrevData.first;
12354 break;
12355 }
12356 }
12357 }
12358 } else if (PrevDeclInScope != nullptr) {
12359 auto *PrevDRDInScope = PrevDRD =
12360 cast<OMPDeclareReductionDecl>(PrevDeclInScope);
12361 do {
12362 PreviousRedeclTypes[PrevDRDInScope->getType().getCanonicalType()] =
12363 PrevDRDInScope->getLocation();
12364 PrevDRDInScope = PrevDRDInScope->getPrevDeclInScope();
12365 } while (PrevDRDInScope != nullptr);
12366 }
12367 for (auto &TyData : ReductionTypes) {
12368 auto I = PreviousRedeclTypes.find(TyData.first.getCanonicalType());
12369 bool Invalid = false;
12370 if (I != PreviousRedeclTypes.end()) {
12371 Diag(TyData.second, diag::err_omp_declare_reduction_redefinition)
12372 << TyData.first;
12373 Diag(I->second, diag::note_previous_definition);
12374 Invalid = true;
12375 }
12376 PreviousRedeclTypes[TyData.first.getCanonicalType()] = TyData.second;
12377 auto *DRD = OMPDeclareReductionDecl::Create(Context, DC, TyData.second,
12378 Name, TyData.first, PrevDRD);
12379 DC->addDecl(DRD);
12380 DRD->setAccess(AS);
12381 Decls.push_back(DRD);
12382 if (Invalid)
12383 DRD->setInvalidDecl();
12384 else
12385 PrevDRD = DRD;
12386 }
12387
12388 return DeclGroupPtrTy::make(
12389 DeclGroupRef::Create(Context, Decls.begin(), Decls.size()));
12390}
12391
12392void Sema::ActOnOpenMPDeclareReductionCombinerStart(Scope *S, Decl *D) {
12393 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12394
12395 // Enter new function scope.
12396 PushFunctionScope();
12397 getCurFunction()->setHasBranchProtectedScope();
12398 getCurFunction()->setHasOMPDeclareReductionCombiner();
12399
12400 if (S != nullptr)
12401 PushDeclContext(S, DRD);
12402 else
12403 CurContext = DRD;
12404
Faisal Valid143a0c2017-04-01 21:30:49 +000012405 PushExpressionEvaluationContext(
12406 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012407
12408 QualType ReductionType = DRD->getType();
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012409 // Create 'T* omp_parm;T omp_in;'. All references to 'omp_in' will
12410 // be replaced by '*omp_parm' during codegen. This required because 'omp_in'
12411 // uses semantics of argument handles by value, but it should be passed by
12412 // reference. C lang does not support references, so pass all parameters as
12413 // pointers.
12414 // Create 'T omp_in;' variable.
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012415 auto *OmpInParm =
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012416 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_in");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012417 // Create 'T* omp_parm;T omp_out;'. All references to 'omp_out' will
12418 // be replaced by '*omp_parm' during codegen. This required because 'omp_out'
12419 // uses semantics of argument handles by value, but it should be passed by
12420 // reference. C lang does not support references, so pass all parameters as
12421 // pointers.
12422 // Create 'T omp_out;' variable.
12423 auto *OmpOutParm =
12424 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_out");
12425 if (S != nullptr) {
12426 PushOnScopeChains(OmpInParm, S);
12427 PushOnScopeChains(OmpOutParm, S);
12428 } else {
12429 DRD->addDecl(OmpInParm);
12430 DRD->addDecl(OmpOutParm);
12431 }
12432}
12433
12434void Sema::ActOnOpenMPDeclareReductionCombinerEnd(Decl *D, Expr *Combiner) {
12435 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12436 DiscardCleanupsInEvaluationContext();
12437 PopExpressionEvaluationContext();
12438
12439 PopDeclContext();
12440 PopFunctionScopeInfo();
12441
12442 if (Combiner != nullptr)
12443 DRD->setCombiner(Combiner);
12444 else
12445 DRD->setInvalidDecl();
12446}
12447
Alexey Bataev070f43a2017-09-06 14:49:58 +000012448VarDecl *Sema::ActOnOpenMPDeclareReductionInitializerStart(Scope *S, Decl *D) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012449 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12450
12451 // Enter new function scope.
12452 PushFunctionScope();
12453 getCurFunction()->setHasBranchProtectedScope();
12454
12455 if (S != nullptr)
12456 PushDeclContext(S, DRD);
12457 else
12458 CurContext = DRD;
12459
Faisal Valid143a0c2017-04-01 21:30:49 +000012460 PushExpressionEvaluationContext(
12461 ExpressionEvaluationContext::PotentiallyEvaluated);
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012462
12463 QualType ReductionType = DRD->getType();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012464 // Create 'T* omp_parm;T omp_priv;'. All references to 'omp_priv' will
12465 // be replaced by '*omp_parm' during codegen. This required because 'omp_priv'
12466 // uses semantics of argument handles by value, but it should be passed by
12467 // reference. C lang does not support references, so pass all parameters as
12468 // pointers.
12469 // Create 'T omp_priv;' variable.
12470 auto *OmpPrivParm =
12471 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_priv");
Alexey Bataeva839ddd2016-03-17 10:19:46 +000012472 // Create 'T* omp_parm;T omp_orig;'. All references to 'omp_orig' will
12473 // be replaced by '*omp_parm' during codegen. This required because 'omp_orig'
12474 // uses semantics of argument handles by value, but it should be passed by
12475 // reference. C lang does not support references, so pass all parameters as
12476 // pointers.
12477 // Create 'T omp_orig;' variable.
12478 auto *OmpOrigParm =
12479 buildVarDecl(*this, D->getLocation(), ReductionType, "omp_orig");
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012480 if (S != nullptr) {
12481 PushOnScopeChains(OmpPrivParm, S);
12482 PushOnScopeChains(OmpOrigParm, S);
12483 } else {
12484 DRD->addDecl(OmpPrivParm);
12485 DRD->addDecl(OmpOrigParm);
12486 }
Alexey Bataev070f43a2017-09-06 14:49:58 +000012487 return OmpPrivParm;
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012488}
12489
Alexey Bataev070f43a2017-09-06 14:49:58 +000012490void Sema::ActOnOpenMPDeclareReductionInitializerEnd(Decl *D, Expr *Initializer,
12491 VarDecl *OmpPrivParm) {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012492 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12493 DiscardCleanupsInEvaluationContext();
12494 PopExpressionEvaluationContext();
12495
12496 PopDeclContext();
12497 PopFunctionScopeInfo();
12498
Alexey Bataev070f43a2017-09-06 14:49:58 +000012499 if (Initializer != nullptr) {
12500 DRD->setInitializer(Initializer, OMPDeclareReductionDecl::CallInit);
12501 } else if (OmpPrivParm->hasInit()) {
12502 DRD->setInitializer(OmpPrivParm->getInit(),
12503 OmpPrivParm->isDirectInit()
12504 ? OMPDeclareReductionDecl::DirectInit
12505 : OMPDeclareReductionDecl::CopyInit);
12506 } else {
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012507 DRD->setInvalidDecl();
Alexey Bataev070f43a2017-09-06 14:49:58 +000012508 }
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000012509}
12510
12511Sema::DeclGroupPtrTy Sema::ActOnOpenMPDeclareReductionDirectiveEnd(
12512 Scope *S, DeclGroupPtrTy DeclReductions, bool IsValid) {
12513 for (auto *D : DeclReductions.get()) {
12514 if (IsValid) {
12515 auto *DRD = cast<OMPDeclareReductionDecl>(D);
12516 if (S != nullptr)
12517 PushOnScopeChains(DRD, S, /*AddToContext=*/false);
12518 } else
12519 D->setInvalidDecl();
12520 }
12521 return DeclReductions;
12522}
12523
David Majnemer9d168222016-08-05 17:44:54 +000012524OMPClause *Sema::ActOnOpenMPNumTeamsClause(Expr *NumTeams,
Kelvin Li099bb8c2015-11-24 20:50:12 +000012525 SourceLocation StartLoc,
12526 SourceLocation LParenLoc,
12527 SourceLocation EndLoc) {
12528 Expr *ValExpr = NumTeams;
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012529 Stmt *HelperValStmt = nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012530
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012531 // OpenMP [teams Constrcut, Restrictions]
12532 // The num_teams expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012533 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_teams,
12534 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012535 return nullptr;
Kelvin Li099bb8c2015-11-24 20:50:12 +000012536
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012537 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012538 OpenMPDirectiveKind CaptureRegion =
12539 getOpenMPCaptureRegionForClause(DKind, OMPC_num_teams);
12540 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012541 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacobbc126342017-01-25 11:28:18 +000012542 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12543 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12544 HelperValStmt = buildPreInits(Context, Captures);
12545 }
12546
12547 return new (Context) OMPNumTeamsClause(ValExpr, HelperValStmt, CaptureRegion,
12548 StartLoc, LParenLoc, EndLoc);
Kelvin Li099bb8c2015-11-24 20:50:12 +000012549}
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012550
12551OMPClause *Sema::ActOnOpenMPThreadLimitClause(Expr *ThreadLimit,
12552 SourceLocation StartLoc,
12553 SourceLocation LParenLoc,
12554 SourceLocation EndLoc) {
12555 Expr *ValExpr = ThreadLimit;
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012556 Stmt *HelperValStmt = nullptr;
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012557
12558 // OpenMP [teams Constrcut, Restrictions]
12559 // The thread_limit expression must evaluate to a positive integer value.
Alexey Bataeva0569352015-12-01 10:17:31 +000012560 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_thread_limit,
12561 /*StrictlyPositive=*/true))
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012562 return nullptr;
12563
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012564 OpenMPDirectiveKind DKind = DSAStack->getCurrentDirective();
Alexey Bataev2ba67042017-11-28 21:11:44 +000012565 OpenMPDirectiveKind CaptureRegion =
12566 getOpenMPCaptureRegionForClause(DKind, OMPC_thread_limit);
12567 if (CaptureRegion != OMPD_unknown && !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012568 ValExpr = MakeFullExpr(ValExpr).get();
Arpith Chacko Jacob7ecc0b72017-01-25 11:44:35 +000012569 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12570 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12571 HelperValStmt = buildPreInits(Context, Captures);
12572 }
12573
12574 return new (Context) OMPThreadLimitClause(
12575 ValExpr, HelperValStmt, CaptureRegion, StartLoc, LParenLoc, EndLoc);
Kelvin Lia15fb1a2015-11-27 18:47:36 +000012576}
Alexey Bataeva0569352015-12-01 10:17:31 +000012577
12578OMPClause *Sema::ActOnOpenMPPriorityClause(Expr *Priority,
12579 SourceLocation StartLoc,
12580 SourceLocation LParenLoc,
12581 SourceLocation EndLoc) {
12582 Expr *ValExpr = Priority;
12583
12584 // OpenMP [2.9.1, task Constrcut]
12585 // The priority-value is a non-negative numerical scalar expression.
12586 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_priority,
12587 /*StrictlyPositive=*/false))
12588 return nullptr;
12589
12590 return new (Context) OMPPriorityClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12591}
Alexey Bataev1fd4aed2015-12-07 12:52:51 +000012592
12593OMPClause *Sema::ActOnOpenMPGrainsizeClause(Expr *Grainsize,
12594 SourceLocation StartLoc,
12595 SourceLocation LParenLoc,
12596 SourceLocation EndLoc) {
12597 Expr *ValExpr = Grainsize;
12598
12599 // OpenMP [2.9.2, taskloop Constrcut]
12600 // The parameter of the grainsize clause must be a positive integer
12601 // expression.
12602 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_grainsize,
12603 /*StrictlyPositive=*/true))
12604 return nullptr;
12605
12606 return new (Context) OMPGrainsizeClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12607}
Alexey Bataev382967a2015-12-08 12:06:20 +000012608
12609OMPClause *Sema::ActOnOpenMPNumTasksClause(Expr *NumTasks,
12610 SourceLocation StartLoc,
12611 SourceLocation LParenLoc,
12612 SourceLocation EndLoc) {
12613 Expr *ValExpr = NumTasks;
12614
12615 // OpenMP [2.9.2, taskloop Constrcut]
12616 // The parameter of the num_tasks clause must be a positive integer
12617 // expression.
12618 if (!IsNonNegativeIntegerValue(ValExpr, *this, OMPC_num_tasks,
12619 /*StrictlyPositive=*/true))
12620 return nullptr;
12621
12622 return new (Context) OMPNumTasksClause(ValExpr, StartLoc, LParenLoc, EndLoc);
12623}
12624
Alexey Bataev28c75412015-12-15 08:19:24 +000012625OMPClause *Sema::ActOnOpenMPHintClause(Expr *Hint, SourceLocation StartLoc,
12626 SourceLocation LParenLoc,
12627 SourceLocation EndLoc) {
12628 // OpenMP [2.13.2, critical construct, Description]
12629 // ... where hint-expression is an integer constant expression that evaluates
12630 // to a valid lock hint.
12631 ExprResult HintExpr = VerifyPositiveIntegerConstantInClause(Hint, OMPC_hint);
12632 if (HintExpr.isInvalid())
12633 return nullptr;
12634 return new (Context)
12635 OMPHintClause(HintExpr.get(), StartLoc, LParenLoc, EndLoc);
12636}
12637
Carlo Bertollib4adf552016-01-15 18:50:31 +000012638OMPClause *Sema::ActOnOpenMPDistScheduleClause(
12639 OpenMPDistScheduleClauseKind Kind, Expr *ChunkSize, SourceLocation StartLoc,
12640 SourceLocation LParenLoc, SourceLocation KindLoc, SourceLocation CommaLoc,
12641 SourceLocation EndLoc) {
12642 if (Kind == OMPC_DIST_SCHEDULE_unknown) {
12643 std::string Values;
12644 Values += "'";
12645 Values += getOpenMPSimpleClauseTypeName(OMPC_dist_schedule, 0);
12646 Values += "'";
12647 Diag(KindLoc, diag::err_omp_unexpected_clause_value)
12648 << Values << getOpenMPClauseName(OMPC_dist_schedule);
12649 return nullptr;
12650 }
12651 Expr *ValExpr = ChunkSize;
Alexey Bataev3392d762016-02-16 11:18:12 +000012652 Stmt *HelperValStmt = nullptr;
Carlo Bertollib4adf552016-01-15 18:50:31 +000012653 if (ChunkSize) {
12654 if (!ChunkSize->isValueDependent() && !ChunkSize->isTypeDependent() &&
12655 !ChunkSize->isInstantiationDependent() &&
12656 !ChunkSize->containsUnexpandedParameterPack()) {
12657 SourceLocation ChunkSizeLoc = ChunkSize->getLocStart();
12658 ExprResult Val =
12659 PerformOpenMPImplicitIntegerConversion(ChunkSizeLoc, ChunkSize);
12660 if (Val.isInvalid())
12661 return nullptr;
12662
12663 ValExpr = Val.get();
12664
12665 // OpenMP [2.7.1, Restrictions]
12666 // chunk_size must be a loop invariant integer expression with a positive
12667 // value.
12668 llvm::APSInt Result;
12669 if (ValExpr->isIntegerConstantExpr(Result, Context)) {
12670 if (Result.isSigned() && !Result.isStrictlyPositive()) {
12671 Diag(ChunkSizeLoc, diag::err_omp_negative_expression_in_clause)
12672 << "dist_schedule" << ChunkSize->getSourceRange();
12673 return nullptr;
12674 }
Alexey Bataev2ba67042017-11-28 21:11:44 +000012675 } else if (getOpenMPCaptureRegionForClause(
12676 DSAStack->getCurrentDirective(), OMPC_dist_schedule) !=
12677 OMPD_unknown &&
Alexey Bataevb46cdea2016-06-15 11:20:48 +000012678 !CurContext->isDependentContext()) {
Alexey Bataev8e769ee2017-12-22 21:01:52 +000012679 ValExpr = MakeFullExpr(ValExpr).get();
Alexey Bataev5a3af132016-03-29 08:58:54 +000012680 llvm::MapVector<Expr *, DeclRefExpr *> Captures;
12681 ValExpr = tryBuildCapture(*this, ValExpr, Captures).get();
12682 HelperValStmt = buildPreInits(Context, Captures);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012683 }
12684 }
12685 }
12686
12687 return new (Context)
12688 OMPDistScheduleClause(StartLoc, LParenLoc, KindLoc, CommaLoc, EndLoc,
Alexey Bataev3392d762016-02-16 11:18:12 +000012689 Kind, ValExpr, HelperValStmt);
Carlo Bertollib4adf552016-01-15 18:50:31 +000012690}
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012691
12692OMPClause *Sema::ActOnOpenMPDefaultmapClause(
12693 OpenMPDefaultmapClauseModifier M, OpenMPDefaultmapClauseKind Kind,
12694 SourceLocation StartLoc, SourceLocation LParenLoc, SourceLocation MLoc,
12695 SourceLocation KindLoc, SourceLocation EndLoc) {
12696 // OpenMP 4.5 only supports 'defaultmap(tofrom: scalar)'
David Majnemer9d168222016-08-05 17:44:54 +000012697 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom || Kind != OMPC_DEFAULTMAP_scalar) {
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012698 std::string Value;
12699 SourceLocation Loc;
12700 Value += "'";
12701 if (M != OMPC_DEFAULTMAP_MODIFIER_tofrom) {
12702 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012703 OMPC_DEFAULTMAP_MODIFIER_tofrom);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012704 Loc = MLoc;
12705 } else {
12706 Value += getOpenMPSimpleClauseTypeName(OMPC_defaultmap,
David Majnemer9d168222016-08-05 17:44:54 +000012707 OMPC_DEFAULTMAP_scalar);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012708 Loc = KindLoc;
12709 }
12710 Value += "'";
12711 Diag(Loc, diag::err_omp_unexpected_clause_value)
12712 << Value << getOpenMPClauseName(OMPC_defaultmap);
12713 return nullptr;
12714 }
Alexey Bataev2fd0cb22017-10-05 17:51:39 +000012715 DSAStack->setDefaultDMAToFromScalar(StartLoc);
Arpith Chacko Jacob3cf89042016-01-26 16:37:23 +000012716
12717 return new (Context)
12718 OMPDefaultmapClause(StartLoc, LParenLoc, MLoc, KindLoc, EndLoc, Kind, M);
12719}
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012720
12721bool Sema::ActOnStartOpenMPDeclareTargetDirective(SourceLocation Loc) {
12722 DeclContext *CurLexicalContext = getCurLexicalContext();
12723 if (!CurLexicalContext->isFileContext() &&
12724 !CurLexicalContext->isExternCContext() &&
Alexey Bataev502ec492017-10-03 20:00:00 +000012725 !CurLexicalContext->isExternCXXContext() &&
12726 !isa<CXXRecordDecl>(CurLexicalContext) &&
12727 !isa<ClassTemplateDecl>(CurLexicalContext) &&
12728 !isa<ClassTemplatePartialSpecializationDecl>(CurLexicalContext) &&
12729 !isa<ClassTemplateSpecializationDecl>(CurLexicalContext)) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012730 Diag(Loc, diag::err_omp_region_not_file_context);
12731 return false;
12732 }
12733 if (IsInOpenMPDeclareTargetContext) {
12734 Diag(Loc, diag::err_omp_enclosed_declare_target);
12735 return false;
12736 }
12737
12738 IsInOpenMPDeclareTargetContext = true;
12739 return true;
12740}
12741
12742void Sema::ActOnFinishOpenMPDeclareTargetDirective() {
12743 assert(IsInOpenMPDeclareTargetContext &&
12744 "Unexpected ActOnFinishOpenMPDeclareTargetDirective");
12745
12746 IsInOpenMPDeclareTargetContext = false;
12747}
12748
David Majnemer9d168222016-08-05 17:44:54 +000012749void Sema::ActOnOpenMPDeclareTargetName(Scope *CurScope,
12750 CXXScopeSpec &ScopeSpec,
12751 const DeclarationNameInfo &Id,
12752 OMPDeclareTargetDeclAttr::MapTypeTy MT,
12753 NamedDeclSetType &SameDirectiveDecls) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012754 LookupResult Lookup(*this, Id, LookupOrdinaryName);
12755 LookupParsedName(Lookup, CurScope, &ScopeSpec, true);
12756
12757 if (Lookup.isAmbiguous())
12758 return;
12759 Lookup.suppressDiagnostics();
12760
12761 if (!Lookup.isSingleResult()) {
12762 if (TypoCorrection Corrected =
12763 CorrectTypo(Id, LookupOrdinaryName, CurScope, nullptr,
12764 llvm::make_unique<VarOrFuncDeclFilterCCC>(*this),
12765 CTK_ErrorRecovery)) {
12766 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_var_use_suggest)
12767 << Id.getName());
12768 checkDeclIsAllowedInOpenMPTarget(nullptr, Corrected.getCorrectionDecl());
12769 return;
12770 }
12771
12772 Diag(Id.getLoc(), diag::err_undeclared_var_use) << Id.getName();
12773 return;
12774 }
12775
12776 NamedDecl *ND = Lookup.getAsSingle<NamedDecl>();
12777 if (isa<VarDecl>(ND) || isa<FunctionDecl>(ND)) {
12778 if (!SameDirectiveDecls.insert(cast<NamedDecl>(ND->getCanonicalDecl())))
12779 Diag(Id.getLoc(), diag::err_omp_declare_target_multiple) << Id.getName();
12780
12781 if (!ND->hasAttr<OMPDeclareTargetDeclAttr>()) {
12782 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(Context, MT);
12783 ND->addAttr(A);
12784 if (ASTMutationListener *ML = Context.getASTMutationListener())
12785 ML->DeclarationMarkedOpenMPDeclareTarget(ND, A);
Kelvin Li1ce87c72017-12-12 20:08:12 +000012786 checkDeclIsAllowedInOpenMPTarget(nullptr, ND, Id.getLoc());
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012787 } else if (ND->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() != MT) {
12788 Diag(Id.getLoc(), diag::err_omp_declare_target_to_and_link)
12789 << Id.getName();
12790 }
12791 } else
12792 Diag(Id.getLoc(), diag::err_omp_invalid_target_decl) << Id.getName();
12793}
12794
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012795static void checkDeclInTargetContext(SourceLocation SL, SourceRange SR,
12796 Sema &SemaRef, Decl *D) {
12797 if (!D)
12798 return;
12799 Decl *LD = nullptr;
12800 if (isa<TagDecl>(D)) {
12801 LD = cast<TagDecl>(D)->getDefinition();
12802 } else if (isa<VarDecl>(D)) {
12803 LD = cast<VarDecl>(D)->getDefinition();
12804
12805 // If this is an implicit variable that is legal and we do not need to do
12806 // anything.
12807 if (cast<VarDecl>(D)->isImplicit()) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012808 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12809 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12810 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012811 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012812 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012813 return;
12814 }
12815
12816 } else if (isa<FunctionDecl>(D)) {
12817 const FunctionDecl *FD = nullptr;
12818 if (cast<FunctionDecl>(D)->hasBody(FD))
12819 LD = const_cast<FunctionDecl *>(FD);
12820
12821 // If the definition is associated with the current declaration in the
12822 // target region (it can be e.g. a lambda) that is legal and we do not need
12823 // to do anything else.
12824 if (LD == D) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012825 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12826 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12827 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012828 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012829 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012830 return;
12831 }
12832 }
12833 if (!LD)
12834 LD = D;
12835 if (LD && !LD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12836 (isa<VarDecl>(LD) || isa<FunctionDecl>(LD))) {
12837 // Outlined declaration is not declared target.
12838 if (LD->isOutOfLine()) {
12839 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12840 SemaRef.Diag(SL, diag::note_used_here) << SR;
12841 } else {
12842 DeclContext *DC = LD->getDeclContext();
12843 while (DC) {
12844 if (isa<FunctionDecl>(DC) &&
12845 cast<FunctionDecl>(DC)->hasAttr<OMPDeclareTargetDeclAttr>())
12846 break;
12847 DC = DC->getParent();
12848 }
12849 if (DC)
12850 return;
12851
12852 // Is not declared in target context.
12853 SemaRef.Diag(LD->getLocation(), diag::warn_omp_not_in_target_context);
12854 SemaRef.Diag(SL, diag::note_used_here) << SR;
12855 }
12856 // Mark decl as declared target to prevent further diagnostic.
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012857 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12858 SemaRef.Context, OMPDeclareTargetDeclAttr::MT_To);
12859 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012860 if (ASTMutationListener *ML = SemaRef.Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012861 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012862 }
12863}
12864
12865static bool checkValueDeclInTarget(SourceLocation SL, SourceRange SR,
12866 Sema &SemaRef, DSAStackTy *Stack,
12867 ValueDecl *VD) {
12868 if (VD->hasAttr<OMPDeclareTargetDeclAttr>())
12869 return true;
12870 if (!CheckTypeMappable(SL, SR, SemaRef, Stack, VD->getType()))
12871 return false;
12872 return true;
12873}
12874
Kelvin Li1ce87c72017-12-12 20:08:12 +000012875void Sema::checkDeclIsAllowedInOpenMPTarget(Expr *E, Decl *D,
12876 SourceLocation IdLoc) {
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012877 if (!D || D->isInvalidDecl())
12878 return;
12879 SourceRange SR = E ? E->getSourceRange() : D->getSourceRange();
12880 SourceLocation SL = E ? E->getLocStart() : D->getLocation();
12881 // 2.10.6: threadprivate variable cannot appear in a declare target directive.
12882 if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
12883 if (DSAStack->isThreadPrivate(VD)) {
12884 Diag(SL, diag::err_omp_threadprivate_in_target);
12885 ReportOriginalDSA(*this, DSAStack, VD, DSAStack->getTopDSA(VD, false));
12886 return;
12887 }
12888 }
12889 if (ValueDecl *VD = dyn_cast<ValueDecl>(D)) {
12890 // Problem if any with var declared with incomplete type will be reported
12891 // as normal, so no need to check it here.
12892 if ((E || !VD->getType()->isIncompleteType()) &&
12893 !checkValueDeclInTarget(SL, SR, *this, DSAStack, VD)) {
12894 // Mark decl as declared target to prevent further diagnostic.
12895 if (isa<VarDecl>(VD) || isa<FunctionDecl>(VD)) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012896 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12897 Context, OMPDeclareTargetDeclAttr::MT_To);
12898 VD->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012899 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012900 ML->DeclarationMarkedOpenMPDeclareTarget(VD, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012901 }
12902 return;
12903 }
12904 }
Kelvin Li1ce87c72017-12-12 20:08:12 +000012905 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
12906 if (FD->hasAttr<OMPDeclareTargetDeclAttr>() &&
12907 (FD->getAttr<OMPDeclareTargetDeclAttr>()->getMapType() ==
12908 OMPDeclareTargetDeclAttr::MT_Link)) {
12909 assert(IdLoc.isValid() && "Source location is expected");
12910 Diag(IdLoc, diag::err_omp_function_in_link_clause);
12911 Diag(FD->getLocation(), diag::note_defined_here) << FD;
12912 return;
12913 }
12914 }
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012915 if (!E) {
12916 // Checking declaration inside declare target region.
12917 if (!D->hasAttr<OMPDeclareTargetDeclAttr>() &&
12918 (isa<VarDecl>(D) || isa<FunctionDecl>(D))) {
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012919 Attr *A = OMPDeclareTargetDeclAttr::CreateImplicit(
12920 Context, OMPDeclareTargetDeclAttr::MT_To);
12921 D->addAttr(A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012922 if (ASTMutationListener *ML = Context.getASTMutationListener())
Dmitry Polukhind69b5052016-05-09 14:59:13 +000012923 ML->DeclarationMarkedOpenMPDeclareTarget(D, A);
Dmitry Polukhin0b0da292016-04-06 11:38:59 +000012924 }
12925 return;
12926 }
12927 checkDeclInTargetContext(E->getExprLoc(), E->getSourceRange(), *this, D);
12928}
Samuel Antao661c0902016-05-26 17:39:58 +000012929
12930OMPClause *Sema::ActOnOpenMPToClause(ArrayRef<Expr *> VarList,
12931 SourceLocation StartLoc,
12932 SourceLocation LParenLoc,
12933 SourceLocation EndLoc) {
12934 MappableVarListInfo MVLI(VarList);
12935 checkMappableExpressionList(*this, DSAStack, OMPC_to, MVLI, StartLoc);
12936 if (MVLI.ProcessedVarList.empty())
12937 return nullptr;
12938
12939 return OMPToClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12940 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12941 MVLI.VarComponents);
12942}
Samuel Antaoec172c62016-05-26 17:49:04 +000012943
12944OMPClause *Sema::ActOnOpenMPFromClause(ArrayRef<Expr *> VarList,
12945 SourceLocation StartLoc,
12946 SourceLocation LParenLoc,
12947 SourceLocation EndLoc) {
12948 MappableVarListInfo MVLI(VarList);
12949 checkMappableExpressionList(*this, DSAStack, OMPC_from, MVLI, StartLoc);
12950 if (MVLI.ProcessedVarList.empty())
12951 return nullptr;
12952
12953 return OMPFromClause::Create(Context, StartLoc, LParenLoc, EndLoc,
12954 MVLI.ProcessedVarList, MVLI.VarBaseDeclarations,
12955 MVLI.VarComponents);
12956}
Carlo Bertolli2404b172016-07-13 15:37:16 +000012957
12958OMPClause *Sema::ActOnOpenMPUseDevicePtrClause(ArrayRef<Expr *> VarList,
12959 SourceLocation StartLoc,
12960 SourceLocation LParenLoc,
12961 SourceLocation EndLoc) {
Samuel Antaocc10b852016-07-28 14:23:26 +000012962 MappableVarListInfo MVLI(VarList);
12963 SmallVector<Expr *, 8> PrivateCopies;
12964 SmallVector<Expr *, 8> Inits;
12965
Carlo Bertolli2404b172016-07-13 15:37:16 +000012966 for (auto &RefExpr : VarList) {
12967 assert(RefExpr && "NULL expr in OpenMP use_device_ptr clause.");
12968 SourceLocation ELoc;
12969 SourceRange ERange;
12970 Expr *SimpleRefExpr = RefExpr;
12971 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
12972 if (Res.second) {
12973 // It will be analyzed later.
Samuel Antaocc10b852016-07-28 14:23:26 +000012974 MVLI.ProcessedVarList.push_back(RefExpr);
12975 PrivateCopies.push_back(nullptr);
12976 Inits.push_back(nullptr);
Carlo Bertolli2404b172016-07-13 15:37:16 +000012977 }
12978 ValueDecl *D = Res.first;
12979 if (!D)
12980 continue;
12981
12982 QualType Type = D->getType();
Samuel Antaocc10b852016-07-28 14:23:26 +000012983 Type = Type.getNonReferenceType().getUnqualifiedType();
12984
12985 auto *VD = dyn_cast<VarDecl>(D);
12986
12987 // Item should be a pointer or reference to pointer.
12988 if (!Type->isPointerType()) {
Carlo Bertolli2404b172016-07-13 15:37:16 +000012989 Diag(ELoc, diag::err_omp_usedeviceptr_not_a_pointer)
12990 << 0 << RefExpr->getSourceRange();
12991 continue;
12992 }
Samuel Antaocc10b852016-07-28 14:23:26 +000012993
12994 // Build the private variable and the expression that refers to it.
12995 auto VDPrivate = buildVarDecl(*this, ELoc, Type, D->getName(),
12996 D->hasAttrs() ? &D->getAttrs() : nullptr);
12997 if (VDPrivate->isInvalidDecl())
12998 continue;
12999
13000 CurContext->addDecl(VDPrivate);
13001 auto VDPrivateRefExpr = buildDeclRefExpr(
13002 *this, VDPrivate, RefExpr->getType().getUnqualifiedType(), ELoc);
13003
13004 // Add temporary variable to initialize the private copy of the pointer.
13005 auto *VDInit =
13006 buildVarDecl(*this, RefExpr->getExprLoc(), Type, ".devptr.temp");
13007 auto *VDInitRefExpr = buildDeclRefExpr(*this, VDInit, RefExpr->getType(),
13008 RefExpr->getExprLoc());
13009 AddInitializerToDecl(VDPrivate,
13010 DefaultLvalueConversion(VDInitRefExpr).get(),
Richard Smith3beb7c62017-01-12 02:27:38 +000013011 /*DirectInit=*/false);
Samuel Antaocc10b852016-07-28 14:23:26 +000013012
13013 // If required, build a capture to implement the privatization initialized
13014 // with the current list item value.
13015 DeclRefExpr *Ref = nullptr;
13016 if (!VD)
13017 Ref = buildCapture(*this, D, SimpleRefExpr, /*WithInit=*/true);
13018 MVLI.ProcessedVarList.push_back(VD ? RefExpr->IgnoreParens() : Ref);
13019 PrivateCopies.push_back(VDPrivateRefExpr);
13020 Inits.push_back(VDInitRefExpr);
13021
13022 // We need to add a data sharing attribute for this variable to make sure it
13023 // is correctly captured. A variable that shows up in a use_device_ptr has
13024 // similar properties of a first private variable.
13025 DSAStack->addDSA(D, RefExpr->IgnoreParens(), OMPC_firstprivate, Ref);
13026
13027 // Create a mappable component for the list item. List items in this clause
13028 // only need a component.
13029 MVLI.VarBaseDeclarations.push_back(D);
13030 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13031 MVLI.VarComponents.back().push_back(
13032 OMPClauseMappableExprCommon::MappableComponent(SimpleRefExpr, D));
Carlo Bertolli2404b172016-07-13 15:37:16 +000013033 }
13034
Samuel Antaocc10b852016-07-28 14:23:26 +000013035 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli2404b172016-07-13 15:37:16 +000013036 return nullptr;
13037
Samuel Antaocc10b852016-07-28 14:23:26 +000013038 return OMPUseDevicePtrClause::Create(
13039 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13040 PrivateCopies, Inits, MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli2404b172016-07-13 15:37:16 +000013041}
Carlo Bertolli70594e92016-07-13 17:16:49 +000013042
13043OMPClause *Sema::ActOnOpenMPIsDevicePtrClause(ArrayRef<Expr *> VarList,
13044 SourceLocation StartLoc,
13045 SourceLocation LParenLoc,
13046 SourceLocation EndLoc) {
Samuel Antao6890b092016-07-28 14:25:09 +000013047 MappableVarListInfo MVLI(VarList);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013048 for (auto &RefExpr : VarList) {
Kelvin Li84376252016-12-14 15:39:58 +000013049 assert(RefExpr && "NULL expr in OpenMP is_device_ptr clause.");
Carlo Bertolli70594e92016-07-13 17:16:49 +000013050 SourceLocation ELoc;
13051 SourceRange ERange;
13052 Expr *SimpleRefExpr = RefExpr;
13053 auto Res = getPrivateItem(*this, SimpleRefExpr, ELoc, ERange);
13054 if (Res.second) {
13055 // It will be analyzed later.
Samuel Antao6890b092016-07-28 14:25:09 +000013056 MVLI.ProcessedVarList.push_back(RefExpr);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013057 }
13058 ValueDecl *D = Res.first;
13059 if (!D)
13060 continue;
13061
13062 QualType Type = D->getType();
13063 // item should be a pointer or array or reference to pointer or array
13064 if (!Type.getNonReferenceType()->isPointerType() &&
13065 !Type.getNonReferenceType()->isArrayType()) {
13066 Diag(ELoc, diag::err_omp_argument_type_isdeviceptr)
13067 << 0 << RefExpr->getSourceRange();
13068 continue;
13069 }
Samuel Antao6890b092016-07-28 14:25:09 +000013070
13071 // Check if the declaration in the clause does not show up in any data
13072 // sharing attribute.
13073 auto DVar = DSAStack->getTopDSA(D, false);
13074 if (isOpenMPPrivate(DVar.CKind)) {
13075 Diag(ELoc, diag::err_omp_variable_in_given_clause_and_dsa)
13076 << getOpenMPClauseName(DVar.CKind)
13077 << getOpenMPClauseName(OMPC_is_device_ptr)
13078 << getOpenMPDirectiveName(DSAStack->getCurrentDirective());
13079 ReportOriginalDSA(*this, DSAStack, D, DVar);
13080 continue;
13081 }
13082
13083 Expr *ConflictExpr;
13084 if (DSAStack->checkMappableExprComponentListsForDecl(
David Majnemer9d168222016-08-05 17:44:54 +000013085 D, /*CurrentRegionOnly=*/true,
Samuel Antao6890b092016-07-28 14:25:09 +000013086 [&ConflictExpr](
13087 OMPClauseMappableExprCommon::MappableExprComponentListRef R,
13088 OpenMPClauseKind) -> bool {
13089 ConflictExpr = R.front().getAssociatedExpression();
13090 return true;
13091 })) {
13092 Diag(ELoc, diag::err_omp_map_shared_storage) << RefExpr->getSourceRange();
13093 Diag(ConflictExpr->getExprLoc(), diag::note_used_here)
13094 << ConflictExpr->getSourceRange();
13095 continue;
13096 }
13097
13098 // Store the components in the stack so that they can be used to check
13099 // against other clauses later on.
13100 OMPClauseMappableExprCommon::MappableComponent MC(SimpleRefExpr, D);
13101 DSAStack->addMappableExpressionComponents(
13102 D, MC, /*WhereFoundClauseKind=*/OMPC_is_device_ptr);
13103
13104 // Record the expression we've just processed.
13105 MVLI.ProcessedVarList.push_back(SimpleRefExpr);
13106
13107 // Create a mappable component for the list item. List items in this clause
13108 // only need a component. We use a null declaration to signal fields in
13109 // 'this'.
13110 assert((isa<DeclRefExpr>(SimpleRefExpr) ||
13111 isa<CXXThisExpr>(cast<MemberExpr>(SimpleRefExpr)->getBase())) &&
13112 "Unexpected device pointer expression!");
13113 MVLI.VarBaseDeclarations.push_back(
13114 isa<DeclRefExpr>(SimpleRefExpr) ? D : nullptr);
13115 MVLI.VarComponents.resize(MVLI.VarComponents.size() + 1);
13116 MVLI.VarComponents.back().push_back(MC);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013117 }
13118
Samuel Antao6890b092016-07-28 14:25:09 +000013119 if (MVLI.ProcessedVarList.empty())
Carlo Bertolli70594e92016-07-13 17:16:49 +000013120 return nullptr;
13121
Samuel Antao6890b092016-07-28 14:25:09 +000013122 return OMPIsDevicePtrClause::Create(
13123 Context, StartLoc, LParenLoc, EndLoc, MVLI.ProcessedVarList,
13124 MVLI.VarBaseDeclarations, MVLI.VarComponents);
Carlo Bertolli70594e92016-07-13 17:16:49 +000013125}